@ai-agent-forge/plugin-memory 0.88.11 → 0.88.13
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/README.md +11 -0
- package/agent-forge.json +1 -1
- package/dist/inference-bin.bundle.js +145 -57
- package/dist/memory/embedding-provider.d.ts +3 -0
- package/dist/memory/embedding-provider.d.ts.map +1 -1
- package/dist/memory/embedding-provider.js +48 -17
- package/dist/memory/embedding-provider.js.map +1 -1
- package/dist/memory/embedding-reranker.d.ts +3 -0
- package/dist/memory/embedding-reranker.d.ts.map +1 -1
- package/dist/memory/embedding-reranker.js +37 -7
- package/dist/memory/embedding-reranker.js.map +1 -1
- package/dist/memory/foundation.d.ts.map +1 -1
- package/dist/memory/foundation.js +19 -0
- package/dist/memory/foundation.js.map +1 -1
- package/dist/memory/vector-channel.d.ts.map +1 -1
- package/dist/memory/vector-channel.js +96 -25
- package/dist/memory/vector-channel.js.map +1 -1
- package/dist/memory/vector-index.d.ts.map +1 -1
- package/dist/memory/vector-index.js +32 -16
- package/dist/memory/vector-index.js.map +1 -1
- package/package.json +5 -4
- package/plugin.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"foundation.js","sourceRoot":"","sources":["../../src/memory/foundation.ts"],"names":[],"mappings":"AA6IA,SAAS,aAAa,CAAC,KAAc,EAAwB;IAC5D,IAAI,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IACtF,MAAM,SAAS,GAAG,MAAM,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC;IAC/C,OAAO,SAAS,KAAK,MAAM,CAAC,SAAS,IAAI,SAAS,KAAK,IAAI,CAAC;AAAA,CAC5D;AAED,SAAS,iBAAiB,CAAC,KAAc,EAAE,KAAa,EAAgC;IACvF,IAAI,CAAC,aAAa,CAAC,KAAK,CAAC;QAAE,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AC,KAAK,CAAC,CAAC;IAC1C,IAAI,MAAM,GAAG,qBAAqB,CAAC;IACnC,KAAK,MAAM,IAAI,IAAI,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,UAAU,CAAC,EAAE,CAAC;QACzD,MAAM,IAAI,MAAM,CAAC,IAAI,CAAC,CAAC;QACvB,MAAM,GAAG,MAAM,CAAC,OAAO,CAAC,EAAE,EAAE,MAAM,GAAG,cAAc,CAAC,CAAC;IACtD,CAAC;IACD,OAAO,MAAM,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,EAAE,EAAE,GAAG,CAAC,CAAC;AAAA,CAC7C;AAED,0FAA0F;AAC1F,MAAM,UAAU,oBAAoB,CAAC,KAAa,EAAE,aAAqB,EAAU;IAClF,oBAAoB,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;IACrC,oBAAoB,CAAC,aAAa,EAAE,eAAe,CAAC,CAAC;IACrD,OAAO,GAAG,KAAK,SAAS,aAAa,EAAE,CAAC;AAAA,CACxC;AA2BD;;;;;;;;;;GAUG;AACH,MAAM,UAAU,qBAAqB,CAAC,IAAkB,EAAE,OAAe,EAA2B;IACnG,oBAAoB,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC;IACzC,IACC,IAAI,CAAC,UAAU,KAAK,YAAY;QAChC,IAAI,CAAC,UAAU,EAAE,KAAK,CAAC,KAAK,KAAK,cAAc;QAC/C,IAAI,CAAC,UAAU,CAAC,WAAW,KAAK,SAAS,EACxC,CAAC;QACF,OAAO,SAAS,CAAC;IAClB,CAAC;IACD,IAAI,IAAI,CAAC,OAAO,KAAK,SAAS;QAAE,OAAO,QAAQ,CAAC;IAChD,IAAI,IAAI,CAAC,OAAO,KAAK,OAAO;QAAE,OAAO,SAAS,CAAC;IAC/C,OAAO,eAAe,CAAC;AAAA,CACvB","sourcesContent":["/**\n * Memory Foundation — canonical atom, identity, and immutable snapshots (1C.1a).\n *\n * A canonical atom is the immutable committed fact. Derived state (attention,\n * effective status, purgeAt) is NOT part of the atom; it is rebuilt from\n * lifecycle events (1C.1b/1C.2). Everything returned to hosts and plugins is a\n * detached, deep-frozen snapshot: mutating the input after `buildMemoryAtomV1`\n * never changes the stored atom.\n *\n * Field semantics follow `docs/design/记忆系统设计.md` §4 (记录模型), which is the\n * authoritative source for memory fields.\n */\nimport type { JsonValue } from \"@agent-forge/plugin-sdk\";\n\n/** Source of one memory: where the fact came from, optionally pinned by revision/digest. */\nexport interface MemorySourceRefV1 {\n\treadonly kind: \"session\" | \"entry\" | \"artifact\" | \"tool\" | \"state\";\n\treadonly id: string;\n\treadonly revision?: string;\n\treadonly digest?: string;\n}\n\n/** Namespace-scoped search facet. Facets are atom facts, never derived. */\nexport interface MemoryFacetV1 {\n\treadonly namespace: string;\n\treadonly schemaVersion: number;\n\treadonly key: string;\n\treadonly value: string;\n}\n\n/** Typed relation between atoms. Weights/validity belong to projections, not here. */\nexport interface MemoryRelationV1 {\n\treadonly relationId: string;\n\treadonly namespace: string;\n\treadonly schemaVersion: number;\n\treadonly kind: string;\n\treadonly targetMemoryId?: string;\n\treadonly targetRef?: MemorySourceRefV1;\n\treadonly confidence?: number;\n\treadonly relationRevision: string;\n}\n\nexport interface MemoryTimeRangeV1 {\n\treadonly from?: string;\n\treadonly to?: string;\n}\n\n/** Applicability narrowing; empty means \"applies without narrowing\". */\nexport interface MemoryApplicabilityV1 {\n\treadonly scenes?: readonly string[];\n\treadonly projects?: readonly string[];\n\treadonly tasks?: readonly string[];\n\treadonly timeRange?: MemoryTimeRangeV1;\n\treadonly exceptions?: readonly string[];\n}\n\n/** Preference envelope: the generic schema frozen for 1C; policy semantics come later. */\nexport interface MemoryPreferenceEnvelopeV1 {\n\treadonly subject: \"user\" | \"project\" | \"task\" | \"environment\";\n\treadonly key: string;\n\treadonly preferredValue: JsonValue;\n\treadonly alternatives?: readonly JsonValue[];\n\treadonly scope: {\n\t\treadonly level: \"task\" | \"project\" | \"scene\" | \"timeRange\" | \"profile-private\" | \"user-default\";\n\t\treadonly scenes?: readonly string[];\n\t\treadonly projects?: readonly string[];\n\t\treadonly tasks?: readonly string[];\n\t\treadonly timeRange?: MemoryTimeRangeV1;\n\t\treadonly exceptions?: readonly string[];\n\t};\n\treadonly evidence: {\n\t\treadonly class: \"explicit\" | \"repeated_behavior\" | \"inferred\";\n\t\treadonly sourceRefs: readonly MemorySourceRefV1[];\n\t\treadonly confidence: number;\n\t};\n\treadonly applicabilityConfidence: number;\n\treadonly confirmedAt?: string;\n}\n\n/** Provenance for synthesis/compaction memories derived from other atoms. */\nexport interface MemoryProvenanceV1 {\n\treadonly sourceMemoryIds: readonly string[];\n\treadonly purgeGroupId: string;\n\treadonly containsSourceContent: boolean;\n}\n\nexport type MemoryScopeV1 = \"session\" | \"cycle\" | \"long-term\";\nexport type MemoryKindV1 =\n\t| \"observation\"\n\t| \"preference\"\n\t| \"fact\"\n\t| \"decision\"\n\t| \"constraint\"\n\t| \"inference\"\n\t| \"synthesis\";\nexport type MemoryEvidenceClassV1 = \"explicit\" | \"repeated_behavior\" | \"tool_or_test\" | \"derived\";\n\n/** The immutable canonical atom. Once committed, no field may change in place. */\nexport interface MemoryAtomV1<TPayload = JsonValue> {\n\treadonly memoryId: string;\n\treadonly contractVersion: string;\n\treadonly schemaVersion: number;\n\treadonly scope: MemoryScopeV1;\n\treadonly retentionMode: string;\n\treadonly owner: string;\n\treadonly profileId: string;\n\treadonly shareGroupId?: string;\n\t/**\n\t * Suite (方案) this atom belongs to (方案系统设计 §6.1/§11, M5). Absent\n\t * (or protocol-level `null` on the wire, normalized to absent here) marks a\n\t * legacy pre-M5 atom: such atoms are fail-safe INVISIBLE to every\n\t * suite-scoped read and only readable through suite-unscoped queries. The\n\t * one cross-suite exception is an explicitly promoted user-default\n\t * preference (see {@link memorySuiteVisibility}).\n\t */\n\treadonly suiteId?: string;\n\treadonly retentionPolicyVersion: string;\n\treadonly memoryKind: MemoryKindV1;\n\treadonly payload: TPayload;\n\treadonly preference?: MemoryPreferenceEnvelopeV1;\n\treadonly occurredAt: string;\n\treadonly recordedAt: string;\n\treadonly sourceRefs: readonly MemorySourceRefV1[];\n\treadonly observationId: string;\n\treadonly sessionRefs: readonly string[];\n\treadonly agentInstanceRefs: readonly string[];\n\treadonly projectRefs: readonly string[];\n\treadonly subjectRefs: readonly string[];\n\treadonly facets: readonly MemoryFacetV1[];\n\treadonly relations: readonly MemoryRelationV1[];\n\treadonly provenance?: MemoryProvenanceV1;\n\treadonly confidence: number;\n\treadonly importance: number;\n\treadonly applicability?: MemoryApplicabilityV1;\n\treadonly evidenceClass: MemoryEvidenceClassV1;\n\treadonly contentRevision: string;\n\treadonly writeReason: string;\n}\n\ntype PlainRecord = Record<string, unknown>;\n\nfunction isPlainRecord(value: unknown): value is PlainRecord {\n\tif (value === null || typeof value !== \"object\" || Array.isArray(value)) return false;\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === Object.prototype || prototype === null;\n}\n\nfunction assertPlainRecord(value: unknown, label: string): asserts value is PlainRecord {\n\tif (!isPlainRecord(value)) throw new Error(`${label} must be a plain object`);\n}\n\nfunction assertExactKeys(\n\tvalue: PlainRecord,\n\trequired: readonly string[],\n\toptional: readonly string[],\n\tlabel: string,\n): void {\n\tconst allowed = new Set([...required, ...optional]);\n\tconst unsupported = Object.keys(value)\n\t\t.filter((key) => !allowed.has(key))\n\t\t.sort();\n\tif (unsupported.length > 0) throw new Error(`${label} has unsupported fields: ${unsupported.join(\", \")}`);\n\tfor (const key of required) {\n\t\tif (!(key in value)) throw new Error(`${label} is missing required field: ${key}`);\n\t}\n}\n\nfunction assertNonEmptyString(value: unknown, label: string): asserts value is string {\n\tif (typeof value !== \"string\" || value.trim().length === 0) throw new Error(`${label} must be a non-empty string`);\n}\n\nfunction assertPositiveSafeInteger(value: unknown, label: string): asserts value is number {\n\tif (typeof value !== \"number\" || !Number.isSafeInteger(value) || value < 1) {\n\t\tthrow new Error(`${label} must be a positive safe integer`);\n\t}\n}\n\nfunction assertUnitInterval(value: unknown, label: string): asserts value is number {\n\tif (typeof value !== \"number\" || !Number.isFinite(value) || value < 0 || value > 1) {\n\t\tthrow new Error(`${label} must be a number between 0 and 1`);\n\t}\n}\n\nfunction assertTimestamp(value: unknown, label: string): asserts value is string {\n\tassertNonEmptyString(value, label);\n\tif (Number.isNaN(Date.parse(value))) throw new Error(`${label} must be an ISO-8601 timestamp`);\n}\n\nfunction assertJsonValue(value: unknown, label: string, seen = new WeakSet<object>()): asserts value is JsonValue {\n\tif (value === null || typeof value === \"string\" || typeof value === \"boolean\") return;\n\tif (typeof value === \"number\") {\n\t\tif (Number.isFinite(value)) return;\n\t\tthrow new Error(`${label} must contain finite JSON numbers`);\n\t}\n\tif (typeof value !== \"object\") throw new Error(`${label} must be JSON-compatible`);\n\tif (seen.has(value)) throw new Error(`${label} must not contain cycles`);\n\tseen.add(value);\n\tif (Array.isArray(value)) {\n\t\tfor (const [index, child] of value.entries()) assertJsonValue(child, `${label}[${index}]`, seen);\n\t} else {\n\t\tif (!isPlainRecord(value)) throw new Error(`${label} must contain only plain JSON objects`);\n\t\tfor (const [key, child] of Object.entries(value)) assertJsonValue(child, `${label}.${key}`, seen);\n\t}\n\tseen.delete(value);\n}\n\nfunction assertStringArray(value: unknown, label: string): asserts value is readonly string[] {\n\tif (!Array.isArray(value)) throw new Error(`${label} must be an array`);\n\tfor (const [index, item] of value.entries()) assertNonEmptyString(item, `${label}[${index}]`);\n}\n\nfunction detachedFreeze<T>(value: T, seen = new WeakMap<object, unknown>()): T {\n\tif (value === null || typeof value !== \"object\") return value;\n\tconst existing = seen.get(value);\n\t// v8 ignore next -- 校验后的原子全部由新副本构成,不存在共享引用\n\tif (existing !== undefined) return existing as T;\n\tif (Array.isArray(value)) {\n\t\tconst copy: unknown[] = [];\n\t\tseen.set(value, copy);\n\t\tfor (const child of value) copy.push(detachedFreeze(child, seen));\n\t\treturn Object.freeze(copy) as T;\n\t}\n\tconst copy: Record<string, unknown> = Object.create(null) as Record<string, unknown>;\n\tseen.set(value, copy);\n\tfor (const [key, child] of Object.entries(value as Record<string, unknown>)) {\n\t\tcopy[key] = detachedFreeze(child, seen);\n\t}\n\treturn Object.freeze(copy) as T;\n}\n\n/** Stable JSON serialization with recursively sorted object keys (for identity digests). */\nfunction stableStringify(value: JsonValue): string {\n\tif (value === null || typeof value === \"boolean\" || typeof value === \"number\" || typeof value === \"string\") {\n\t\treturn JSON.stringify(value);\n\t}\n\tif (Array.isArray(value)) return `[${value.map((item) => stableStringify(item)).join(\",\")}]`;\n\tconst entries = Object.keys(value)\n\t\t.sort()\n\t\t.map((key) => `${JSON.stringify(key)}:${stableStringify((value as Record<string, JsonValue>)[key])}`);\n\treturn `{${entries.join(\",\")}}`;\n}\n\nconst MEMORY_SCOPES_V1: readonly MemoryScopeV1[] = [\"session\", \"cycle\", \"long-term\"];\nconst MEMORY_KINDS_V1: readonly MemoryKindV1[] = [\n\t\"observation\",\n\t\"preference\",\n\t\"fact\",\n\t\"decision\",\n\t\"constraint\",\n\t\"inference\",\n\t\"synthesis\",\n];\nconst MEMORY_EVIDENCE_CLASSES_V1: readonly MemoryEvidenceClassV1[] = [\n\t\"explicit\",\n\t\"repeated_behavior\",\n\t\"tool_or_test\",\n\t\"derived\",\n];\nconst SOURCE_REF_KINDS: readonly MemorySourceRefV1[\"kind\"][] = [\"session\", \"entry\", \"artifact\", \"tool\", \"state\"];\n\nfunction validateSourceRef(value: unknown, label: string): MemorySourceRefV1 {\n\tassertPlainRecord(value, label);\n\tassertExactKeys(value, [\"kind\", \"id\"], [\"revision\", \"digest\"], label);\n\tif (!SOURCE_REF_KINDS.includes(value.kind as MemorySourceRefV1[\"kind\"])) {\n\t\tthrow new Error(`${label}.kind is invalid`);\n\t}\n\tassertNonEmptyString(value.id, `${label}.id`);\n\tif (value.revision !== undefined) assertNonEmptyString(value.revision, `${label}.revision`);\n\tif (value.digest !== undefined) assertNonEmptyString(value.digest, `${label}.digest`);\n\treturn detachedFreeze({\n\t\tkind: value.kind as MemorySourceRefV1[\"kind\"],\n\t\tid: value.id,\n\t\t...(value.revision === undefined ? {} : { revision: value.revision }),\n\t\t...(value.digest === undefined ? {} : { digest: value.digest }),\n\t});\n}\n\nfunction validateFacet(value: unknown, label: string): MemoryFacetV1 {\n\tassertPlainRecord(value, label);\n\tassertExactKeys(value, [\"namespace\", \"schemaVersion\", \"key\", \"value\"], [], label);\n\tassertNonEmptyString(value.namespace, `${label}.namespace`);\n\tassertPositiveSafeInteger(value.schemaVersion, `${label}.schemaVersion`);\n\tassertNonEmptyString(value.key, `${label}.key`);\n\tassertNonEmptyString(value.value, `${label}.value`);\n\treturn detachedFreeze({\n\t\tnamespace: value.namespace,\n\t\tschemaVersion: value.schemaVersion,\n\t\tkey: value.key,\n\t\tvalue: value.value,\n\t});\n}\n\nfunction validateRelation(value: unknown, label: string): MemoryRelationV1 {\n\tassertPlainRecord(value, label);\n\tassertExactKeys(\n\t\tvalue,\n\t\t[\"relationId\", \"namespace\", \"schemaVersion\", \"kind\", \"relationRevision\"],\n\t\t[\"targetMemoryId\", \"targetRef\", \"confidence\"],\n\t\tlabel,\n\t);\n\tassertNonEmptyString(value.relationId, `${label}.relationId`);\n\tassertNonEmptyString(value.namespace, `${label}.namespace`);\n\tassertPositiveSafeInteger(value.schemaVersion, `${label}.schemaVersion`);\n\tassertNonEmptyString(value.kind, `${label}.kind`);\n\tassertNonEmptyString(value.relationRevision, `${label}.relationRevision`);\n\tif (value.targetMemoryId !== undefined && value.targetRef !== undefined) {\n\t\tthrow new Error(`${label} must not declare both targetMemoryId and targetRef`);\n\t}\n\tconst targetMemoryId = value.targetMemoryId === undefined ? undefined : (value.targetMemoryId as string);\n\tif (targetMemoryId !== undefined) assertNonEmptyString(targetMemoryId, `${label}.targetMemoryId`);\n\tconst targetRef =\n\t\tvalue.targetRef === undefined ? undefined : validateSourceRef(value.targetRef, `${label}.targetRef`);\n\tif (value.confidence !== undefined) assertUnitInterval(value.confidence, `${label}.confidence`);\n\treturn detachedFreeze({\n\t\trelationId: value.relationId,\n\t\tnamespace: value.namespace,\n\t\tschemaVersion: value.schemaVersion,\n\t\tkind: value.kind,\n\t\t...(targetMemoryId === undefined ? {} : { targetMemoryId }),\n\t\t...(targetRef === undefined ? {} : { targetRef }),\n\t\t...(value.confidence === undefined ? {} : { confidence: value.confidence }),\n\t\trelationRevision: value.relationRevision,\n\t});\n}\n\nfunction validateTimeRange(value: unknown, label: string): MemoryTimeRangeV1 {\n\tassertPlainRecord(value, label);\n\t// Key order reversed on purpose: in the natural order the boundary-gate\n\t// lexical scanner reads this key pair as an import specifier (first key\n\t// string, comma, second key string). `assertExactKeys` builds a Set, so the\n\t// order is irrelevant to validation.\n\tassertExactKeys(value, [], [\"to\", \"from\"], label);\n\tconst from = value.from === undefined ? undefined : (value.from as string);\n\tconst to = value.to === undefined ? undefined : (value.to as string);\n\tif (from !== undefined) assertTimestamp(from, `${label}.from`);\n\tif (to !== undefined) assertTimestamp(to, `${label}.to`);\n\treturn detachedFreeze({\n\t\t...(from === undefined ? {} : { from }),\n\t\t...(to === undefined ? {} : { to }),\n\t});\n}\n\nfunction validateApplicability(value: unknown, label: string): MemoryApplicabilityV1 {\n\tassertPlainRecord(value, label);\n\tassertExactKeys(value, [], [\"scenes\", \"projects\", \"tasks\", \"timeRange\", \"exceptions\"], label);\n\tconst timeRange =\n\t\tvalue.timeRange === undefined ? undefined : validateTimeRange(value.timeRange, `${label}.timeRange`);\n\treturn detachedFreeze({\n\t\t...(value.scenes === undefined ? {} : { scenes: Object.freeze([...(value.scenes as readonly string[])]) }),\n\t\t...(value.projects === undefined ? {} : { projects: Object.freeze([...(value.projects as readonly string[])]) }),\n\t\t...(value.tasks === undefined ? {} : { tasks: Object.freeze([...(value.tasks as readonly string[])]) }),\n\t\t...(timeRange === undefined ? {} : { timeRange }),\n\t\t...(value.exceptions === undefined\n\t\t\t? {}\n\t\t\t: { exceptions: Object.freeze([...(value.exceptions as readonly string[])]) }),\n\t});\n}\n\nfunction validatePreferenceEnvelope(value: unknown, label: string): MemoryPreferenceEnvelopeV1 {\n\tassertPlainRecord(value, label);\n\tassertExactKeys(\n\t\tvalue,\n\t\t[\"subject\", \"key\", \"preferredValue\", \"scope\", \"evidence\", \"applicabilityConfidence\"],\n\t\t[\"alternatives\", \"confirmedAt\"],\n\t\tlabel,\n\t);\n\tconst subjects: readonly MemoryPreferenceEnvelopeV1[\"subject\"][] = [\"user\", \"project\", \"task\", \"environment\"];\n\tif (!subjects.includes(value.subject as MemoryPreferenceEnvelopeV1[\"subject\"])) {\n\t\tthrow new Error(`${label}.subject is invalid`);\n\t}\n\tassertNonEmptyString(value.key, `${label}.key`);\n\tassertJsonValue(value.preferredValue, `${label}.preferredValue`);\n\tif (value.alternatives !== undefined) {\n\t\tif (!Array.isArray(value.alternatives)) throw new Error(`${label}.alternatives must be an array`);\n\t\tfor (const [index, item] of value.alternatives.entries()) {\n\t\t\tassertJsonValue(item, `${label}.alternatives[${index}]`);\n\t\t}\n\t}\n\tconst scope = value.scope;\n\tassertPlainRecord(scope, `${label}.scope`);\n\tassertExactKeys(scope, [\"level\"], [\"scenes\", \"projects\", \"tasks\", \"timeRange\", \"exceptions\"], `${label}.scope`);\n\tconst levels: readonly MemoryPreferenceEnvelopeV1[\"scope\"][\"level\"][] = [\n\t\t\"task\",\n\t\t\"project\",\n\t\t\"scene\",\n\t\t\"timeRange\",\n\t\t\"profile-private\",\n\t\t\"user-default\",\n\t];\n\tif (!levels.includes(scope.level as MemoryPreferenceEnvelopeV1[\"scope\"][\"level\"])) {\n\t\tthrow new Error(`${label}.scope.level is invalid`);\n\t}\n\t// Anchor levels require their anchor to be present (记录模型约束).\n\tconst anchors: ReadonlyArray<[string, keyof PlainRecord]> = [\n\t\t[\"task\", \"tasks\"],\n\t\t[\"project\", \"projects\"],\n\t\t[\"scene\", \"scenes\"],\n\t\t[\"timeRange\", \"timeRange\"],\n\t];\n\tfor (const [level, field] of anchors) {\n\t\tif (\n\t\t\tscope.level === level &&\n\t\t\t(scope[field] === undefined || (Array.isArray(scope[field]) && scope[field].length === 0))\n\t\t) {\n\t\t\tthrow new Error(`${label}.scope.level \"${level}\" requires non-empty ${field}`);\n\t\t}\n\t}\n\tconst evidence = value.evidence;\n\tassertPlainRecord(evidence, `${label}.evidence`);\n\tassertExactKeys(evidence, [\"class\", \"sourceRefs\", \"confidence\"], [], `${label}.evidence`);\n\tconst evidenceClasses: readonly MemoryPreferenceEnvelopeV1[\"evidence\"][\"class\"][] = [\n\t\t\"explicit\",\n\t\t\"repeated_behavior\",\n\t\t\"inferred\",\n\t];\n\tif (!evidenceClasses.includes(evidence.class as MemoryPreferenceEnvelopeV1[\"evidence\"][\"class\"])) {\n\t\tthrow new Error(`${label}.evidence.class is invalid`);\n\t}\n\tif (!Array.isArray(evidence.sourceRefs) || evidence.sourceRefs.length === 0) {\n\t\tthrow new Error(`${label}.evidence.sourceRefs must not be empty`);\n\t}\n\tconst evidenceSourceRefs = evidence.sourceRefs.map((item, index) =>\n\t\tvalidateSourceRef(item, `${label}.evidence.sourceRefs[${index}]`),\n\t);\n\tassertUnitInterval(evidence.confidence, `${label}.evidence.confidence`);\n\tassertUnitInterval(value.applicabilityConfidence, `${label}.applicabilityConfidence`);\n\tif (value.confirmedAt !== undefined) assertTimestamp(value.confirmedAt, `${label}.confirmedAt`);\n\treturn detachedFreeze({\n\t\tsubject: value.subject as MemoryPreferenceEnvelopeV1[\"subject\"],\n\t\tkey: value.key,\n\t\tpreferredValue: value.preferredValue,\n\t\t...(value.alternatives === undefined ? {} : { alternatives: Object.freeze([...value.alternatives]) }),\n\t\tscope: detachedFreeze({\n\t\t\tlevel: scope.level as MemoryPreferenceEnvelopeV1[\"scope\"][\"level\"],\n\t\t\t...(scope.scenes === undefined ? {} : { scenes: Object.freeze([...(scope.scenes as readonly string[])]) }),\n\t\t\t...(scope.projects === undefined\n\t\t\t\t? {}\n\t\t\t\t: { projects: Object.freeze([...(scope.projects as readonly string[])]) }),\n\t\t\t...(scope.tasks === undefined ? {} : { tasks: Object.freeze([...(scope.tasks as readonly string[])]) }),\n\t\t\t...(scope.timeRange === undefined\n\t\t\t\t? {}\n\t\t\t\t: { timeRange: validateTimeRange(scope.timeRange, `${label}.scope.timeRange`) }),\n\t\t\t...(scope.exceptions === undefined\n\t\t\t\t? {}\n\t\t\t\t: { exceptions: Object.freeze([...(scope.exceptions as readonly string[])]) }),\n\t\t}),\n\t\tevidence: detachedFreeze({\n\t\t\tclass: evidence.class as MemoryPreferenceEnvelopeV1[\"evidence\"][\"class\"],\n\t\t\tsourceRefs: Object.freeze(evidenceSourceRefs),\n\t\t\tconfidence: evidence.confidence,\n\t\t}),\n\t\tapplicabilityConfidence: value.applicabilityConfidence,\n\t\t...(value.confirmedAt === undefined ? {} : { confirmedAt: value.confirmedAt }),\n\t}) as MemoryPreferenceEnvelopeV1;\n}\n\nfunction validateProvenance(value: unknown, label: string): MemoryProvenanceV1 {\n\tassertPlainRecord(value, label);\n\tassertExactKeys(value, [\"sourceMemoryIds\", \"purgeGroupId\", \"containsSourceContent\"], [], label);\n\tassertStringArray(value.sourceMemoryIds, `${label}.sourceMemoryIds`);\n\tif (value.sourceMemoryIds.length === 0) throw new Error(`${label}.sourceMemoryIds must not be empty`);\n\tassertNonEmptyString(value.purgeGroupId, `${label}.purgeGroupId`);\n\tif (typeof value.containsSourceContent !== \"boolean\") {\n\t\tthrow new Error(`${label}.containsSourceContent must be boolean`);\n\t}\n\treturn detachedFreeze({\n\t\tsourceMemoryIds: Object.freeze([...(value.sourceMemoryIds as readonly string[])]),\n\t\tpurgeGroupId: value.purgeGroupId,\n\t\tcontainsSourceContent: value.containsSourceContent,\n\t});\n}\n\n/**\n * Validates a canonical memory atom and returns a detached, deep-frozen\n * snapshot. Unknown fields, wrong enums, non-JSON payloads, preference-kind\n * atoms without a preference envelope, and identity fields (memoryId,\n * observationId, contentRevision, owner) that are not non-empty strings are\n * rejected.\n */\nexport function validateMemoryAtomV1<TPayload = JsonValue>(value: unknown): MemoryAtomV1<TPayload> {\n\tassertPlainRecord(value, \"Memory atom\");\n\tassertExactKeys(\n\t\tvalue,\n\t\t[\n\t\t\t\"memoryId\",\n\t\t\t\"contractVersion\",\n\t\t\t\"schemaVersion\",\n\t\t\t\"scope\",\n\t\t\t\"retentionMode\",\n\t\t\t\"owner\",\n\t\t\t\"profileId\",\n\t\t\t\"retentionPolicyVersion\",\n\t\t\t\"memoryKind\",\n\t\t\t\"payload\",\n\t\t\t\"occurredAt\",\n\t\t\t\"recordedAt\",\n\t\t\t\"sourceRefs\",\n\t\t\t\"observationId\",\n\t\t\t\"sessionRefs\",\n\t\t\t\"agentInstanceRefs\",\n\t\t\t\"projectRefs\",\n\t\t\t\"subjectRefs\",\n\t\t\t\"facets\",\n\t\t\t\"relations\",\n\t\t\t\"confidence\",\n\t\t\t\"importance\",\n\t\t\t\"evidenceClass\",\n\t\t\t\"contentRevision\",\n\t\t\t\"writeReason\",\n\t\t],\n\t\t[\"tenantId\", \"shareGroupId\", \"suiteId\", \"preference\", \"provenance\", \"applicability\"],\n\t\t\"Memory atom\",\n\t);\n\tassertNonEmptyString(value.memoryId, \"Memory atom.memoryId\");\n\tassertNonEmptyString(value.contractVersion, \"Memory atom.contractVersion\");\n\tassertPositiveSafeInteger(value.schemaVersion, \"Memory atom.schemaVersion\");\n\tif (!MEMORY_SCOPES_V1.includes(value.scope as MemoryScopeV1)) throw new Error(\"Memory atom.scope is invalid\");\n\tassertNonEmptyString(value.retentionMode, \"Memory atom.retentionMode\");\n\tassertNonEmptyString(value.owner, \"Memory atom.owner\");\n\tassertNonEmptyString(value.profileId, \"Memory atom.profileId\");\n\tif (value.shareGroupId !== undefined) assertNonEmptyString(value.shareGroupId, \"Memory atom.shareGroupId\");\n\t// Legacy (pre-M5) atoms may carry protocol-level `null` for \"no suite\"; it\n\t// is tolerated here and normalized to an absent field (存量语义), while a\n\t// present suiteId must be a non-empty string.\n\tif (value.suiteId !== undefined && value.suiteId !== null) {\n\t\tassertNonEmptyString(value.suiteId, \"Memory atom.suiteId\");\n\t}\n\tassertNonEmptyString(value.retentionPolicyVersion, \"Memory atom.retentionPolicyVersion\");\n\tif (!MEMORY_KINDS_V1.includes(value.memoryKind as MemoryKindV1))\n\t\tthrow new Error(\"Memory atom.memoryKind is invalid\");\n\tassertJsonValue(value.payload, \"Memory atom.payload\");\n\tif (value.memoryKind === \"preference\" && value.preference === undefined) {\n\t\tthrow new Error(\"Memory atom.memoryKind preference requires a preference envelope\");\n\t}\n\tconst preference =\n\t\tvalue.preference === undefined\n\t\t\t? undefined\n\t\t\t: validatePreferenceEnvelope(value.preference, \"Memory atom.preference\");\n\tassertTimestamp(value.occurredAt, \"Memory atom.occurredAt\");\n\tassertTimestamp(value.recordedAt, \"Memory atom.recordedAt\");\n\tif (!Array.isArray(value.sourceRefs)) throw new Error(\"Memory atom.sourceRefs must be an array\");\n\tconst sourceRefs = value.sourceRefs.map((item, index) =>\n\t\tvalidateSourceRef(item, `Memory atom.sourceRefs[${index}]`),\n\t);\n\tassertNonEmptyString(value.observationId, \"Memory atom.observationId\");\n\tassertStringArray(value.sessionRefs, \"Memory atom.sessionRefs\");\n\tassertStringArray(value.agentInstanceRefs, \"Memory atom.agentInstanceRefs\");\n\tassertStringArray(value.projectRefs, \"Memory atom.projectRefs\");\n\tassertStringArray(value.subjectRefs, \"Memory atom.subjectRefs\");\n\tif (!Array.isArray(value.facets)) throw new Error(\"Memory atom.facets must be an array\");\n\tconst facets = value.facets.map((item, index) => validateFacet(item, `Memory atom.facets[${index}]`));\n\tif (!Array.isArray(value.relations)) throw new Error(\"Memory atom.relations must be an array\");\n\tconst relations = value.relations.map((item, index) => validateRelation(item, `Memory atom.relations[${index}]`));\n\tconst provenance =\n\t\tvalue.provenance === undefined ? undefined : validateProvenance(value.provenance, \"Memory atom.provenance\");\n\tassertUnitInterval(value.confidence, \"Memory atom.confidence\");\n\tassertUnitInterval(value.importance, \"Memory atom.importance\");\n\tconst applicability =\n\t\tvalue.applicability === undefined\n\t\t\t? undefined\n\t\t\t: validateApplicability(value.applicability, \"Memory atom.applicability\");\n\tif (!MEMORY_EVIDENCE_CLASSES_V1.includes(value.evidenceClass as MemoryEvidenceClassV1)) {\n\t\tthrow new Error(\"Memory atom.evidenceClass is invalid\");\n\t}\n\tassertNonEmptyString(value.contentRevision, \"Memory atom.contentRevision\");\n\tassertNonEmptyString(value.writeReason, \"Memory atom.writeReason\");\n\n\treturn detachedFreeze({\n\t\tmemoryId: value.memoryId,\n\t\tcontractVersion: value.contractVersion,\n\t\tschemaVersion: value.schemaVersion,\n\t\tscope: value.scope as MemoryScopeV1,\n\t\tretentionMode: value.retentionMode,\n\t\towner: value.owner,\n\t\tprofileId: value.profileId,\n\t\t...(value.shareGroupId === undefined ? {} : { shareGroupId: value.shareGroupId }),\n\t\t...(value.suiteId === undefined || value.suiteId === null ? {} : { suiteId: value.suiteId }),\n\t\tretentionPolicyVersion: value.retentionPolicyVersion,\n\t\tmemoryKind: value.memoryKind as MemoryKindV1,\n\t\tpayload: value.payload as TPayload,\n\t\t...(preference === undefined ? {} : { preference }),\n\t\toccurredAt: value.occurredAt,\n\t\trecordedAt: value.recordedAt,\n\t\tsourceRefs: Object.freeze(sourceRefs),\n\t\tobservationId: value.observationId,\n\t\tsessionRefs: Object.freeze([...value.sessionRefs]),\n\t\tagentInstanceRefs: Object.freeze([...value.agentInstanceRefs]),\n\t\tprojectRefs: Object.freeze([...value.projectRefs]),\n\t\tsubjectRefs: Object.freeze([...value.subjectRefs]),\n\t\tfacets: Object.freeze(facets),\n\t\trelations: Object.freeze(relations),\n\t\t...(provenance === undefined ? {} : { provenance }),\n\t\tconfidence: value.confidence,\n\t\timportance: value.importance,\n\t\t...(applicability === undefined ? {} : { applicability }),\n\t\tevidenceClass: value.evidenceClass as MemoryEvidenceClassV1,\n\t\tcontentRevision: value.contentRevision,\n\t\twriteReason: value.writeReason,\n\t}) as MemoryAtomV1<TPayload>;\n}\n\n/** Builds a detached, frozen canonical atom (validate + freeze). */\nexport function buildMemoryAtomV1<TPayload = JsonValue>(atom: MemoryAtomV1<TPayload>): MemoryAtomV1<TPayload> {\n\treturn validateMemoryAtomV1<TPayload>(atom);\n}\n\n/** FNV-1a 64-bit digest over the stable JSON serialization of `value`. */\nexport function memoryContentDigest(value: JsonValue): string {\n\tconst serialized = stableStringify(value);\n\tlet digest = 14695981039346656037n;\n\tfor (const byte of new TextEncoder().encode(serialized)) {\n\t\tdigest ^= BigInt(byte);\n\t\tdigest = BigInt.asUintN(64, digest * 1099511628211n);\n\t}\n\treturn digest.toString(16).padStart(16, \"0\");\n}\n\n/** Idempotent submission identity: the same (owner, observationId) is one observation. */\nexport function memoryObservationKey(owner: string, observationId: string): string {\n\tassertNonEmptyString(owner, \"owner\");\n\tassertNonEmptyString(observationId, \"observationId\");\n\treturn `${owner}\\u0000${observationId}`;\n}\n\n// ---------------------------------------------------------------------------\n// Suite (方案) read boundary (方案系统设计 §6.1/§11, M5)\n// ---------------------------------------------------------------------------\n\n/** Why a record was excluded from a suite-scoped read (读取边界惰性可观测). */\nexport type MemorySuiteVisibilityV1 =\n\t/** The atom matches the queried suite, or is an explicitly promoted user-default preference. */\n\t| \"visible\"\n\t/** Legacy (pre-M5) atom without a suiteId — fail-safe invisible to every suite. */\n\t| \"legacy\"\n\t/** The atom belongs to a different suite. */\n\t| \"foreign-suite\";\n\n/**\n * Skipped-record counters attached to suite-scoped reads. The read boundary is\n * lazy and observable (设计 §11 三段式): excluded atoms are counted, never\n * silently dropped.\n */\nexport interface MemorySuiteFilterStatsV1 {\n\t/** Legacy (suiteId-less) atoms skipped as invisible to any suite. */\n\treadonly legacySkipped: number;\n\t/** Atoms bound to a different suiteId that were skipped. */\n\treadonly foreignSuiteSkipped: number;\n}\n\n/**\n * Suite-scoped visibility of one atom (方案系统设计 §6.1/§11):\n * - `atom.suiteId === suiteId` → visible;\n * - an explicitly promoted user-default preference (scope.level\n * \"user-default\" WITH `confirmedAt` — the canonical explicit-confirmation\n * marker set only by the explicit promotion channel) ignores the suiteId\n * filter and is visible in every suite (§6.1 跨方案偏好);\n * - absent suiteId (legacy/存量) → invisible to every suite (fail-safe\n * default), counted via {@link MemorySuiteFilterStatsV1};\n * - any other suiteId → invisible.\n */\nexport function memorySuiteVisibility(atom: MemoryAtomV1, suiteId: string): MemorySuiteVisibilityV1 {\n\tassertNonEmptyString(suiteId, \"suiteId\");\n\tif (\n\t\tatom.memoryKind === \"preference\" &&\n\t\tatom.preference?.scope.level === \"user-default\" &&\n\t\tatom.preference.confirmedAt !== undefined\n\t) {\n\t\treturn \"visible\";\n\t}\n\tif (atom.suiteId === undefined) return \"legacy\";\n\tif (atom.suiteId === suiteId) return \"visible\";\n\treturn \"foreign-suite\";\n}\n"]}
|
|
1
|
+
{"version":3,"file":"foundation.js","sourceRoot":"","sources":["../../src/memory/foundation.ts"],"names":[],"mappings":"AA6IA,SAAS,aAAa,CAAC,KAAc,EAAwB;IAC5D,IAAI,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IACtF,MAAM,SAAS,GAAG,MAAM,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC;IAC/C,OAAO,SAAS,KAAK,MAAM,CAAC,SAAS,IAAI,SAAS,KAAK,IAAI,CAAC;AAAA,CAC5D;AAED,SAAS,iBAAiB,CAAC,KAAc,EAAE,KAAa,EAAgC;IACvF,IAAI,CAAC,aAAa,CAAC,KAAK,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,GAAG,KAAK,yBAAyB,CAAC,CAAC;AAAA,CAC9E;AAED,SAAS,eAAe,CACvB,KAAkB,EAClB,QAA2B,EAC3B,QAA2B,EAC3B,KAAa,EACN;IACP,MAAM,OAAO,GAAG,IAAI,GAAG,CAAC,CAAC,GAAG,QAAQ,EAAE,GAAG,QAAQ,CAAC,CAAC,CAAC;IACpD,MAAM,WAAW,GAAG,MAAM,CAAC,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AAC,CAAC;IACrC,oBAAoB,CAAC,aAAa,EAAE,eAAe,CAAC,CAAC;IACrD,OAAO,GAAG,KAAK,SAAS,aAAa,EAAE,CAAC;AAAA,CACxC;AA2BD;;;;;;;;;;GAUG;AACH,MAAM,UAAU,qBAAqB,CAAC,IAAkB,EAAE,OAAe,EAA2B;IACnG,oBAAoB,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC;IACzC,IACC,IAAI,CAAC,UAAU,KAAK,YAAY;QAChC,IAAI,CAAC,UAAU,EAAE,KAAK,CAAC,KAAK,KAAK,cAAc;QAC/C,IAAI,CAAC,UAAU,CAAC,WAAW,KAAK,SAAS,EACxC,CAAC;QACF,OAAO,SAAS,CAAC;IAClB,CAAC;IACD,IAAI,IAAI,CAAC,OAAO,KAAK,SAAS;QAAE,OAAO,QAAQ,CAAC;IAChD,IAAI,IAAI,CAAC,OAAO,KAAK,OAAO;QAAE,OAAO,SAAS,CAAC;IAC/C,OAAO,eAAe,CAAC;AAAA,CACvB","sourcesContent":["/**\n * Memory Foundation — canonical atom, identity, and immutable snapshots (1C.1a).\n *\n * A canonical atom is the immutable committed fact. Derived state (attention,\n * effective status, purgeAt) is NOT part of the atom; it is rebuilt from\n * lifecycle events (1C.1b/1C.2). Everything returned to hosts and plugins is a\n * detached, deep-frozen snapshot: mutating the input after `buildMemoryAtomV1`\n * never changes the stored atom.\n *\n * Field semantics follow `docs/design/记忆系统设计.md` §4 (记录模型), which is the\n * authoritative source for memory fields.\n */\nimport type { JsonValue } from \"@agent-forge/plugin-sdk\";\n\n/** Source of one memory: where the fact came from, optionally pinned by revision/digest. */\nexport interface MemorySourceRefV1 {\n\treadonly kind: \"session\" | \"entry\" | \"artifact\" | \"tool\" | \"state\";\n\treadonly id: string;\n\treadonly revision?: string;\n\treadonly digest?: string;\n}\n\n/** Namespace-scoped search facet. Facets are atom facts, never derived. */\nexport interface MemoryFacetV1 {\n\treadonly namespace: string;\n\treadonly schemaVersion: number;\n\treadonly key: string;\n\treadonly value: string;\n}\n\n/** Typed relation between atoms. Weights/validity belong to projections, not here. */\nexport interface MemoryRelationV1 {\n\treadonly relationId: string;\n\treadonly namespace: string;\n\treadonly schemaVersion: number;\n\treadonly kind: string;\n\treadonly targetMemoryId?: string;\n\treadonly targetRef?: MemorySourceRefV1;\n\treadonly confidence?: number;\n\treadonly relationRevision: string;\n}\n\nexport interface MemoryTimeRangeV1 {\n\treadonly from?: string;\n\treadonly to?: string;\n}\n\n/** Applicability narrowing; empty means \"applies without narrowing\". */\nexport interface MemoryApplicabilityV1 {\n\treadonly scenes?: readonly string[];\n\treadonly projects?: readonly string[];\n\treadonly tasks?: readonly string[];\n\treadonly timeRange?: MemoryTimeRangeV1;\n\treadonly exceptions?: readonly string[];\n}\n\n/** Preference envelope: the generic schema frozen for 1C; policy semantics come later. */\nexport interface MemoryPreferenceEnvelopeV1 {\n\treadonly subject: \"user\" | \"project\" | \"task\" | \"environment\";\n\treadonly key: string;\n\treadonly preferredValue: JsonValue;\n\treadonly alternatives?: readonly JsonValue[];\n\treadonly scope: {\n\t\treadonly level: \"task\" | \"project\" | \"scene\" | \"timeRange\" | \"profile-private\" | \"user-default\";\n\t\treadonly scenes?: readonly string[];\n\t\treadonly projects?: readonly string[];\n\t\treadonly tasks?: readonly string[];\n\t\treadonly timeRange?: MemoryTimeRangeV1;\n\t\treadonly exceptions?: readonly string[];\n\t};\n\treadonly evidence: {\n\t\treadonly class: \"explicit\" | \"repeated_behavior\" | \"inferred\";\n\t\treadonly sourceRefs: readonly MemorySourceRefV1[];\n\t\treadonly confidence: number;\n\t};\n\treadonly applicabilityConfidence: number;\n\treadonly confirmedAt?: string;\n}\n\n/** Provenance for synthesis/compaction memories derived from other atoms. */\nexport interface MemoryProvenanceV1 {\n\treadonly sourceMemoryIds: readonly string[];\n\treadonly purgeGroupId: string;\n\treadonly containsSourceContent: boolean;\n}\n\nexport type MemoryScopeV1 = \"session\" | \"cycle\" | \"long-term\";\nexport type MemoryKindV1 =\n\t| \"observation\"\n\t| \"preference\"\n\t| \"fact\"\n\t| \"decision\"\n\t| \"constraint\"\n\t| \"inference\"\n\t| \"synthesis\";\nexport type MemoryEvidenceClassV1 = \"explicit\" | \"repeated_behavior\" | \"tool_or_test\" | \"derived\";\n\n/** The immutable canonical atom. Once committed, no field may change in place. */\nexport interface MemoryAtomV1<TPayload = JsonValue> {\n\treadonly memoryId: string;\n\treadonly contractVersion: string;\n\treadonly schemaVersion: number;\n\treadonly scope: MemoryScopeV1;\n\treadonly retentionMode: string;\n\treadonly owner: string;\n\treadonly profileId: string;\n\treadonly shareGroupId?: string;\n\t/**\n\t * Suite (方案) this atom belongs to (方案系统设计 §6.1/§11, M5). Absent\n\t * (or protocol-level `null` on the wire, normalized to absent here) marks a\n\t * legacy pre-M5 atom: such atoms are fail-safe INVISIBLE to every\n\t * suite-scoped read and only readable through suite-unscoped queries. The\n\t * one cross-suite exception is an explicitly promoted user-default\n\t * preference (see {@link memorySuiteVisibility}).\n\t */\n\treadonly suiteId?: string;\n\treadonly retentionPolicyVersion: string;\n\treadonly memoryKind: MemoryKindV1;\n\treadonly payload: TPayload;\n\treadonly preference?: MemoryPreferenceEnvelopeV1;\n\treadonly occurredAt: string;\n\treadonly recordedAt: string;\n\treadonly sourceRefs: readonly MemorySourceRefV1[];\n\treadonly observationId: string;\n\treadonly sessionRefs: readonly string[];\n\treadonly agentInstanceRefs: readonly string[];\n\treadonly projectRefs: readonly string[];\n\treadonly subjectRefs: readonly string[];\n\treadonly facets: readonly MemoryFacetV1[];\n\treadonly relations: readonly MemoryRelationV1[];\n\treadonly provenance?: MemoryProvenanceV1;\n\treadonly confidence: number;\n\treadonly importance: number;\n\treadonly applicability?: MemoryApplicabilityV1;\n\treadonly evidenceClass: MemoryEvidenceClassV1;\n\treadonly contentRevision: string;\n\treadonly writeReason: string;\n}\n\ntype PlainRecord = Record<string, unknown>;\n\nfunction isPlainRecord(value: unknown): value is PlainRecord {\n\tif (value === null || typeof value !== \"object\" || Array.isArray(value)) return false;\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === Object.prototype || prototype === null;\n}\n\nfunction assertPlainRecord(value: unknown, label: string): asserts value is PlainRecord {\n\tif (!isPlainRecord(value)) throw new Error(`${label} must be a plain object`);\n}\n\nfunction assertExactKeys(\n\tvalue: PlainRecord,\n\trequired: readonly string[],\n\toptional: readonly string[],\n\tlabel: string,\n): void {\n\tconst allowed = new Set([...required, ...optional]);\n\tconst unsupported = Object.keys(value)\n\t\t.filter((key) => !allowed.has(key))\n\t\t.sort();\n\tif (unsupported.length > 0) throw new Error(`${label} has unsupported fields: ${unsupported.join(\", \")}`);\n\tfor (const key of required) {\n\t\tif (!(key in value)) throw new Error(`${label} is missing required field: ${key}`);\n\t}\n}\n\nfunction assertNonEmptyString(value: unknown, label: string): asserts value is string {\n\tif (typeof value !== \"string\" || value.trim().length === 0) throw new Error(`${label} must be a non-empty string`);\n}\n\nfunction assertPositiveSafeInteger(value: unknown, label: string): asserts value is number {\n\tif (typeof value !== \"number\" || !Number.isSafeInteger(value) || value < 1) {\n\t\tthrow new Error(`${label} must be a positive safe integer`);\n\t}\n}\n\nfunction assertUnitInterval(value: unknown, label: string): asserts value is number {\n\tif (typeof value !== \"number\" || !Number.isFinite(value) || value < 0 || value > 1) {\n\t\tthrow new Error(`${label} must be a number between 0 and 1`);\n\t}\n}\n\nfunction assertTimestamp(value: unknown, label: string): asserts value is string {\n\tassertNonEmptyString(value, label);\n\tif (Number.isNaN(Date.parse(value))) throw new Error(`${label} must be an ISO-8601 timestamp`);\n}\n\nfunction assertJsonValue(value: unknown, label: string, seen = new WeakSet<object>()): asserts value is JsonValue {\n\tif (value === null || typeof value === \"string\" || typeof value === \"boolean\") return;\n\tif (typeof value === \"number\") {\n\t\tif (Number.isFinite(value)) return;\n\t\tthrow new Error(`${label} must contain finite JSON numbers`);\n\t}\n\tif (typeof value !== \"object\") throw new Error(`${label} must be JSON-compatible`);\n\tif (seen.has(value)) throw new Error(`${label} must not contain cycles`);\n\tseen.add(value);\n\tif (Array.isArray(value)) {\n\t\tfor (const [index, child] of value.entries()) assertJsonValue(child, `${label}[${index}]`, seen);\n\t} else {\n\t\tif (!isPlainRecord(value)) throw new Error(`${label} must contain only plain JSON objects`);\n\t\tfor (const [key, child] of Object.entries(value)) assertJsonValue(child, `${label}.${key}`, seen);\n\t}\n\tseen.delete(value);\n}\n\nfunction assertStringArray(value: unknown, label: string): asserts value is readonly string[] {\n\tif (!Array.isArray(value)) throw new Error(`${label} must be an array`);\n\tfor (const [index, item] of value.entries()) assertNonEmptyString(item, `${label}[${index}]`);\n}\n\nfunction detachedFreeze<T>(value: T, seen = new WeakMap<object, unknown>()): T {\n\tif (value === null || typeof value !== \"object\") return value;\n\tconst existing = seen.get(value);\n\t// v8 ignore next -- 校验后的原子全部由新副本构成,不存在共享引用\n\tif (existing !== undefined) return existing as T;\n\tif (Array.isArray(value)) {\n\t\tconst copy: unknown[] = [];\n\t\tseen.set(value, copy);\n\t\tfor (const child of value) copy.push(detachedFreeze(child, seen));\n\t\treturn Object.freeze(copy) as T;\n\t}\n\tconst copy: Record<string, unknown> = Object.create(null) as Record<string, unknown>;\n\tseen.set(value, copy);\n\tfor (const [key, child] of Object.entries(value as Record<string, unknown>)) {\n\t\tcopy[key] = detachedFreeze(child, seen);\n\t}\n\treturn Object.freeze(copy) as T;\n}\n\n/** Stable JSON serialization with recursively sorted object keys (for identity digests). */\nfunction stableStringify(value: JsonValue): string {\n\tif (value === null || typeof value === \"boolean\" || typeof value === \"number\" || typeof value === \"string\") {\n\t\treturn JSON.stringify(value);\n\t}\n\tif (Array.isArray(value)) return `[${value.map((item) => stableStringify(item)).join(\",\")}]`;\n\tconst entries = Object.keys(value)\n\t\t.sort()\n\t\t.map((key) => `${JSON.stringify(key)}:${stableStringify((value as Record<string, JsonValue>)[key])}`);\n\treturn `{${entries.join(\",\")}}`;\n}\n\nconst MEMORY_SCOPES_V1: readonly MemoryScopeV1[] = [\"session\", \"cycle\", \"long-term\"];\nconst MEMORY_KINDS_V1: readonly MemoryKindV1[] = [\n\t\"observation\",\n\t\"preference\",\n\t\"fact\",\n\t\"decision\",\n\t\"constraint\",\n\t\"inference\",\n\t\"synthesis\",\n];\nconst MEMORY_EVIDENCE_CLASSES_V1: readonly MemoryEvidenceClassV1[] = [\n\t\"explicit\",\n\t\"repeated_behavior\",\n\t\"tool_or_test\",\n\t\"derived\",\n];\nconst SOURCE_REF_KINDS: readonly MemorySourceRefV1[\"kind\"][] = [\"session\", \"entry\", \"artifact\", \"tool\", \"state\"];\n\nfunction validateSourceRef(value: unknown, label: string): MemorySourceRefV1 {\n\tassertPlainRecord(value, label);\n\tassertExactKeys(value, [\"kind\", \"id\"], [\"revision\", \"digest\"], label);\n\tif (!SOURCE_REF_KINDS.includes(value.kind as MemorySourceRefV1[\"kind\"])) {\n\t\tthrow new Error(`${label}.kind is invalid`);\n\t}\n\tassertNonEmptyString(value.id, `${label}.id`);\n\tif (value.revision !== undefined) assertNonEmptyString(value.revision, `${label}.revision`);\n\tif (value.digest !== undefined) assertNonEmptyString(value.digest, `${label}.digest`);\n\treturn detachedFreeze({\n\t\tkind: value.kind as MemorySourceRefV1[\"kind\"],\n\t\tid: value.id,\n\t\t...(value.revision === undefined ? {} : { revision: value.revision }),\n\t\t...(value.digest === undefined ? {} : { digest: value.digest }),\n\t});\n}\n\nfunction validateFacet(value: unknown, label: string): MemoryFacetV1 {\n\tassertPlainRecord(value, label);\n\tassertExactKeys(value, [\"namespace\", \"schemaVersion\", \"key\", \"value\"], [], label);\n\tassertNonEmptyString(value.namespace, `${label}.namespace`);\n\tassertPositiveSafeInteger(value.schemaVersion, `${label}.schemaVersion`);\n\tassertNonEmptyString(value.key, `${label}.key`);\n\tassertNonEmptyString(value.value, `${label}.value`);\n\treturn detachedFreeze({\n\t\tnamespace: value.namespace,\n\t\tschemaVersion: value.schemaVersion,\n\t\tkey: value.key,\n\t\tvalue: value.value,\n\t});\n}\n\nfunction validateRelation(value: unknown, label: string): MemoryRelationV1 {\n\tassertPlainRecord(value, label);\n\tassertExactKeys(\n\t\tvalue,\n\t\t[\"relationId\", \"namespace\", \"schemaVersion\", \"kind\", \"relationRevision\"],\n\t\t[\"targetMemoryId\", \"targetRef\", \"confidence\"],\n\t\tlabel,\n\t);\n\tassertNonEmptyString(value.relationId, `${label}.relationId`);\n\tassertNonEmptyString(value.namespace, `${label}.namespace`);\n\tassertPositiveSafeInteger(value.schemaVersion, `${label}.schemaVersion`);\n\tassertNonEmptyString(value.kind, `${label}.kind`);\n\tassertNonEmptyString(value.relationRevision, `${label}.relationRevision`);\n\tif (value.targetMemoryId !== undefined && value.targetRef !== undefined) {\n\t\tthrow new Error(`${label} must not declare both targetMemoryId and targetRef`);\n\t}\n\tconst targetMemoryId = value.targetMemoryId === undefined ? undefined : (value.targetMemoryId as string);\n\tif (targetMemoryId !== undefined) assertNonEmptyString(targetMemoryId, `${label}.targetMemoryId`);\n\tconst targetRef =\n\t\tvalue.targetRef === undefined ? undefined : validateSourceRef(value.targetRef, `${label}.targetRef`);\n\tif (value.confidence !== undefined) assertUnitInterval(value.confidence, `${label}.confidence`);\n\treturn detachedFreeze({\n\t\trelationId: value.relationId,\n\t\tnamespace: value.namespace,\n\t\tschemaVersion: value.schemaVersion,\n\t\tkind: value.kind,\n\t\t...(targetMemoryId === undefined ? {} : { targetMemoryId }),\n\t\t...(targetRef === undefined ? {} : { targetRef }),\n\t\t...(value.confidence === undefined ? {} : { confidence: value.confidence }),\n\t\trelationRevision: value.relationRevision,\n\t});\n}\n\nfunction validateTimeRange(value: unknown, label: string): MemoryTimeRangeV1 {\n\tassertPlainRecord(value, label);\n\t// Key order reversed on purpose: in the natural order the boundary-gate\n\t// lexical scanner reads this key pair as an import specifier (first key\n\t// string, comma, second key string). `assertExactKeys` builds a Set, so the\n\t// order is irrelevant to validation.\n\tassertExactKeys(value, [], [\"to\", \"from\"], label);\n\tconst from = value.from === undefined ? undefined : (value.from as string);\n\tconst to = value.to === undefined ? undefined : (value.to as string);\n\tif (from !== undefined) assertTimestamp(from, `${label}.from`);\n\tif (to !== undefined) assertTimestamp(to, `${label}.to`);\n\treturn detachedFreeze({\n\t\t...(from === undefined ? {} : { from }),\n\t\t...(to === undefined ? {} : { to }),\n\t});\n}\n\nfunction validateApplicability(value: unknown, label: string): MemoryApplicabilityV1 {\n\tassertPlainRecord(value, label);\n\tassertExactKeys(value, [], [\"scenes\", \"projects\", \"tasks\", \"timeRange\", \"exceptions\"], label);\n\tif (value.scenes !== undefined) assertStringArray(value.scenes, `${label}.scenes`);\n\tif (value.projects !== undefined) assertStringArray(value.projects, `${label}.projects`);\n\tif (value.tasks !== undefined) assertStringArray(value.tasks, `${label}.tasks`);\n\tif (value.exceptions !== undefined) assertStringArray(value.exceptions, `${label}.exceptions`);\n\tconst timeRange =\n\t\tvalue.timeRange === undefined ? undefined : validateTimeRange(value.timeRange, `${label}.timeRange`);\n\treturn detachedFreeze({\n\t\t...(value.scenes === undefined ? {} : { scenes: Object.freeze([...(value.scenes as readonly string[])]) }),\n\t\t...(value.projects === undefined ? {} : { projects: Object.freeze([...(value.projects as readonly string[])]) }),\n\t\t...(value.tasks === undefined ? {} : { tasks: Object.freeze([...(value.tasks as readonly string[])]) }),\n\t\t...(timeRange === undefined ? {} : { timeRange }),\n\t\t...(value.exceptions === undefined\n\t\t\t? {}\n\t\t\t: { exceptions: Object.freeze([...(value.exceptions as readonly string[])]) }),\n\t});\n}\n\nfunction validatePreferenceEnvelope(value: unknown, label: string): MemoryPreferenceEnvelopeV1 {\n\tassertPlainRecord(value, label);\n\tassertExactKeys(\n\t\tvalue,\n\t\t[\"subject\", \"key\", \"preferredValue\", \"scope\", \"evidence\", \"applicabilityConfidence\"],\n\t\t[\"alternatives\", \"confirmedAt\"],\n\t\tlabel,\n\t);\n\tconst subjects: readonly MemoryPreferenceEnvelopeV1[\"subject\"][] = [\"user\", \"project\", \"task\", \"environment\"];\n\tif (!subjects.includes(value.subject as MemoryPreferenceEnvelopeV1[\"subject\"])) {\n\t\tthrow new Error(`${label}.subject is invalid`);\n\t}\n\tassertNonEmptyString(value.key, `${label}.key`);\n\tassertJsonValue(value.preferredValue, `${label}.preferredValue`);\n\tif (value.alternatives !== undefined) {\n\t\tif (!Array.isArray(value.alternatives)) throw new Error(`${label}.alternatives must be an array`);\n\t\tfor (const [index, item] of value.alternatives.entries()) {\n\t\t\tassertJsonValue(item, `${label}.alternatives[${index}]`);\n\t\t}\n\t}\n\tconst scope = value.scope;\n\tassertPlainRecord(scope, `${label}.scope`);\n\tassertExactKeys(scope, [\"level\"], [\"scenes\", \"projects\", \"tasks\", \"timeRange\", \"exceptions\"], `${label}.scope`);\n\tconst levels: readonly MemoryPreferenceEnvelopeV1[\"scope\"][\"level\"][] = [\n\t\t\"task\",\n\t\t\"project\",\n\t\t\"scene\",\n\t\t\"timeRange\",\n\t\t\"profile-private\",\n\t\t\"user-default\",\n\t];\n\tif (!levels.includes(scope.level as MemoryPreferenceEnvelopeV1[\"scope\"][\"level\"])) {\n\t\tthrow new Error(`${label}.scope.level is invalid`);\n\t}\n\t// String-array scope collections face the same rigor as adjacent collection\n\t// fields (sessionRefs, applicability): a bare string must be rejected, not\n\t// silently exploded into a per-character array by the freeze copy.\n\tif (scope.scenes !== undefined) assertStringArray(scope.scenes, `${label}.scope.scenes`);\n\tif (scope.projects !== undefined) assertStringArray(scope.projects, `${label}.scope.projects`);\n\tif (scope.tasks !== undefined) assertStringArray(scope.tasks, `${label}.scope.tasks`);\n\tif (scope.exceptions !== undefined) assertStringArray(scope.exceptions, `${label}.scope.exceptions`);\n\t// Anchor levels require their anchor to be present (记录模型约束).\n\tconst anchors: ReadonlyArray<[string, keyof PlainRecord]> = [\n\t\t[\"task\", \"tasks\"],\n\t\t[\"project\", \"projects\"],\n\t\t[\"scene\", \"scenes\"],\n\t\t[\"timeRange\", \"timeRange\"],\n\t];\n\tfor (const [level, field] of anchors) {\n\t\tif (\n\t\t\tscope.level === level &&\n\t\t\t(scope[field] === undefined || (Array.isArray(scope[field]) && scope[field].length === 0))\n\t\t) {\n\t\t\tthrow new Error(`${label}.scope.level \"${level}\" requires non-empty ${field}`);\n\t\t}\n\t}\n\tconst evidence = value.evidence;\n\tassertPlainRecord(evidence, `${label}.evidence`);\n\tassertExactKeys(evidence, [\"class\", \"sourceRefs\", \"confidence\"], [], `${label}.evidence`);\n\tconst evidenceClasses: readonly MemoryPreferenceEnvelopeV1[\"evidence\"][\"class\"][] = [\n\t\t\"explicit\",\n\t\t\"repeated_behavior\",\n\t\t\"inferred\",\n\t];\n\tif (!evidenceClasses.includes(evidence.class as MemoryPreferenceEnvelopeV1[\"evidence\"][\"class\"])) {\n\t\tthrow new Error(`${label}.evidence.class is invalid`);\n\t}\n\tif (!Array.isArray(evidence.sourceRefs) || evidence.sourceRefs.length === 0) {\n\t\tthrow new Error(`${label}.evidence.sourceRefs must not be empty`);\n\t}\n\tconst evidenceSourceRefs = evidence.sourceRefs.map((item, index) =>\n\t\tvalidateSourceRef(item, `${label}.evidence.sourceRefs[${index}]`),\n\t);\n\tassertUnitInterval(evidence.confidence, `${label}.evidence.confidence`);\n\tassertUnitInterval(value.applicabilityConfidence, `${label}.applicabilityConfidence`);\n\tif (value.confirmedAt !== undefined) assertTimestamp(value.confirmedAt, `${label}.confirmedAt`);\n\treturn detachedFreeze({\n\t\tsubject: value.subject as MemoryPreferenceEnvelopeV1[\"subject\"],\n\t\tkey: value.key,\n\t\tpreferredValue: value.preferredValue,\n\t\t...(value.alternatives === undefined ? {} : { alternatives: Object.freeze([...value.alternatives]) }),\n\t\tscope: detachedFreeze({\n\t\t\tlevel: scope.level as MemoryPreferenceEnvelopeV1[\"scope\"][\"level\"],\n\t\t\t...(scope.scenes === undefined ? {} : { scenes: Object.freeze([...(scope.scenes as readonly string[])]) }),\n\t\t\t...(scope.projects === undefined\n\t\t\t\t? {}\n\t\t\t\t: { projects: Object.freeze([...(scope.projects as readonly string[])]) }),\n\t\t\t...(scope.tasks === undefined ? {} : { tasks: Object.freeze([...(scope.tasks as readonly string[])]) }),\n\t\t\t...(scope.timeRange === undefined\n\t\t\t\t? {}\n\t\t\t\t: { timeRange: validateTimeRange(scope.timeRange, `${label}.scope.timeRange`) }),\n\t\t\t...(scope.exceptions === undefined\n\t\t\t\t? {}\n\t\t\t\t: { exceptions: Object.freeze([...(scope.exceptions as readonly string[])]) }),\n\t\t}),\n\t\tevidence: detachedFreeze({\n\t\t\tclass: evidence.class as MemoryPreferenceEnvelopeV1[\"evidence\"][\"class\"],\n\t\t\tsourceRefs: Object.freeze(evidenceSourceRefs),\n\t\t\tconfidence: evidence.confidence,\n\t\t}),\n\t\tapplicabilityConfidence: value.applicabilityConfidence,\n\t\t...(value.confirmedAt === undefined ? {} : { confirmedAt: value.confirmedAt }),\n\t}) as MemoryPreferenceEnvelopeV1;\n}\n\nfunction validateProvenance(value: unknown, label: string): MemoryProvenanceV1 {\n\tassertPlainRecord(value, label);\n\tassertExactKeys(value, [\"sourceMemoryIds\", \"purgeGroupId\", \"containsSourceContent\"], [], label);\n\tassertStringArray(value.sourceMemoryIds, `${label}.sourceMemoryIds`);\n\tif (value.sourceMemoryIds.length === 0) throw new Error(`${label}.sourceMemoryIds must not be empty`);\n\tassertNonEmptyString(value.purgeGroupId, `${label}.purgeGroupId`);\n\tif (typeof value.containsSourceContent !== \"boolean\") {\n\t\tthrow new Error(`${label}.containsSourceContent must be boolean`);\n\t}\n\treturn detachedFreeze({\n\t\tsourceMemoryIds: Object.freeze([...(value.sourceMemoryIds as readonly string[])]),\n\t\tpurgeGroupId: value.purgeGroupId,\n\t\tcontainsSourceContent: value.containsSourceContent,\n\t});\n}\n\n/**\n * Validates a canonical memory atom and returns a detached, deep-frozen\n * snapshot. Unknown fields, wrong enums, non-JSON payloads, preference-kind\n * atoms without a preference envelope, and identity fields (memoryId,\n * observationId, contentRevision, owner) that are not non-empty strings are\n * rejected.\n */\nexport function validateMemoryAtomV1<TPayload = JsonValue>(value: unknown): MemoryAtomV1<TPayload> {\n\tassertPlainRecord(value, \"Memory atom\");\n\tassertExactKeys(\n\t\tvalue,\n\t\t[\n\t\t\t\"memoryId\",\n\t\t\t\"contractVersion\",\n\t\t\t\"schemaVersion\",\n\t\t\t\"scope\",\n\t\t\t\"retentionMode\",\n\t\t\t\"owner\",\n\t\t\t\"profileId\",\n\t\t\t\"retentionPolicyVersion\",\n\t\t\t\"memoryKind\",\n\t\t\t\"payload\",\n\t\t\t\"occurredAt\",\n\t\t\t\"recordedAt\",\n\t\t\t\"sourceRefs\",\n\t\t\t\"observationId\",\n\t\t\t\"sessionRefs\",\n\t\t\t\"agentInstanceRefs\",\n\t\t\t\"projectRefs\",\n\t\t\t\"subjectRefs\",\n\t\t\t\"facets\",\n\t\t\t\"relations\",\n\t\t\t\"confidence\",\n\t\t\t\"importance\",\n\t\t\t\"evidenceClass\",\n\t\t\t\"contentRevision\",\n\t\t\t\"writeReason\",\n\t\t],\n\t\t[\"tenantId\", \"shareGroupId\", \"suiteId\", \"preference\", \"provenance\", \"applicability\"],\n\t\t\"Memory atom\",\n\t);\n\tassertNonEmptyString(value.memoryId, \"Memory atom.memoryId\");\n\tassertNonEmptyString(value.contractVersion, \"Memory atom.contractVersion\");\n\tassertPositiveSafeInteger(value.schemaVersion, \"Memory atom.schemaVersion\");\n\tif (!MEMORY_SCOPES_V1.includes(value.scope as MemoryScopeV1)) throw new Error(\"Memory atom.scope is invalid\");\n\tassertNonEmptyString(value.retentionMode, \"Memory atom.retentionMode\");\n\tassertNonEmptyString(value.owner, \"Memory atom.owner\");\n\tassertNonEmptyString(value.profileId, \"Memory atom.profileId\");\n\tif (value.shareGroupId !== undefined) assertNonEmptyString(value.shareGroupId, \"Memory atom.shareGroupId\");\n\t// Legacy (pre-M5) atoms may carry protocol-level `null` for \"no suite\"; it\n\t// is tolerated here and normalized to an absent field (存量语义), while a\n\t// present suiteId must be a non-empty string.\n\tif (value.suiteId !== undefined && value.suiteId !== null) {\n\t\tassertNonEmptyString(value.suiteId, \"Memory atom.suiteId\");\n\t}\n\tassertNonEmptyString(value.retentionPolicyVersion, \"Memory atom.retentionPolicyVersion\");\n\tif (!MEMORY_KINDS_V1.includes(value.memoryKind as MemoryKindV1))\n\t\tthrow new Error(\"Memory atom.memoryKind is invalid\");\n\tassertJsonValue(value.payload, \"Memory atom.payload\");\n\tif (value.memoryKind === \"preference\" && value.preference === undefined) {\n\t\tthrow new Error(\"Memory atom.memoryKind preference requires a preference envelope\");\n\t}\n\tconst preference =\n\t\tvalue.preference === undefined\n\t\t\t? undefined\n\t\t\t: validatePreferenceEnvelope(value.preference, \"Memory atom.preference\");\n\tassertTimestamp(value.occurredAt, \"Memory atom.occurredAt\");\n\tassertTimestamp(value.recordedAt, \"Memory atom.recordedAt\");\n\tif (!Array.isArray(value.sourceRefs)) throw new Error(\"Memory atom.sourceRefs must be an array\");\n\tconst sourceRefs = value.sourceRefs.map((item, index) =>\n\t\tvalidateSourceRef(item, `Memory atom.sourceRefs[${index}]`),\n\t);\n\tassertNonEmptyString(value.observationId, \"Memory atom.observationId\");\n\tassertStringArray(value.sessionRefs, \"Memory atom.sessionRefs\");\n\tassertStringArray(value.agentInstanceRefs, \"Memory atom.agentInstanceRefs\");\n\tassertStringArray(value.projectRefs, \"Memory atom.projectRefs\");\n\tassertStringArray(value.subjectRefs, \"Memory atom.subjectRefs\");\n\tif (!Array.isArray(value.facets)) throw new Error(\"Memory atom.facets must be an array\");\n\tconst facets = value.facets.map((item, index) => validateFacet(item, `Memory atom.facets[${index}]`));\n\tif (!Array.isArray(value.relations)) throw new Error(\"Memory atom.relations must be an array\");\n\tconst relations = value.relations.map((item, index) => validateRelation(item, `Memory atom.relations[${index}]`));\n\tconst provenance =\n\t\tvalue.provenance === undefined ? undefined : validateProvenance(value.provenance, \"Memory atom.provenance\");\n\tassertUnitInterval(value.confidence, \"Memory atom.confidence\");\n\tassertUnitInterval(value.importance, \"Memory atom.importance\");\n\tconst applicability =\n\t\tvalue.applicability === undefined\n\t\t\t? undefined\n\t\t\t: validateApplicability(value.applicability, \"Memory atom.applicability\");\n\tif (!MEMORY_EVIDENCE_CLASSES_V1.includes(value.evidenceClass as MemoryEvidenceClassV1)) {\n\t\tthrow new Error(\"Memory atom.evidenceClass is invalid\");\n\t}\n\tassertNonEmptyString(value.contentRevision, \"Memory atom.contentRevision\");\n\tassertNonEmptyString(value.writeReason, \"Memory atom.writeReason\");\n\n\treturn detachedFreeze({\n\t\tmemoryId: value.memoryId,\n\t\tcontractVersion: value.contractVersion,\n\t\tschemaVersion: value.schemaVersion,\n\t\tscope: value.scope as MemoryScopeV1,\n\t\tretentionMode: value.retentionMode,\n\t\towner: value.owner,\n\t\tprofileId: value.profileId,\n\t\t...(value.shareGroupId === undefined ? {} : { shareGroupId: value.shareGroupId }),\n\t\t...(value.suiteId === undefined || value.suiteId === null ? {} : { suiteId: value.suiteId }),\n\t\tretentionPolicyVersion: value.retentionPolicyVersion,\n\t\tmemoryKind: value.memoryKind as MemoryKindV1,\n\t\tpayload: value.payload as TPayload,\n\t\t...(preference === undefined ? {} : { preference }),\n\t\toccurredAt: value.occurredAt,\n\t\trecordedAt: value.recordedAt,\n\t\tsourceRefs: Object.freeze(sourceRefs),\n\t\tobservationId: value.observationId,\n\t\tsessionRefs: Object.freeze([...value.sessionRefs]),\n\t\tagentInstanceRefs: Object.freeze([...value.agentInstanceRefs]),\n\t\tprojectRefs: Object.freeze([...value.projectRefs]),\n\t\tsubjectRefs: Object.freeze([...value.subjectRefs]),\n\t\tfacets: Object.freeze(facets),\n\t\trelations: Object.freeze(relations),\n\t\t...(provenance === undefined ? {} : { provenance }),\n\t\tconfidence: value.confidence,\n\t\timportance: value.importance,\n\t\t...(applicability === undefined ? {} : { applicability }),\n\t\tevidenceClass: value.evidenceClass as MemoryEvidenceClassV1,\n\t\tcontentRevision: value.contentRevision,\n\t\twriteReason: value.writeReason,\n\t}) as MemoryAtomV1<TPayload>;\n}\n\n/** Builds a detached, frozen canonical atom (validate + freeze). */\nexport function buildMemoryAtomV1<TPayload = JsonValue>(atom: MemoryAtomV1<TPayload>): MemoryAtomV1<TPayload> {\n\treturn validateMemoryAtomV1<TPayload>(atom);\n}\n\n/** FNV-1a 64-bit digest over the stable JSON serialization of `value`. */\nexport function memoryContentDigest(value: JsonValue): string {\n\tconst serialized = stableStringify(value);\n\tlet digest = 14695981039346656037n;\n\tfor (const byte of new TextEncoder().encode(serialized)) {\n\t\tdigest ^= BigInt(byte);\n\t\tdigest = BigInt.asUintN(64, digest * 1099511628211n);\n\t}\n\treturn digest.toString(16).padStart(16, \"0\");\n}\n\n/** Idempotent submission identity: the same (owner, observationId) is one observation. */\nexport function memoryObservationKey(owner: string, observationId: string): string {\n\tassertNonEmptyString(owner, \"owner\");\n\tassertNonEmptyString(observationId, \"observationId\");\n\treturn `${owner}\\u0000${observationId}`;\n}\n\n// ---------------------------------------------------------------------------\n// Suite (方案) read boundary (方案系统设计 §6.1/§11, M5)\n// ---------------------------------------------------------------------------\n\n/** Why a record was excluded from a suite-scoped read (读取边界惰性可观测). */\nexport type MemorySuiteVisibilityV1 =\n\t/** The atom matches the queried suite, or is an explicitly promoted user-default preference. */\n\t| \"visible\"\n\t/** Legacy (pre-M5) atom without a suiteId — fail-safe invisible to every suite. */\n\t| \"legacy\"\n\t/** The atom belongs to a different suite. */\n\t| \"foreign-suite\";\n\n/**\n * Skipped-record counters attached to suite-scoped reads. The read boundary is\n * lazy and observable (设计 §11 三段式): excluded atoms are counted, never\n * silently dropped.\n */\nexport interface MemorySuiteFilterStatsV1 {\n\t/** Legacy (suiteId-less) atoms skipped as invisible to any suite. */\n\treadonly legacySkipped: number;\n\t/** Atoms bound to a different suiteId that were skipped. */\n\treadonly foreignSuiteSkipped: number;\n}\n\n/**\n * Suite-scoped visibility of one atom (方案系统设计 §6.1/§11):\n * - `atom.suiteId === suiteId` → visible;\n * - an explicitly promoted user-default preference (scope.level\n * \"user-default\" WITH `confirmedAt` — the canonical explicit-confirmation\n * marker set only by the explicit promotion channel) ignores the suiteId\n * filter and is visible in every suite (§6.1 跨方案偏好);\n * - absent suiteId (legacy/存量) → invisible to every suite (fail-safe\n * default), counted via {@link MemorySuiteFilterStatsV1};\n * - any other suiteId → invisible.\n */\nexport function memorySuiteVisibility(atom: MemoryAtomV1, suiteId: string): MemorySuiteVisibilityV1 {\n\tassertNonEmptyString(suiteId, \"suiteId\");\n\tif (\n\t\tatom.memoryKind === \"preference\" &&\n\t\tatom.preference?.scope.level === \"user-default\" &&\n\t\tatom.preference.confirmedAt !== undefined\n\t) {\n\t\treturn \"visible\";\n\t}\n\tif (atom.suiteId === undefined) return \"legacy\";\n\tif (atom.suiteId === suiteId) return \"visible\";\n\treturn \"foreign-suite\";\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vector-channel.d.ts","sourceRoot":"","sources":["../../src/memory/vector-channel.ts"],"names":[],"mappings":"AAAA;;GAEG;AAGH,OAAO,KAAK,EACX,aAAa,EACb,wBAAwB,EACxB,gCAAgC,EAChC,MAAM,yBAAyB,CAAC;AAmBjC,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AAKpE,8FAAiD;AACjD,eAAO,MAAM,wBAAwB,6BAA6B,CAAC;AACnE,eAAO,MAAM,iBAAiB,WAAW,CAAC;AAC1C,eAAO,MAAM,0BAA0B,gBAAgB,CAAC;AAExD,wGAA2D;AAC3D,MAAM,MAAM,uBAAuB,GAAG,kBAAkB,GAAG,UAAU,GAAG,OAAO,GAAG,UAAU,GAAG,QAAQ,CAAC;AAExG,+FAAoD;AACpD,MAAM,WAAW,uBAAuB;IACvC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,OAAO,EAAE,SAAS,MAAM,EAAE,CAAC;CACpC;AAED;;;;GAIG;AACH,MAAM,WAAW,qBAAqB;IACrC,QAAQ,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,CAAC;IACnC,gGAAwC;IACxC,QAAQ,CAAC,g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;QAAE,MAAM,EAAE,QAAQ,CAAC;QAAC,OAAO,EAAE,MAAM,CAAC;QAAC,OAAO,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,CAAA;KAAE,CACnF,CAAC;IACF,yEAA+C;IAC/C,OAAO,IAAI,IAAI,CAAC;CAChB;AAED,wBAAgB,yBAAyB,CAAC,IAAI,EAAE,yBAAyB,GAAG,qBAAqB,CA+hBhG","sourcesContent":["/**\n * 向量通道状态机(capability 拆分战役 slice 3b):vectorEnsure 状态转换、装配分支(服务/本地/下载/征询门)、dispose 闩锁。共享闭包状态收拢为 channel 对象, 经 deps 显式注入; 降级/投影经 slice 3a 的 vector-projection 上报\n */\n\nimport { join } from \"node:path\";\nimport type {\n\tCapabilityAPI,\n\tMemoryEnablingOverrideV1,\n\tMemoryVectorComponentsOverrideV1,\n} from \"@agent-forge/plugin-sdk\";\nimport {\n\tDISK_HEADROOM_MIN_BYTES,\n\tdiskHeadroomCheck,\n\tenablingActionList,\n\tMODEL_MIN_WEIGHT_BYTES,\n\tmissingHeavyDependencyModules,\n\tmodelFilesCheck,\n\tnativeBinaryCheck,\n\tnormalizeMemoryAgentDirIdentity,\n\tRERANKER_MIN_WEIGHT_BYTES,\n\tremoteHostsForEnabling,\n\tresolveHeavyDependencyEntryPath,\n\tvectorPresetForMode,\n\twriteMemoryConsentDeclined,\n} from \"./enabling.ts\";\nimport { ensureInferenceServiceChannel, serviceFailureActionList } from \"./inference-channel.ts\";\nimport { type MemoryInferenceClientV1, resolveMemoryInferencePort } from \"./inference-client.ts\";\nimport { MEMORY_INFERENCE_DEFAULT_PORT, MEMORY_INFERENCE_PORT_ENV } from \"./inference-protocol.ts\";\nimport type { ActiveVectorChannelV1 } from \"./vector-projection.ts\";\n\n/** enabling 加载/下载期间的周期性进度日志间隔。 */\nconst ENABLING_PROGRESS_LOG_INTERVAL_MS = 15_000;\n\n/** 两档共用精排模型 (POC 报告 §8: 官方 Xenova 转换版唯一实测可用)。 */\nexport const VECTOR_RERANKER_MODEL_ID = \"Xenova/bge-reranker-base\";\nexport const VECTOR_DB_DIRNAME = \"vector\";\nexport const VECTOR_MODEL_CACHE_DIRNAME = \"model-cache\";\n\n/** capability 级状态机 (设计 §3.2): off 只出现在模式关闭 (零注册, 不可观测)。 */\nexport type MemoryCapabilityStateV1 = \"consent-required\" | \"enabling\" | \"ready\" | \"degraded\" | \"failed\";\n\n/** enabling 失败的结构化结果: 原因 + 行动清单 (硬性要求, 设计 §3.2)。 */\nexport interface MemoryEnablingFailureV1 {\n\treadonly reason: string;\n\treadonly actions: readonly string[];\n}\n\n/**\n * 征询门待决信息 (2026-10-05 用户裁决「首次使用征询、拒绝即持久化关闭」):\n * 向量通道从未就绪且模式已启用时, 模型下载必须先经用户同意——检索不触发下载,\n * 由 AI 转述征询后经 memory_enable 工具面继续。\n */\nexport interface MemoryConsentNeededV1 {\n\treadonly models: readonly string[];\n\t/** 模型权重体积下限之和 (非精确体积; 实际下载量以镜像文件为准)。 */\n\treadonly approximateBytes: number;\n}\n\n/** 征询面 (consent-required 态的模型可见包): AI 转述话术 + 后续动作 + 注入块。 */\nexport interface MemoryConsentAskV1 {\n\treadonly message: string;\n\treadonly actions: readonly string[];\n\treadonly block: string;\n}\n\n/**\n * 向量通道对 capability 装配上下文的显式依赖视图 (slice 3b): 逐项来自\n * createMemoryCapabilityHarness 的闭包捕获核实, 不再经共享闭包隐式可达。\n */\nexport interface MemoryVectorChannelDepsV1 {\n\t/** agent 根目录 (MemoryCapabilityContext.agentDir): 模型缓存/索引/征询持久化的路径域。 */\n\treadonly agentDir: string;\n\t/** 已解析的全局档位 (harness memoryMode, off 已被工厂入口拦截)。 */\n\treadonly memoryMode: \"light\" | \"full\";\n\t/** capability 日志面 (api.logger): 进度/失败/自愈日志。 */\n\treadonly logger: CapabilityAPI[\"logger\"];\n\t/** 宿主注入的 onnxruntime-node 入口 (MemoryCapabilityContext.hostOnnxRuntimeEntryPath)。 */\n\treadonly hostOnnxRuntimeEntryPath?: string;\n\t/** 宿主注入的 @lancedb/lancedb 入口 (MemoryCapabilityContext.hostLancedbEntryPath)。 */\n\treadonly hostLancedbEntryPath?: string;\n\t/** 宿主注入的 @huggingface/transformers 入口 (MemoryCapabilityContext.hostTransformersEntryPath)。 */\n\treadonly hostTransformersEntryPath?: string;\n\t/** 服务装配缝 (Slice B2): 测试端口直连 (MemoryCapabilityContext.inferenceService.port)。 */\n\treadonly inferenceServicePort?: number;\n\t/** 服务装配缝 (Slice B2): 替换进程拉起的测试缝 (inferenceService.spawnImpl)。 */\n\treadonly inferenceServiceSpawnImpl?: (\n\t\tagentDir: string,\n\t\tmode: \"light\" | \"full\",\n\t\tport: number,\n\t\t/** spawn 异步失败 (EACCES/ENOMEM 等) 的回调; 缺省实现经 child 'error' 事件馈入。 */\n\t\tonError?: (error: Error) => void,\n\t) => Promise<void>;\n\t/** 服务装配缝 (Slice B2): 声明模型在位, 文件检查与征询门让位 (inferenceService.modelsInPlace)。 */\n\treadonly inferenceServiceModelsInPlace?: boolean;\n\t/** enabling 测试缝 (loadImpl 重定向模型加载); undefined = 生产路径。 */\n\treadonly enablingOverride?: MemoryEnablingOverrideV1;\n\t/** 组件注入 (deterministic mock 门禁): 存在时通道直接 ready, 跳过真实装配。 */\n\treadonly injectedComponents?: MemoryVectorComponentsOverrideV1;\n\t/** 写侧投影 (slice 3a 的 vectorProjection.resetReconcile): downloadMemory 就绪后重臂启动对账。 */\n\treadonly resetReconcile: () => void;\n\t/** 写侧投影 (slice 3a 的 vectorProjection.reconcileOnce): downloadMemory 就绪后补跑对账。 */\n\treadonly reconcileOnce: () => void;\n}\n\nexport interface MemoryVectorChannelV1 {\n\t/** harness.vectorState 面: 征询拒绝时投影为 \"off\" (本实例按模式关闭对待)。 */\n\tstate(): \"off\" | MemoryCapabilityStateV1;\n\t/** vectorState 原值 (未做 declined 投影; recall/合并探测等内部消费)。 */\n\trawState(): MemoryCapabilityStateV1;\n\t/** vectorEnabled: failed/consent-required/declined 时 false (写侧埋点门)。 */\n\tenabled(): boolean;\n\t/** 已就绪通道的同步快照 (vectorChannel 只读; projection.readyChannel 面)。 */\n\treadyChannel(): ActiveVectorChannelV1 | undefined;\n\t/** dispose 闩锁只读视图 (capabilityDisposed; projection.isDisposed 面)。 */\n\tisDisposed(): boolean;\n\t/** 征询拒绝标记 (declineMemory 持久化后的本实例内存面)。 */\n\tdeclined(): boolean;\n\t/** 用户显式再启用 (/memory light|full、自动升档) 清除本实例拒绝标记。 */\n\tclearDeclined(): void;\n\t/** 征询一次性注入钉住标记 (auto-recall 每实例只注入一次)。 */\n\tconsentAsked(): boolean;\n\tmarkConsentAsked(): void;\n\t/** 无副作用征询探测 (auto-recall 首轮; 纯本地 stat, 绝不触发下载/加载)。 */\n\tprimeConsentGate(): void;\n\t/** 征询待决面 (consent-required 且待决信息就位时非 undefined; 纯只读, 不探测)。 */\n\tconsentAsk(): MemoryConsentAskV1 | undefined;\n\t/** warming 守卫 (recall 后台预热不阻塞读侧): 装配在途且未拒绝。 */\n\twarming(): boolean;\n\t/** enabling 失败结构化结果 (未失败 = undefined)。 */\n\tfailure(): MemoryEnablingFailureV1 | undefined;\n\t/** 运行期故障 → degraded (可自愈; recall 与投影对账共用)。 */\n\tmarkDegraded(): void;\n\t/** degraded → ready 的自愈转换 (仅从 degraded; 全通 recall 成功后调用)。 */\n\trecoverDegraded(): void;\n\t/** vectorEnsure: 惰性单飞装配 (recall/write/埋点/对账的公共入口)。 */\n\tensure(): Promise<ActiveVectorChannelV1 | undefined>;\n\t/** harness.enablingOutcome 面: 触发惰性 enabling 并等待落定 (ready 或结构化失败)。 */\n\tenablingOutcome(): Promise<\"ready\" | MemoryEnablingFailureV1>;\n\t/** declineMemory 核心: 持久化拒绝 + 本实例按模式关闭。 */\n\tdecline(): { status: \"completed\"; message: string };\n\t/** downloadMemory 核心: 置征询同意 + 装配 + 补跑启动对账。 */\n\tdownload(): Promise<\n\t\t| { status: \"completed\"; message: string }\n\t\t| { status: \"failed\"; message: string; actions?: readonly string[]; next?: string }\n\t>;\n\t/** capabilityTeardown 本体: 资源关闭 + 闩锁置位 (幂等)。 */\n\tdispose(): void;\n}\n\nexport function createMemoryVectorChannel(deps: MemoryVectorChannelDepsV1): MemoryVectorChannelV1 {\n\tconst {\n\t\tagentDir,\n\t\tmemoryMode,\n\t\tlogger,\n\t\thostOnnxRuntimeEntryPath,\n\t\thostLancedbEntryPath,\n\t\thostTransformersEntryPath,\n\t\tinferenceServicePort,\n\t\tinferenceServiceSpawnImpl,\n\t\tinferenceServiceModelsInPlace,\n\t\tenablingOverride,\n\t\tinjectedComponents,\n\t\tresetReconcile,\n\t\treconcileOnce,\n\t} = deps;\n\t// ---- 语义召回通道 (2.4d6 S1/S2; 召回唯一检索路径) ----\n\t// 状态机 (设计 §3.2): enabling = 检查/加载进行中 (惰性触发: 首次向量操作\n\t// 时真正执行); ready = 可用; degraded = ready 后运行期故障 (可自愈回\n\t// ready); failed = enabling 失败, 本实例内终态 (mode 回退 off, 记忆工具\n\t// 返回携带行动清单的不可用 packet, 不再重试)。所有写侧操作经 vectorQueue\n\t// 串行化, 避免 reconcile 与写入埋点在 LanceDB 建表上竞态; recall 等待\n\t// enabling 单飞完成, 不与后台对账并发读索引。transformers/lancedb 的动态\n\t// import 只出现在 vectorEnsure 的装配分支里 (type-position 引类型), 未\n\t// 触发时不加载任何重依赖。\n\tlet vectorState: MemoryCapabilityStateV1 = \"enabling\";\n\tlet vectorChannel: ActiveVectorChannelV1 | undefined;\n\tlet enablingFailure: MemoryEnablingFailureV1 | undefined;\n\tlet enablingSettled: (() => void) | undefined;\n\t// 征询门 (2026-10-05 用户裁决「首次使用征询、拒绝即持久化关闭」): 模型文件\n\t// 缺失时下载必须先经用户同意——consentGranted 只由 memory_enable 工具面置位;\n\t// consentDeclined = 本实例内用户拒绝/跳过 (同时持久化, 见\n\t// writeMemoryConsentDeclined), 之后本实例按模式关闭对待; consentAsked 钉住\n\t// 自动召回的一次性征询注入, 不随查询文本翻新。\n\tlet consentGranted = false;\n\tlet consentDeclined = false;\n\tlet consentAsked = false;\n\tlet consentNeededInfo: MemoryConsentNeededV1 | undefined;\n\tconst enablingSettledPromise = new Promise<\"ready\" | MemoryEnablingFailureV1>((resolve) => {\n\t\tenablingSettled = () => resolve(enablingFailure ?? \"ready\");\n\t});\n\tif (injectedComponents !== undefined) {\n\t\t// 测试注入: 直接 ready, 跳过真实装配与档位解析。\n\t\tvectorState = \"ready\";\n\t\tvectorChannel = {\n\t\t\tembed: injectedComponents.embedProvider,\n\t\t\treranker: injectedComponents.reranker,\n\t\t\tindex: injectedComponents.vectorIndex,\n\t\t\tqueryPrefix: injectedComponents.queryPrefix ?? \"\",\n\t\t\tembeddingModelId: injectedComponents.embedProvider.modelId,\n\t\t};\n\t\tenablingSettled?.();\n\t}\n\tconst vectorEnabled = (): boolean =>\n\t\tvectorState !== \"failed\" && vectorState !== \"consent-required\" && !consentDeclined;\n\t// 征询话术 (AI 转述给用户; 会话语言由 AI 决定): 模型清单 + 体积下限 + 两个\n\t// 后续动作。consent-required 态下的 recall packet、auto-recall 注入块共用。\n\tconst consentAskMessage = (): string => {\n\t\tconst info = consentNeededInfo;\n\t\tconst models = info === undefined ? \"embedding + reranker\" : info.models.join(\" + \");\n\t\tconst floorMb = Math.ceil(\n\t\t\t(info?.approximateBytes ?? MODEL_MIN_WEIGHT_BYTES[memoryMode] + RERANKER_MIN_WEIGHT_BYTES) / (1024 * 1024),\n\t\t);\n\t\treturn (\n\t\t\t`memory needs a one-time model download (${models}, at least ${floorMb} MB total; ` +\n\t\t\t\"actual sizes come from the mirror) into <agentDir>/memory/model-cache before recall can run — \" +\n\t\t\t\"nothing downloads without user consent\"\n\t\t);\n\t};\n\tconst consentAskActions = (): readonly string[] => [\n\t\t\"Ask the user whether to download the memory models now\",\n\t\t'With consent, call memory_enable with action \"download\"',\n\t\t'If the user declines, call memory_enable with action \"decline\" (persists memory off; set memory.mode in settings.json later to re-enable)',\n\t];\n\tconst consentAskBlock = (): string =>\n\t\t[\n\t\t\t\"<memory_setup>\",\n\t\t\tconsentAskMessage(),\n\t\t\t\"Ask the user (in the conversation language) whether to download now; relay that it is one-time and the size.\",\n\t\t\t...consentAskActions()\n\t\t\t\t.slice(1)\n\t\t\t\t.map((line) => `- ${line}`),\n\t\t\t\"</memory_setup>\",\n\t\t].join(\"\\n\");\n\t// 无副作用探测: 初始态是 enabling, 而征询态只在 vectorEnsure 探测后落定——\n\t// 自动召回钩子首轮就要给出征询注入, 这里只做模型文件存在性检查 (纯本地\n\t// stat), 缺失即落定 consent-required, 绝不触发下载/加载。\n\tconst primeConsentGate = (): void => {\n\t\tif (consentGranted || consentDeclined || vectorState !== \"enabling\") return;\n\t\tif (\n\t\t\tenablingOverride?.embeddingLoadImpl !== undefined ||\n\t\t\tenablingOverride?.rerankerLoadImpl !== undefined ||\n\t\t\t// 服务装配缝的模型声明 (Slice B2): 与 vectorEnsure 装配分支同一豁免 —\n\t\t\t// 声明在位时文件检查让位, 征询门不应被 auto-recall 钩子提前翻起。\n\t\t\tinferenceServiceModelsInPlace === true\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tconst preset = vectorPresetForMode(memoryMode);\n\t\tconst modelCacheDir = join(agentDir, \"memory\", VECTOR_MODEL_CACHE_DIRNAME);\n\t\tconst modelsMissing =\n\t\t\tmodelFilesCheck(modelCacheDir, preset.embeddingModelId, MODEL_MIN_WEIGHT_BYTES[memoryMode]) === \"missing\" ||\n\t\t\tmodelFilesCheck(modelCacheDir, VECTOR_RERANKER_MODEL_ID, RERANKER_MIN_WEIGHT_BYTES) === \"missing\";\n\t\tif (!modelsMissing) return;\n\t\tvectorState = \"consent-required\";\n\t\tconsentNeededInfo = {\n\t\t\tmodels: [\n\t\t\t\tpreset.embeddingModelId,\n\t\t\t\t...(modelFilesCheck(modelCacheDir, VECTOR_RERANKER_MODEL_ID, RERANKER_MIN_WEIGHT_BYTES) === \"missing\"\n\t\t\t\t\t? [VECTOR_RERANKER_MODEL_ID]\n\t\t\t\t\t: []),\n\t\t\t],\n\t\t\tapproximateBytes: MODEL_MIN_WEIGHT_BYTES[memoryMode] + RERANKER_MIN_WEIGHT_BYTES,\n\t\t};\n\t};\n\tlet vectorInitPromise: Promise<ActiveVectorChannelV1 | undefined> | undefined;\n\n\t/**\n\t * 开启状态机 (设计 §3.2, 惰性单飞): 本地检查 (native .node 可解析 → 重依赖\n\t * 供给 (lancedb/transformers: 宿主入口路径或插件位置自解析) → 模型文件存在\n\t * 与大小 → 磁盘余量) → transformers 加载 (自带下载, 进度周期性\n\t * 落一行日志) → 冒烟 (embed 一条 + getStoredModelId 与档位比对) → ready。\n\t * 任一步失败 → failed (原因 + 五选一行动清单), mode 记录回退 off, 本实例\n\t * 不再重试。\n\t */\n\t/** 服务模式持有的 IPC 客户端 (断连自愈检测用; 本地装配路径恒 undefined)。 */\n\tlet inferenceClient: MemoryInferenceClientV1 | undefined;\n\n\tconst vectorEnsure = (): Promise<ActiveVectorChannelV1 | undefined> => {\n\t\tif (vectorState === \"ready\" || vectorState === \"degraded\") {\n\t\t\t// 服务模式断连自愈 (Slice B2): 缓存 channel 背后的 IPC 客户端死亡时\n\t\t\t// 清缓存重走装配 (重连 + 必要时重拉起服务), 而不是拿着死连接报错。\n\t\t\tif (inferenceClient === undefined || inferenceClient.isAlive()) return Promise.resolve(vectorChannel);\n\t\t\tlogger?.warn(\"memory inference service connection lost; reconnecting\");\n\t\t\tinferenceClient = undefined;\n\t\t\tvectorChannel = undefined;\n\t\t\tvectorState = \"enabling\";\n\t\t\tvectorInitPromise = undefined;\n\t\t}\n\t\tif (vectorState === \"failed\") return Promise.resolve(undefined);\n\t\tif (vectorInitPromise !== undefined) return vectorInitPromise;\n\t\tvectorInitPromise = (async (): Promise<ActiveVectorChannelV1 | undefined> => {\n\t\t\tconst preset = vectorPresetForMode(memoryMode);\n\t\t\tconst modelCacheDir = join(agentDir, \"memory\", VECTOR_MODEL_CACHE_DIRNAME);\n\t\t\tconst failEnabling = (\n\t\t\t\treason: string,\n\t\t\t\tactions: readonly string[] = enablingActionList(modelCacheDir, memoryMode),\n\t\t\t): undefined => {\n\t\t\t\tvectorState = \"failed\";\n\t\t\t\tenablingFailure = { reason, actions };\n\t\t\t\tvectorInitPromise = undefined;\n\t\t\t\tlogger?.warn(`memory enabling failed: ${reason} — actions: ${enablingFailure.actions.join(\" | \")}`, {\n\t\t\t\t\tmode: memoryMode,\n\t\t\t\t});\n\t\t\t\tenablingSettled?.();\n\t\t\t\treturn undefined;\n\t\t\t};\n\t\t\t// dispose 竞态守卫 (2026-10-06 复审遗留): teardown 与在途 enabling 竞态\n\t\t\t// 时, 装配完成点必须让位——不得把新连接/索引句柄赋回已清空的引用 (那会\n\t\t\t// 复活一条无人关闭的连接: 服务端 connections>0 抑制空闲自杀、挂住嵌入\n\t\t\t// 进程事件循环), 也不得让 enablingOutcome() 等待者悬挂。改为关闭刚取得\n\t\t\t// 的资源并落结构化 failed (MemoryEnablingFailureV1 形状)。\n\t\t\tconst failEnablingDisposed = (closeAcquired: Promise<unknown>): undefined => {\n\t\t\t\tvectorState = \"failed\";\n\t\t\t\tenablingFailure = { reason: \"capability disposed during enabling\", actions: [] };\n\t\t\t\tvectorInitPromise = undefined;\n\t\t\t\t// 与 failEnabling 同构落一行: dispose 竞态让位不再是排障不可见。\n\t\t\t\tlogger?.warn(`memory enabling aborted: ${enablingFailure.reason}`);\n\t\t\t\tvoid closeAcquired.catch((error: unknown) => {\n\t\t\t\t\tlogger?.warn(\n\t\t\t\t\t\t`memory channel close after capability dispose failed: ${\n\t\t\t\t\t\t\terror instanceof Error ? error.message : String(error)\n\t\t\t\t\t\t}`,\n\t\t\t\t\t);\n\t\t\t\t});\n\t\t\t\tenablingSettled?.();\n\t\t\t\treturn undefined;\n\t\t\t};\n\t\t\tlogger?.info(`memory enabling started (mode=${memoryMode}, embedding=${preset.embeddingModelId})`);\n\t\t\t// 检查 1: native .node sidecar (纯本地, 零网络)。宿主注入路径优先\n\t\t\t// (安装店副本自解析不可达, 见 MemoryCapabilityContext.hostOnnxRuntimeEntryPath)。\n\t\t\tconst nativeProblem = nativeBinaryCheck(hostOnnxRuntimeEntryPath);\n\t\t\tif (nativeProblem !== undefined) return failEnabling(nativeProblem);\n\t\t\t// 检查 1b: 重依赖供给。宿主入口路径优先; 未提供时插件位置自解析,\n\t\t\t// 两者都不可达 = 原本要到加载步才以 \"Cannot find module\" 泛化包装\n\t\t\t// 失败的根因, 前置到模型下载之前以 onnx 缺供分支同构的精准文案报告。\n\t\t\t// 路径已提供但包损坏的真实失败仍走加载步, 由泛化包装保留原始错误。\n\t\t\tconst missingHeavyDependencies = missingHeavyDependencyModules(\n\t\t\t\t{ lancedb: hostLancedbEntryPath, transformers: hostTransformersEntryPath },\n\t\t\t\tresolveHeavyDependencyEntryPath,\n\t\t\t);\n\t\t\tif (missingHeavyDependencies.length > 0) {\n\t\t\t\treturn failEnabling(\n\t\t\t\t\t`${missingHeavyDependencies.join(\", \")} are not provided by the host installation and could not be resolved from the plugin location; to enable memory features, install them in the host project (npm i ${missingHeavyDependencies.join(\" \")}) and restart the session`,\n\t\t\t\t);\n\t\t\t}\n\t\t\t// 检查 2: 模型文件 (缺失 = 进入下载; 存在但截断 = 失败提示手动导入)。\n\t\t\tconst embeddingProblem = modelFilesCheck(\n\t\t\t\tmodelCacheDir,\n\t\t\t\tpreset.embeddingModelId,\n\t\t\t\tMODEL_MIN_WEIGHT_BYTES[memoryMode],\n\t\t\t);\n\t\t\tconst rerankerProblem = modelFilesCheck(modelCacheDir, VECTOR_RERANKER_MODEL_ID, RERANKER_MIN_WEIGHT_BYTES);\n\t\t\tconst modelsMissing =\n\t\t\t\tembeddingProblem === \"missing\" || rerankerProblem === \"missing\"\n\t\t\t\t\t? `${preset.embeddingModelId}${rerankerProblem === \"missing\" ? ` + ${VECTOR_RERANKER_MODEL_ID}` : \"\"}`\n\t\t\t\t\t: undefined;\n\t\t\tif (embeddingProblem !== undefined && embeddingProblem !== \"missing\") return failEnabling(embeddingProblem);\n\t\t\tif (rerankerProblem !== undefined && rerankerProblem !== \"missing\") return failEnabling(rerankerProblem);\n\t\t\t// 征询门 (2026-10-05 用户裁决): 模型缺失且未经用户同意时不下载, 停在\n\t\t\t// consent-required 态等 memory_enable 工具面继续。注入 loadImpl 的测试\n\t\t\t// 缝绕过本门 (deterministic mock 门禁路径, 无网络语义)。截断文件不走\n\t\t\t// 征询 (文件在 = 曾有过一次下载意图), 仍走失败行动清单。\n\t\t\tconst hasEnablingTestSeam =\n\t\t\t\tenablingOverride?.embeddingLoadImpl !== undefined || enablingOverride?.rerankerLoadImpl !== undefined;\n\t\t\t// 服务装配缝的模型声明 (Slice B2): modelsInPlace = 测试声明模型已在位\n\t\t\t// (免写假权重文件), 文件检查与征询门相应让位; 生产路径缺省 false,\n\t\t\t// 真实文件检查与征询门语义不变。\n\t\t\tconst serviceModelsDeclared = inferenceServiceModelsInPlace === true;\n\t\t\tif (modelsMissing !== undefined && !consentGranted && !hasEnablingTestSeam && !serviceModelsDeclared) {\n\t\t\t\tvectorState = \"consent-required\";\n\t\t\t\tconsentNeededInfo = {\n\t\t\t\t\tmodels: modelsMissing.split(\" + \"),\n\t\t\t\t\tapproximateBytes: MODEL_MIN_WEIGHT_BYTES[memoryMode] + RERANKER_MIN_WEIGHT_BYTES,\n\t\t\t\t};\n\t\t\t\tvectorInitPromise = undefined;\n\t\t\t\tenablingSettled?.();\n\t\t\t\tlogger?.info(\n\t\t\t\t\t`memory models missing (${modelsMissing}); download waits for user consent (memory_enable tool)`,\n\t\t\t\t);\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\t// 服务路径不下载 (模型归服务所有); 该日志只属于本地装配的下载分支。\n\t\t\tif (modelsMissing !== undefined && !serviceModelsDeclared) {\n\t\t\t\tlogger?.info(`memory enabling: model files missing (${modelsMissing}); downloading via configured mirrors`);\n\t\t\t}\n\t\t\t// 服务装配路径 (Slice B2, 裁决 C「根治」): 模型在位且无本地装配测试缝时,\n\t\t\t// 装配经共享推理服务 — 模型与索引全机一份 (主会话 + 全部 subagent 共享),\n\t\t\t// 本进程零重依赖加载。失败按 enabling failed 呈现 (裁决 A: 不回退本地\n\t\t\t// 装配 — 回退即重开多进程风险)。loadImpl 缝走下方本地装配路径 (既有语义)。\n\t\t\tconst useInferenceService = (modelsMissing === undefined || serviceModelsDeclared) && !hasEnablingTestSeam;\n\t\t\tif (useInferenceService) {\n\t\t\t\t// 端口解析也走结构化失败: 非法 env 值若在此裸抛, vectorInitPromise\n\t\t\t\t// 直接 reject 且 failEnabling 不运行 — 状态机被钉死在 enabling,\n\t\t\t\t// 写路径 (fire-and-forget) 还会丢成 unhandled rejection。\n\t\t\t\tlet servicePort: number;\n\t\t\t\ttry {\n\t\t\t\t\tservicePort = inferenceServicePort ?? resolveMemoryInferencePort(undefined, process.env);\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn failEnabling(\n\t\t\t\t\t\t`inference service assembly failed (invalid ${MEMORY_INFERENCE_PORT_ENV}: ${\n\t\t\t\t\t\t\terror instanceof Error ? error.message : String(error)\n\t\t\t\t\t\t})`,\n\t\t\t\t\t\tserviceFailureActionList(MEMORY_INFERENCE_DEFAULT_PORT),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tlet client: MemoryInferenceClientV1 | undefined;\n\t\t\t\ttry {\n\t\t\t\t\tclient = await ensureInferenceServiceChannel({\n\t\t\t\t\t\tagentDir,\n\t\t\t\t\t\tmemoryMode,\n\t\t\t\t\t\tport: servicePort,\n\t\t\t\t\t\t...(inferenceServiceSpawnImpl === undefined ? {} : { spawnImpl: inferenceServiceSpawnImpl }),\n\t\t\t\t\t});\n\t\t\t\t\t// agentDir 身份校验 (2026-10-06 串线修复): 固定端口单例服务可能\n\t\t\t\t\t// 属于另一个 --agent-dir 的会话 (hello 此前只回报模型身份, 后连\n\t\t\t\t\t// 者握手/冒烟全过却把读写投影进对方的 LanceDB)。在冒烟与档位比\n\t\t\t\t\t// 对之前先核对身份 — 不一致或缺失都绝不触碰该服务。\n\t\t\t\t\tconst helloAgentDir: string | undefined = client.hello.agentDir;\n\t\t\t\t\tif (helloAgentDir === undefined) {\n\t\t\t\t\t\tclient.close().catch(() => undefined);\n\t\t\t\t\t\treturn failEnabling(\n\t\t\t\t\t\t\t`inference service on port ${servicePort} reports no agent-dir identity — the service was started by an older version; wait for its idle exit or stop it manually, then restart the session`,\n\t\t\t\t\t\t\tserviceFailureActionList(servicePort),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tif (normalizeMemoryAgentDirIdentity(helloAgentDir) !== normalizeMemoryAgentDirIdentity(agentDir)) {\n\t\t\t\t\t\tclient.close().catch(() => undefined);\n\t\t\t\t\t\treturn failEnabling(\n\t\t\t\t\t\t\t`inference service on port ${servicePort} belongs to agent-dir ${helloAgentDir}, this session runs in ${agentDir} — its memory projection lives in another agent-dir; wait for its idle exit or stop it manually, then restart the session`,\n\t\t\t\t\t\t\tserviceFailureActionList(servicePort),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tconst channel: ActiveVectorChannelV1 = {\n\t\t\t\t\t\tembed: client.embedProvider,\n\t\t\t\t\t\treranker: client.reranker,\n\t\t\t\t\t\tindex: client.vectorIndex,\n\t\t\t\t\t\tqueryPrefix: preset.queryPrefix,\n\t\t\t\t\t\tembeddingModelId: client.hello.embeddingModelId,\n\t\t\t\t\t};\n\t\t\t\t\t// 冒烟经 wire (服务端首次 embed 完成模型加载, 预算放宽)。\n\t\t\t\t\tawait channel.embed.embed([\"memory enabling smoke test\"]);\n\t\t\t\t\tif (client.hello.embeddingModelId !== preset.embeddingModelId) {\n\t\t\t\t\t\tclient.close().catch(() => undefined);\n\t\t\t\t\t\treturn failEnabling(\n\t\t\t\t\t\t\t`inference service runs embedding model ${client.hello.embeddingModelId}, session preset is ${preset.embeddingModelId} — the service was spawned for another memory tier; wait for its idle exit or stop it, then restart the session`,\n\t\t\t\t\t\t\tserviceFailureActionList(servicePort),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tconst storedModelId = await channel.index.getStoredModelId();\n\t\t\t\t\tif (storedModelId !== undefined && storedModelId !== preset.embeddingModelId) {\n\t\t\t\t\t\tlogger?.warn(\n\t\t\t\t\t\t\t`memory projection was built for ${storedModelId}, preset is ${preset.embeddingModelId}; startup reconciliation will rebuild it`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\t// dispose 竞态: teardown 已清引用 (capabilityDisposed) 时, 装配成功\n\t\t\t\t\t// 分支不得把新 IPC 连接赋回去——关闭它并落结构化失败, 让在途的\n\t\t\t\t\t// enablingOutcome() 等待者 (如 memory-preheat) 落定为失败而非悬挂。\n\t\t\t\t\tif (capabilityDisposed) return failEnablingDisposed(client.close());\n\t\t\t\t\tinferenceClient = client;\n\t\t\t\t\tvectorChannel = channel;\n\t\t\t\t\tvectorState = \"ready\";\n\t\t\t\t\tlogger?.info(\n\t\t\t\t\t\t`memory ready via shared inference service (mode=${memoryMode}, embedding=${preset.embeddingModelId})`,\n\t\t\t\t\t);\n\t\t\t\t\tenablingSettled?.();\n\t\t\t\t\treturn channel;\n\t\t\t\t} catch (error) {\n\t\t\t\t\t// 连接已建立后的失败 (冒烟/档位比对/getStoredModelId) 必须关掉\n\t\t\t\t\t// 客户端: 悬挂连接会让服务端 connections>0, 空闲自杀永不触发。\n\t\t\t\t\tclient?.close().catch(() => undefined);\n\t\t\t\t\treturn failEnabling(\n\t\t\t\t\t\t`inference service assembly failed (${error instanceof Error ? error.message : String(error)})`,\n\t\t\t\t\t\tserviceFailureActionList(servicePort),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\t// 检查 3: 磁盘余量 (light ≥ 500MB / full ≥ 2GB)。服务装配路径不下载, 已在上面 return。\n\t\t\tconst diskProblem = await diskHeadroomCheck(agentDir, DISK_HEADROOM_MIN_BYTES[memoryMode]);\n\t\t\tif (diskProblem !== undefined) return failEnabling(diskProblem);\n\t\t\t// dispose 竞态 (本地装配路径, 第一道): 已 teardown 就不再打开 LanceDB/\n\t\t\t// 拉起重依赖; 装配完成点还有第二道检查兜住模型下载窗口。\n\t\t\tif (capabilityDisposed) return failEnablingDisposed(Promise.resolve());\n\t\t\t// 加载: transformers/lancedb 的动态 import 都在这些模块内部, 这里只做\n\t\t\t// 模块级懒加载, 保持未触发会话零重依赖。进度周期性落一行 (下载可达\n\t\t\t// 数百 MB), 完成后清除。\n\t\t\tconst progressTimer = setInterval(() => {\n\t\t\t\tlogger?.info(\"memory enabling still in progress (downloading/loading models)\");\n\t\t\t}, ENABLING_PROGRESS_LOG_INTERVAL_MS);\n\t\t\tif (typeof progressTimer === \"object\" && \"unref\" in progressTimer) progressTimer.unref();\n\t\t\ttry {\n\t\t\t\tconst [vectorIndexModule, embeddingModule, rerankerModule] = await Promise.all([\n\t\t\t\t\timport(\"./vector-index.ts\"),\n\t\t\t\t\timport(\"./embedding-provider.ts\"),\n\t\t\t\t\timport(\"./embedding-reranker.ts\"),\n\t\t\t\t]);\n\t\t\t\tconst index = await vectorIndexModule.createMemoryVectorIndex({\n\t\t\t\t\tdbPath: join(agentDir, \"memory\", VECTOR_DB_DIRNAME),\n\t\t\t\t\tdimensions: preset.dimensions,\n\t\t\t\t\t...(hostLancedbEntryPath === undefined ? {} : { moduleEntryPath: hostLancedbEntryPath }),\n\t\t\t\t});\n\t\t\t\tconst remoteHosts = remoteHostsForEnabling();\n\t\t\t\tconst channel: ActiveVectorChannelV1 = {\n\t\t\t\t\tembed: embeddingModule.createTransformersEmbeddingProvider({\n\t\t\t\t\t\tmodelId: preset.embeddingModelId,\n\t\t\t\t\t\tdimensions: preset.dimensions,\n\t\t\t\t\t\tcacheDir: modelCacheDir,\n\t\t\t\t\t\tremoteHosts,\n\t\t\t\t\t\t...(hostTransformersEntryPath === undefined ? {} : { moduleEntryPath: hostTransformersEntryPath }),\n\t\t\t\t\t\t...(enablingOverride?.embeddingLoadImpl === undefined\n\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t: { loadImpl: enablingOverride.embeddingLoadImpl }),\n\t\t\t\t\t}),\n\t\t\t\t\treranker: rerankerModule.createTransformersReranker({\n\t\t\t\t\t\tmodelId: VECTOR_RERANKER_MODEL_ID,\n\t\t\t\t\t\tcacheDir: modelCacheDir,\n\t\t\t\t\t\tremoteHosts,\n\t\t\t\t\t\t...(hostTransformersEntryPath === undefined ? {} : { moduleEntryPath: hostTransformersEntryPath }),\n\t\t\t\t\t\t...(enablingOverride?.rerankerLoadImpl === undefined\n\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t: { loadImpl: enablingOverride.rerankerLoadImpl }),\n\t\t\t\t\t}),\n\t\t\t\t\tindex,\n\t\t\t\t\tqueryPrefix: preset.queryPrefix,\n\t\t\t\t\tembeddingModelId: preset.embeddingModelId,\n\t\t\t\t};\n\t\t\t\t// 冒烟: embed + rerank 各一条 (同时完成两个模型的下载与加载) +\n\t\t\t\t// 投影档位比对。rerank 冒烟 2026-10-06 live E2E 补齐: reranker\n\t\t\t\t// 懒加载, 只 embed 的冒烟会让 \"ready\" 携带未下载的精排权重 —\n\t\t\t\t// 共享推理服务 (两项文件均前置检查、永不自主下载) 对该会话拒启,\n\t\t\t\t// \"fully usable\" 的自述与服务前置条件必须一致。\n\t\t\t\tawait channel.embed.embed([\"memory enabling smoke test\"]);\n\t\t\t\tif (channel.embed.modelId !== preset.embeddingModelId) {\n\t\t\t\t\treturn failEnabling(\n\t\t\t\t\t\t`smoke check failed: embedding modelId ${channel.embed.modelId} does not match the ${memoryMode} preset ${preset.embeddingModelId}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (channel.reranker !== undefined) {\n\t\t\t\t\tawait channel.reranker.rerank(\"memory enabling smoke test\", [\"memory enabling smoke test\"]);\n\t\t\t\t}\n\t\t\t\tconst storedModelId = await channel.index.getStoredModelId();\n\t\t\t\tif (storedModelId !== undefined && storedModelId !== preset.embeddingModelId) {\n\t\t\t\t\tlogger?.warn(\n\t\t\t\t\t\t`memory projection was built for ${storedModelId}, preset is ${preset.embeddingModelId}; startup reconciliation will rebuild it`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\t// dispose 竞态 (本地装配路径, 第二道, 兜住模型下载窗口): 不把索引句柄\n\t\t\t\t// 赋回引用——关闭刚打开的 LanceDB 并落结构化失败。\n\t\t\t\tif (capabilityDisposed) return failEnablingDisposed(channel.index.close());\n\t\t\t\tvectorChannel = channel;\n\t\t\t\tvectorState = \"ready\";\n\t\t\t\tlogger?.info(`memory ready (mode=${memoryMode}, embedding=${preset.embeddingModelId})`);\n\t\t\t\tenablingSettled?.();\n\t\t\t\treturn channel;\n\t\t\t} catch (error) {\n\t\t\t\treturn failEnabling(\n\t\t\t\t\t`model load or smoke check failed (${error instanceof Error ? error.message : String(error)})`,\n\t\t\t\t);\n\t\t\t} finally {\n\t\t\t\tclearInterval(progressTimer);\n\t\t\t}\n\t\t})();\n\t\treturn vectorInitPromise;\n\t};\n\n\t// ---- 征询门执行面 (2026-10-05 用户裁决「首次使用征询、拒绝/失败可跳过」) ----\n\t// memory_enable 是 consent-required / failed 态的唯一下载入口: consentGranted\n\t// 只在这里置位, recall/auto-recall 永不触发下载。decline 同时持久化\n\t// (writeMemoryConsentDeclined), 只抑制默认档——用户显式设置 memory.mode 后\n\t// 下次启用会在首次使用时再次走到征询门。\n\t// ---- 记忆模型下载控制面 (2026-10-05 流程裁决「后台预热、不阻塞提问」) ----\n\t// 生产入口 (交互模式会话绑定后) 经公共工具面调用 memory_enable download\n\t// 触发后台预热; 命令面 /memory off|retry 是用户的直接出口。两处共用同一对\n\t// 闭包; decline 持久化只抑制默认档。\n\tconst declineMemory = (): { status: \"completed\"; message: string } => {\n\t\t// 总是落盘 (幂等写): 升降档会清理文件里的拒绝标记, 之后再次 off 必须\n\t\t// 重新写入——不能用内存 flag 跳过持久化。\n\t\tconst firstDecline = !consentDeclined;\n\t\tconsentDeclined = true;\n\t\twriteMemoryConsentDeclined(agentDir);\n\t\tif (firstDecline) {\n\t\t\tlogger?.info(\"memory disabled by user decision (persisted to the memory agent-dir config)\");\n\t\t}\n\t\treturn {\n\t\t\tstatus: \"completed\",\n\t\t\tmessage:\n\t\t\t\t\"memory disabled for this machine (persisted). Set memory.mode (light|full) in settings.json and restart the session to re-enable\",\n\t\t};\n\t};\n\tconst downloadMemory = async (): Promise<\n\t\t| { status: \"completed\"; message: string }\n\t\t| { status: \"failed\"; message: string; actions?: readonly string[]; next?: string }\n\t> => {\n\t\tif (consentDeclined) {\n\t\t\treturn {\n\t\t\t\tstatus: \"failed\",\n\t\t\t\tmessage:\n\t\t\t\t\t\"memory was declined on this machine — set memory.mode (light|full) in settings.json and restart the session to re-enable\",\n\t\t\t};\n\t\t}\n\t\tconsentGranted = true;\n\t\tif (vectorState === \"failed\" || vectorState === \"consent-required\") {\n\t\t\tvectorState = \"enabling\";\n\t\t\tenablingFailure = undefined;\n\t\t\tvectorInitPromise = undefined;\n\t\t}\n\t\tconst channel = await vectorEnsure();\n\t\tif (channel === undefined) {\n\t\t\tconst failure = enablingFailure ?? {\n\t\t\t\treason: `memory enabling did not complete (state=${vectorState})`,\n\t\t\t\tactions: [] as const,\n\t\t\t};\n\t\t\treturn {\n\t\t\t\tstatus: \"failed\",\n\t\t\t\tmessage: `memory enabling failed: ${failure.reason}`,\n\t\t\t\tactions: failure.actions,\n\t\t\t\tnext: 'Tell the user the download failed and ask whether to skip memory (call memory_enable with action \"decline\" or /memory off — both persist off) or fix the environment and retry (/memory retry)',\n\t\t\t};\n\t\t}\n\t\t// 就绪: 补跑启动对账, 把预热期间写入的 ledger 记忆补进向量投影。\n\t\tresetReconcile();\n\t\treconcileOnce();\n\t\treturn { status: \"completed\", message: \"memory models ready — the memory family is fully usable\" };\n\t};\n\n\t// 会话切换重绑/插件卸载的共享资源释放 (TUI 每次会话切换都重走装配, 不释放\n\t// 即每次泄漏一条 IPC 连接: 服务端 connections>0 抑制空闲自杀, 嵌入方进程因\n\t// socket 未关无法自然退出)。清引用先行: close 的 reject 兜底 warn 一行, 且\n\t// 二次调用因引用已空自然 no-op。服务路径与本地路径互斥 (服务路径的 index\n\t// 归服务进程持有, 客户端只断连; 本地路径才关 LanceDB 句柄)。\n\t// capabilityDisposed 是 teardown 与在途 enabling 的竞态闩锁: teardown 之后\n\t// 才完成的装配在成功分支让位 (见 vectorEnsure 的 failEnablingDisposed),\n\t// 不复活无人关闭的连接/句柄。\n\tlet capabilityDisposed = false;\n\tconst capabilityTeardown = (): void => {\n\t\tcapabilityDisposed = true;\n\t\tif (inferenceClient !== undefined) {\n\t\t\tconst client = inferenceClient;\n\t\t\tinferenceClient = undefined;\n\t\t\tvectorChannel = undefined;\n\t\t\tvoid client.close().catch((error: unknown) => {\n\t\t\t\tlogger?.warn(\n\t\t\t\t\t`memory inference client close failed: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t\t);\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tif (vectorChannel !== undefined) {\n\t\t\tconst channel = vectorChannel;\n\t\t\tvectorChannel = undefined;\n\t\t\tvoid channel.index.close().catch((error: unknown) => {\n\t\t\t\tlogger?.warn(`memory vector index close failed: ${error instanceof Error ? error.message : String(error)}`);\n\t\t\t});\n\t\t}\n\t};\n\n\treturn {\n\t\tstate: (): \"off\" | MemoryCapabilityStateV1 => (consentDeclined ? \"off\" : vectorState),\n\t\trawState: (): MemoryCapabilityStateV1 => vectorState,\n\t\tenabled: vectorEnabled,\n\t\treadyChannel: (): ActiveVectorChannelV1 | undefined => vectorChannel,\n\t\tisDisposed: (): boolean => capabilityDisposed,\n\t\tdeclined: (): boolean => consentDeclined,\n\t\tclearDeclined: (): void => {\n\t\t\tconsentDeclined = false;\n\t\t},\n\t\tconsentAsked: (): boolean => consentAsked,\n\t\tmarkConsentAsked: (): void => {\n\t\t\tconsentAsked = true;\n\t\t},\n\t\tprimeConsentGate,\n\t\tconsentAsk: (): MemoryConsentAskV1 | undefined =>\n\t\t\tvectorState === \"consent-required\" && consentNeededInfo !== undefined\n\t\t\t\t? { message: consentAskMessage(), actions: consentAskActions(), block: consentAskBlock() }\n\t\t\t\t: undefined,\n\t\twarming: (): boolean => vectorState === \"enabling\" && vectorInitPromise !== undefined && !consentDeclined,\n\t\tfailure: (): MemoryEnablingFailureV1 | undefined => enablingFailure,\n\t\tmarkDegraded: (): void => {\n\t\t\tvectorState = \"degraded\";\n\t\t},\n\t\trecoverDegraded: (): void => {\n\t\t\tif (vectorState === \"degraded\") vectorState = \"ready\";\n\t\t},\n\t\tensure: vectorEnsure,\n\t\tenablingOutcome: async (): Promise<\"ready\" | MemoryEnablingFailureV1> => {\n\t\t\tif (vectorState === \"enabling\") void vectorEnsure();\n\t\t\tawait enablingSettledPromise;\n\t\t\treturn enablingFailure ?? \"ready\";\n\t\t},\n\t\tdecline: declineMemory,\n\t\tdownload: downloadMemory,\n\t\tdispose: capabilityTeardown,\n\t};\n}\n"]}
|
|
1
|
+
{"version":3,"file":"vector-channel.d.ts","sourceRoot":"","sources":["../../src/memory/vector-channel.ts"],"names":[],"mappings":"AAAA;;GAEG;AAGH,OAAO,KAAK,EACX,aAAa,EACb,wBAAwB,EACxB,gCAAgC,EAChC,MAAM,yBAAyB,CAAC;AAmBjC,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AAsBpE,8FAAiD;AACjD,eAAO,MAAM,wBAAwB,6BAA6B,CAAC;AACnE,eAAO,MAAM,iBAAiB,WAAW,CAAC;AAC1C,eAAO,MAAM,0BAA0B,gBAAgB,CAAC;AAExD,wGAA2D;AAC3D,MAAM,MAAM,uBAAuB,GAAG,kBAAkB,GAAG,UAAU,GAAG,OAAO,GAAG,UAAU,GAAG,QAAQ,CAAC;AAExG,+FAAoD;AACpD,MAAM,WAAW,uBAAuB;IACvC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,OAAO,EAAE,SAAS,MAAM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,EAAE,MAAM,CAAA;KAAE,CAAC;IACpD,8EAA8C;IAC9C,QAAQ,IAAI,OAAO,CAChB;QAAE,MAAM,EAAE,WAAW,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,GACxC;QAAE,MAAM,EAAE,QAAQ,CAAC;QAAC,OAAO,EAAE,MAAM,CAAC;QAAC,OAAO,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,CAAA;KAAE,CACnF,CAAC;IACF,yEAA+C;IAC/C,OAAO,IAAI,IAAI,CAAC;CAChB;AAED,wBAAgB,yBAAyB,CAAC,IAAI,EAAE,yBAAyB,GAAG,qBAAqB,CAqkBhG","sourcesContent":["/**\n * 向量通道状态机(capability 拆分战役 slice 3b):vectorEnsure 状态转换、装配分支(服务/本地/下载/征询门)、dispose 闩锁。共享闭包状态收拢为 channel 对象, 经 deps 显式注入; 降级/投影经 slice 3a 的 vector-projection 上报\n */\n\nimport { join } from \"node:path\";\nimport type {\n\tCapabilityAPI,\n\tMemoryEnablingOverrideV1,\n\tMemoryVectorComponentsOverrideV1,\n} from \"@agent-forge/plugin-sdk\";\nimport {\n\tDISK_HEADROOM_MIN_BYTES,\n\tdiskHeadroomCheck,\n\tenablingActionList,\n\tMODEL_MIN_WEIGHT_BYTES,\n\tmissingHeavyDependencyModules,\n\tmodelFilesCheck,\n\tnativeBinaryCheck,\n\tnormalizeMemoryAgentDirIdentity,\n\tRERANKER_MIN_WEIGHT_BYTES,\n\tremoteHostsForEnabling,\n\tresolveHeavyDependencyEntryPath,\n\tvectorPresetForMode,\n\twriteMemoryConsentDeclined,\n} from \"./enabling.ts\";\nimport { ensureInferenceServiceChannel, serviceFailureActionList } from \"./inference-channel.ts\";\nimport { type MemoryInferenceClientV1, resolveMemoryInferencePort } from \"./inference-client.ts\";\nimport { MEMORY_INFERENCE_DEFAULT_PORT, MEMORY_INFERENCE_PORT_ENV } from \"./inference-protocol.ts\";\nimport type { ActiveVectorChannelV1 } from \"./vector-projection.ts\";\n\n/** enabling 加载/下载期间的周期性进度日志间隔。 */\nconst ENABLING_PROGRESS_LOG_INTERVAL_MS = 15_000;\n\n// 宿主先撤销 CapabilityAPI 再调用 disposer。清理诊断不得依赖已撤销的 logger,\n// 也不得因诊断输出失败而中断其他资源释放或替换原始装配错误。\nfunction reportCleanupFailure(resource: string, error: unknown): void {\n\ttry {\n\t\tconsole.error(`memory ${resource} close failed`, error);\n\t} catch {\n\t\t// 诊断接收端不可用不改变资源生命周期。\n\t}\n}\n\nfunction closeResource(resource: string, close: () => unknown): Promise<void> {\n\treturn Promise.resolve()\n\t\t.then(close)\n\t\t.then(() => undefined)\n\t\t.catch((error: unknown) => reportCleanupFailure(resource, error));\n}\n\n/** 两档共用精排模型 (POC 报告 §8: 官方 Xenova 转换版唯一实测可用)。 */\nexport const VECTOR_RERANKER_MODEL_ID = \"Xenova/bge-reranker-base\";\nexport const VECTOR_DB_DIRNAME = \"vector\";\nexport const VECTOR_MODEL_CACHE_DIRNAME = \"model-cache\";\n\n/** capability 级状态机 (设计 §3.2): off 只出现在模式关闭 (零注册, 不可观测)。 */\nexport type MemoryCapabilityStateV1 = \"consent-required\" | \"enabling\" | \"ready\" | \"degraded\" | \"failed\";\n\n/** enabling 失败的结构化结果: 原因 + 行动清单 (硬性要求, 设计 §3.2)。 */\nexport interface MemoryEnablingFailureV1 {\n\treadonly reason: string;\n\treadonly actions: readonly string[];\n}\n\n/**\n * 征询门待决信息 (2026-10-05 用户裁决「首次使用征询、拒绝即持久化关闭」):\n * 向量通道从未就绪且模式已启用时, 模型下载必须先经用户同意——检索不触发下载,\n * 由 AI 转述征询后经 memory_enable 工具面继续。\n */\nexport interface MemoryConsentNeededV1 {\n\treadonly models: readonly string[];\n\t/** 模型权重体积下限之和 (非精确体积; 实际下载量以镜像文件为准)。 */\n\treadonly approximateBytes: number;\n}\n\n/** 征询面 (consent-required 态的模型可见包): AI 转述话术 + 后续动作 + 注入块。 */\nexport interface MemoryConsentAskV1 {\n\treadonly message: string;\n\treadonly actions: readonly string[];\n\treadonly block: string;\n}\n\n/**\n * 向量通道对 capability 装配上下文的显式依赖视图 (slice 3b): 逐项来自\n * createMemoryCapabilityHarness 的闭包捕获核实, 不再经共享闭包隐式可达。\n */\nexport interface MemoryVectorChannelDepsV1 {\n\t/** agent 根目录 (MemoryCapabilityContext.agentDir): 模型缓存/索引/征询持久化的路径域。 */\n\treadonly agentDir: string;\n\t/** 已解析的全局档位 (harness memoryMode, off 已被工厂入口拦截)。 */\n\treadonly memoryMode: \"light\" | \"full\";\n\t/** capability 日志面 (api.logger): 进度/失败/自愈日志。 */\n\treadonly logger: CapabilityAPI[\"logger\"];\n\t/** 宿主注入的 onnxruntime-node 入口 (MemoryCapabilityContext.hostOnnxRuntimeEntryPath)。 */\n\treadonly hostOnnxRuntimeEntryPath?: string;\n\t/** 宿主注入的 @lancedb/lancedb 入口 (MemoryCapabilityContext.hostLancedbEntryPath)。 */\n\treadonly hostLancedbEntryPath?: string;\n\t/** 宿主注入的 @huggingface/transformers 入口 (MemoryCapabilityContext.hostTransformersEntryPath)。 */\n\treadonly hostTransformersEntryPath?: string;\n\t/** 服务装配缝 (Slice B2): 测试端口直连 (MemoryCapabilityContext.inferenceService.port)。 */\n\treadonly inferenceServicePort?: number;\n\t/** 服务装配缝 (Slice B2): 替换进程拉起的测试缝 (inferenceService.spawnImpl)。 */\n\treadonly inferenceServiceSpawnImpl?: (\n\t\tagentDir: string,\n\t\tmode: \"light\" | \"full\",\n\t\tport: number,\n\t\t/** spawn 异步失败 (EACCES/ENOMEM 等) 的回调; 缺省实现经 child 'error' 事件馈入。 */\n\t\tonError?: (error: Error) => void,\n\t) => Promise<void>;\n\t/** 服务装配缝 (Slice B2): 声明模型在位, 文件检查与征询门让位 (inferenceService.modelsInPlace)。 */\n\treadonly inferenceServiceModelsInPlace?: boolean;\n\t/** enabling 测试缝 (loadImpl 重定向模型加载); undefined = 生产路径。 */\n\treadonly enablingOverride?: MemoryEnablingOverrideV1;\n\t/** 组件注入 (deterministic mock 门禁): 存在时通道直接 ready, 跳过真实装配。 */\n\treadonly injectedComponents?: MemoryVectorComponentsOverrideV1;\n\t/** 写侧投影 (slice 3a 的 vectorProjection.resetReconcile): downloadMemory 就绪后重臂启动对账。 */\n\treadonly resetReconcile: () => void;\n\t/** 写侧投影 (slice 3a 的 vectorProjection.reconcileOnce): downloadMemory 就绪后补跑对账。 */\n\treadonly reconcileOnce: () => void;\n}\n\nexport interface MemoryVectorChannelV1 {\n\t/** harness.vectorState 面: 征询拒绝时投影为 \"off\" (本实例按模式关闭对待)。 */\n\tstate(): \"off\" | MemoryCapabilityStateV1;\n\t/** vectorState 原值 (未做 declined 投影; recall/合并探测等内部消费)。 */\n\trawState(): MemoryCapabilityStateV1;\n\t/** vectorEnabled: failed/consent-required/declined 时 false (写侧埋点门)。 */\n\tenabled(): boolean;\n\t/** 已就绪通道的同步快照 (vectorChannel 只读; projection.readyChannel 面)。 */\n\treadyChannel(): ActiveVectorChannelV1 | undefined;\n\t/** dispose 闩锁只读视图 (capabilityDisposed; projection.isDisposed 面)。 */\n\tisDisposed(): boolean;\n\t/** 征询拒绝标记 (declineMemory 持久化后的本实例内存面)。 */\n\tdeclined(): boolean;\n\t/** 用户显式再启用 (/memory light|full、自动升档) 清除本实例拒绝标记。 */\n\tclearDeclined(): void;\n\t/** 征询一次性注入钉住标记 (auto-recall 每实例只注入一次)。 */\n\tconsentAsked(): boolean;\n\tmarkConsentAsked(): void;\n\t/** 无副作用征询探测 (auto-recall 首轮; 纯本地 stat, 绝不触发下载/加载)。 */\n\tprimeConsentGate(): void;\n\t/** 征询待决面 (consent-required 且待决信息就位时非 undefined; 纯只读, 不探测)。 */\n\tconsentAsk(): MemoryConsentAskV1 | undefined;\n\t/** warming 守卫 (recall 后台预热不阻塞读侧): 装配在途且未拒绝。 */\n\twarming(): boolean;\n\t/** enabling 失败结构化结果 (未失败 = undefined)。 */\n\tfailure(): MemoryEnablingFailureV1 | undefined;\n\t/** 运行期故障 → degraded (可自愈; recall 与投影对账共用)。 */\n\tmarkDegraded(): void;\n\t/** degraded → ready 的自愈转换 (仅从 degraded; 全通 recall 成功后调用)。 */\n\trecoverDegraded(): void;\n\t/** vectorEnsure: 惰性单飞装配 (recall/write/埋点/对账的公共入口)。 */\n\tensure(): Promise<ActiveVectorChannelV1 | undefined>;\n\t/** harness.enablingOutcome 面: 触发惰性 enabling 并等待落定 (ready 或结构化失败)。 */\n\tenablingOutcome(): Promise<\"ready\" | MemoryEnablingFailureV1>;\n\t/** declineMemory 核心: 持久化拒绝 + 本实例按模式关闭。 */\n\tdecline(): { status: \"completed\"; message: string };\n\t/** downloadMemory 核心: 置征询同意 + 装配 + 补跑启动对账。 */\n\tdownload(): Promise<\n\t\t| { status: \"completed\"; message: string }\n\t\t| { status: \"failed\"; message: string; actions?: readonly string[]; next?: string }\n\t>;\n\t/** capabilityTeardown 本体: 资源关闭 + 闩锁置位 (幂等)。 */\n\tdispose(): void;\n}\n\nexport function createMemoryVectorChannel(deps: MemoryVectorChannelDepsV1): MemoryVectorChannelV1 {\n\tconst {\n\t\tagentDir,\n\t\tmemoryMode,\n\t\tlogger,\n\t\thostOnnxRuntimeEntryPath,\n\t\thostLancedbEntryPath,\n\t\thostTransformersEntryPath,\n\t\tinferenceServicePort,\n\t\tinferenceServiceSpawnImpl,\n\t\tinferenceServiceModelsInPlace,\n\t\tenablingOverride,\n\t\tinjectedComponents,\n\t\tresetReconcile,\n\t\treconcileOnce,\n\t} = deps;\n\t// ---- 语义召回通道 (2.4d6 S1/S2; 召回唯一检索路径) ----\n\t// 状态机 (设计 §3.2): enabling = 检查/加载进行中 (惰性触发: 首次向量操作\n\t// 时真正执行); ready = 可用; degraded = ready 后运行期故障 (可自愈回\n\t// ready); failed = enabling 失败, 本实例内终态 (mode 回退 off, 记忆工具\n\t// 返回携带行动清单的不可用 packet, 不再重试)。所有写侧操作经 vectorQueue\n\t// 串行化, 避免 reconcile 与写入埋点在 LanceDB 建表上竞态; recall 等待\n\t// enabling 单飞完成, 不与后台对账并发读索引。transformers/lancedb 的动态\n\t// import 只出现在 vectorEnsure 的装配分支里 (type-position 引类型), 未\n\t// 触发时不加载任何重依赖。\n\tlet vectorState: MemoryCapabilityStateV1 = \"enabling\";\n\tlet vectorChannel: ActiveVectorChannelV1 | undefined;\n\tlet enablingFailure: MemoryEnablingFailureV1 | undefined;\n\tlet enablingSettled: (() => void) | undefined;\n\t// 征询门 (2026-10-05 用户裁决「首次使用征询、拒绝即持久化关闭」): 模型文件\n\t// 缺失时下载必须先经用户同意——consentGranted 只由 memory_enable 工具面置位;\n\t// consentDeclined = 本实例内用户拒绝/跳过 (同时持久化, 见\n\t// writeMemoryConsentDeclined), 之后本实例按模式关闭对待; consentAsked 钉住\n\t// 自动召回的一次性征询注入, 不随查询文本翻新。\n\tlet consentGranted = false;\n\tlet consentDeclined = false;\n\tlet consentAsked = false;\n\tlet consentNeededInfo: MemoryConsentNeededV1 | undefined;\n\tconst enablingSettledPromise = new Promise<\"ready\" | MemoryEnablingFailureV1>((resolve) => {\n\t\tenablingSettled = () => resolve(enablingFailure ?? \"ready\");\n\t});\n\tif (injectedComponents !== undefined) {\n\t\t// 测试注入: 直接 ready, 跳过真实装配与档位解析。\n\t\tvectorState = \"ready\";\n\t\tvectorChannel = {\n\t\t\tembed: injectedComponents.embedProvider,\n\t\t\treranker: injectedComponents.reranker,\n\t\t\tindex: injectedComponents.vectorIndex,\n\t\t\tqueryPrefix: injectedComponents.queryPrefix ?? \"\",\n\t\t\tembeddingModelId: injectedComponents.embedProvider.modelId,\n\t\t};\n\t\tenablingSettled?.();\n\t}\n\tconst vectorEnabled = (): boolean =>\n\t\tvectorState !== \"failed\" && vectorState !== \"consent-required\" && !consentDeclined;\n\t// 尚未发布的本地资源也归本实例拥有;teardown 立即标记 provider 关闭。\n\tlet closeOwnedLocalResources: (() => Promise<void>) | undefined;\n\tconst closeLocalChannel = async (channel: ActiveVectorChannelV1): Promise<void> => {\n\t\tconst results = await Promise.allSettled([\n\t\t\tPromise.resolve().then(() => channel.index.close()),\n\t\t\t(async () => channel.embed.dispose?.())(),\n\t\t\t(async () => channel.reranker?.dispose?.())(),\n\t\t]);\n\t\tconst resources = [\"vector index\", \"embedding provider\", \"reranker\"];\n\t\tfor (const [index, result] of results.entries()) {\n\t\t\tif (result.status === \"rejected\") reportCleanupFailure(resources[index]!, result.reason);\n\t\t}\n\t};\n\t// 征询话术 (AI 转述给用户; 会话语言由 AI 决定): 模型清单 + 体积下限 + 两个\n\t// 后续动作。consent-required 态下的 recall packet、auto-recall 注入块共用。\n\tconst consentAskMessage = (): string => {\n\t\tconst info = consentNeededInfo;\n\t\tconst models = info === undefined ? \"embedding + reranker\" : info.models.join(\" + \");\n\t\tconst floorMb = Math.ceil(\n\t\t\t(info?.approximateBytes ?? MODEL_MIN_WEIGHT_BYTES[memoryMode] + RERANKER_MIN_WEIGHT_BYTES) / (1024 * 1024),\n\t\t);\n\t\treturn (\n\t\t\t`memory needs a one-time model download (${models}, at least ${floorMb} MB total; ` +\n\t\t\t\"actual sizes come from the mirror) into <agentDir>/memory/model-cache before recall can run — \" +\n\t\t\t\"nothing downloads without user consent\"\n\t\t);\n\t};\n\tconst consentAskActions = (): readonly string[] => [\n\t\t\"Ask the user whether to download the memory models now\",\n\t\t'With consent, call memory_enable with action \"download\"',\n\t\t'If the user declines, call memory_enable with action \"decline\" (persists memory off; set memory.mode in settings.json later to re-enable)',\n\t];\n\tconst consentAskBlock = (): string =>\n\t\t[\n\t\t\t\"<memory_setup>\",\n\t\t\tconsentAskMessage(),\n\t\t\t\"Ask the user (in the conversation language) whether to download now; relay that it is one-time and the size.\",\n\t\t\t...consentAskActions()\n\t\t\t\t.slice(1)\n\t\t\t\t.map((line) => `- ${line}`),\n\t\t\t\"</memory_setup>\",\n\t\t].join(\"\\n\");\n\t// 无副作用探测: 初始态是 enabling, 而征询态只在 vectorEnsure 探测后落定——\n\t// 自动召回钩子首轮就要给出征询注入, 这里只做模型文件存在性检查 (纯本地\n\t// stat), 缺失即落定 consent-required, 绝不触发下载/加载。\n\tconst primeConsentGate = (): void => {\n\t\tif (consentGranted || consentDeclined || vectorState !== \"enabling\") return;\n\t\tif (\n\t\t\tenablingOverride?.embeddingLoadImpl !== undefined ||\n\t\t\tenablingOverride?.rerankerLoadImpl !== undefined ||\n\t\t\t// 服务装配缝的模型声明 (Slice B2): 与 vectorEnsure 装配分支同一豁免 —\n\t\t\t// 声明在位时文件检查让位, 征询门不应被 auto-recall 钩子提前翻起。\n\t\t\tinferenceServiceModelsInPlace === true\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tconst preset = vectorPresetForMode(memoryMode);\n\t\tconst modelCacheDir = join(agentDir, \"memory\", VECTOR_MODEL_CACHE_DIRNAME);\n\t\tconst modelsMissing =\n\t\t\tmodelFilesCheck(modelCacheDir, preset.embeddingModelId, MODEL_MIN_WEIGHT_BYTES[memoryMode]) === \"missing\" ||\n\t\t\tmodelFilesCheck(modelCacheDir, VECTOR_RERANKER_MODEL_ID, RERANKER_MIN_WEIGHT_BYTES) === \"missing\";\n\t\tif (!modelsMissing) return;\n\t\tvectorState = \"consent-required\";\n\t\tconsentNeededInfo = {\n\t\t\tmodels: [\n\t\t\t\tpreset.embeddingModelId,\n\t\t\t\t...(modelFilesCheck(modelCacheDir, VECTOR_RERANKER_MODEL_ID, RERANKER_MIN_WEIGHT_BYTES) === \"missing\"\n\t\t\t\t\t? [VECTOR_RERANKER_MODEL_ID]\n\t\t\t\t\t: []),\n\t\t\t],\n\t\t\tapproximateBytes: MODEL_MIN_WEIGHT_BYTES[memoryMode] + RERANKER_MIN_WEIGHT_BYTES,\n\t\t};\n\t};\n\tlet vectorInitPromise: Promise<ActiveVectorChannelV1 | undefined> | undefined;\n\n\t/**\n\t * 开启状态机 (设计 §3.2, 惰性单飞): 本地检查 (native .node 可解析 → 重依赖\n\t * 供给 (lancedb/transformers: 宿主入口路径或插件位置自解析) → 模型文件存在\n\t * 与大小 → 磁盘余量) → transformers 加载 (自带下载, 进度周期性\n\t * 落一行日志) → 冒烟 (embed 一条 + getStoredModelId 与档位比对) → ready。\n\t * 任一步失败 → failed (原因 + 五选一行动清单), mode 记录回退 off, 本实例\n\t * 不再重试。\n\t */\n\t/** 服务模式持有的 IPC 客户端 (断连自愈检测用; 本地装配路径恒 undefined)。 */\n\tlet inferenceClient: MemoryInferenceClientV1 | undefined;\n\n\tconst vectorEnsure = (): Promise<ActiveVectorChannelV1 | undefined> => {\n\t\tif (capabilityDisposed) {\n\t\t\tvectorState = \"failed\";\n\t\t\tenablingFailure ??= { reason: \"capability disposed during enabling\", actions: [] };\n\t\t\tenablingSettled?.();\n\t\t\treturn Promise.resolve(undefined);\n\t\t}\n\t\tif (vectorState === \"ready\" || vectorState === \"degraded\") {\n\t\t\t// 服务模式断连自愈 (Slice B2): 缓存 channel 背后的 IPC 客户端死亡时\n\t\t\t// 清缓存重走装配 (重连 + 必要时重拉起服务), 而不是拿着死连接报错。\n\t\t\tif (inferenceClient === undefined || inferenceClient.isAlive()) return Promise.resolve(vectorChannel);\n\t\t\tlogger?.warn(\"memory inference service connection lost; reconnecting\");\n\t\t\tinferenceClient = undefined;\n\t\t\tvectorChannel = undefined;\n\t\t\tvectorState = \"enabling\";\n\t\t\tvectorInitPromise = undefined;\n\t\t}\n\t\tif (vectorState === \"failed\") return Promise.resolve(undefined);\n\t\tif (vectorInitPromise !== undefined) return vectorInitPromise;\n\t\tvectorInitPromise = (async (): Promise<ActiveVectorChannelV1 | undefined> => {\n\t\t\tconst preset = vectorPresetForMode(memoryMode);\n\t\t\tconst modelCacheDir = join(agentDir, \"memory\", VECTOR_MODEL_CACHE_DIRNAME);\n\t\t\tconst failEnabling = (\n\t\t\t\treason: string,\n\t\t\t\tactions: readonly string[] = enablingActionList(modelCacheDir, memoryMode),\n\t\t\t): undefined => {\n\t\t\t\tvectorState = \"failed\";\n\t\t\t\tenablingFailure = { reason, actions };\n\t\t\t\tvectorInitPromise = undefined;\n\t\t\t\tenablingSettled?.();\n\t\t\t\tif (!capabilityDisposed)\n\t\t\t\t\tlogger?.warn(`memory enabling failed: ${reason} — actions: ${enablingFailure.actions.join(\" | \")}`, {\n\t\t\t\t\t\tmode: memoryMode,\n\t\t\t\t\t});\n\t\t\t\treturn undefined;\n\t\t\t};\n\t\t\t// dispose 竞态守卫 (2026-10-06 复审遗留): teardown 与在途 enabling 竞态\n\t\t\t// 时, 装配完成点必须让位——不得把新连接/索引句柄赋回已清空的引用 (那会\n\t\t\t// 复活一条无人关闭的连接: 服务端 connections>0 抑制空闲自杀、挂住嵌入\n\t\t\t// 进程事件循环), 也不得让 enablingOutcome() 等待者悬挂。改为关闭刚取得\n\t\t\t// 的资源并落结构化 failed (MemoryEnablingFailureV1 形状)。\n\t\t\tconst failEnablingDisposed = (closeAcquired?: () => Promise<unknown>): undefined => {\n\t\t\t\tvectorState = \"failed\";\n\t\t\t\tenablingFailure = { reason: \"capability disposed during enabling\", actions: [] };\n\t\t\t\tvectorInitPromise = undefined;\n\t\t\t\tenablingSettled?.();\n\t\t\t\tif (closeAcquired !== undefined) void closeResource(\"inference client\", closeAcquired);\n\t\t\t\treturn undefined;\n\t\t\t};\n\t\t\tlogger?.info(`memory enabling started (mode=${memoryMode}, embedding=${preset.embeddingModelId})`);\n\t\t\t// 检查 1: native .node sidecar (纯本地, 零网络)。宿主注入路径优先\n\t\t\t// (安装店副本自解析不可达, 见 MemoryCapabilityContext.hostOnnxRuntimeEntryPath)。\n\t\t\tconst nativeProblem = nativeBinaryCheck(hostOnnxRuntimeEntryPath);\n\t\t\tif (nativeProblem !== undefined) return failEnabling(nativeProblem);\n\t\t\t// 检查 1b: 重依赖供给。宿主入口路径优先; 未提供时插件位置自解析,\n\t\t\t// 两者都不可达 = 原本要到加载步才以 \"Cannot find module\" 泛化包装\n\t\t\t// 失败的根因, 前置到模型下载之前以 onnx 缺供分支同构的精准文案报告。\n\t\t\t// 路径已提供但包损坏的真实失败仍走加载步, 由泛化包装保留原始错误。\n\t\t\tconst missingHeavyDependencies = missingHeavyDependencyModules(\n\t\t\t\t{ lancedb: hostLancedbEntryPath, transformers: hostTransformersEntryPath },\n\t\t\t\tresolveHeavyDependencyEntryPath,\n\t\t\t);\n\t\t\tif (missingHeavyDependencies.length > 0) {\n\t\t\t\treturn failEnabling(\n\t\t\t\t\t`${missingHeavyDependencies.join(\", \")} are not provided by the host installation and could not be resolved from the plugin location; to enable memory features, install them in the host project (npm i ${missingHeavyDependencies.join(\" \")}) and restart the session`,\n\t\t\t\t);\n\t\t\t}\n\t\t\t// 检查 2: 模型文件 (缺失 = 进入下载; 存在但截断 = 失败提示手动导入)。\n\t\t\tconst embeddingProblem = modelFilesCheck(\n\t\t\t\tmodelCacheDir,\n\t\t\t\tpreset.embeddingModelId,\n\t\t\t\tMODEL_MIN_WEIGHT_BYTES[memoryMode],\n\t\t\t);\n\t\t\tconst rerankerProblem = modelFilesCheck(modelCacheDir, VECTOR_RERANKER_MODEL_ID, RERANKER_MIN_WEIGHT_BYTES);\n\t\t\tconst modelsMissing =\n\t\t\t\tembeddingProblem === \"missing\" || rerankerProblem === \"missing\"\n\t\t\t\t\t? `${preset.embeddingModelId}${rerankerProblem === \"missing\" ? ` + ${VECTOR_RERANKER_MODEL_ID}` : \"\"}`\n\t\t\t\t\t: undefined;\n\t\t\tif (embeddingProblem !== undefined && embeddingProblem !== \"missing\") return failEnabling(embeddingProblem);\n\t\t\tif (rerankerProblem !== undefined && rerankerProblem !== \"missing\") return failEnabling(rerankerProblem);\n\t\t\t// 征询门 (2026-10-05 用户裁决): 模型缺失且未经用户同意时不下载, 停在\n\t\t\t// consent-required 态等 memory_enable 工具面继续。注入 loadImpl 的测试\n\t\t\t// 缝绕过本门 (deterministic mock 门禁路径, 无网络语义)。截断文件不走\n\t\t\t// 征询 (文件在 = 曾有过一次下载意图), 仍走失败行动清单。\n\t\t\tconst hasEnablingTestSeam =\n\t\t\t\tenablingOverride?.embeddingLoadImpl !== undefined || enablingOverride?.rerankerLoadImpl !== undefined;\n\t\t\t// 服务装配缝的模型声明 (Slice B2): modelsInPlace = 测试声明模型已在位\n\t\t\t// (免写假权重文件), 文件检查与征询门相应让位; 生产路径缺省 false,\n\t\t\t// 真实文件检查与征询门语义不变。\n\t\t\tconst serviceModelsDeclared = inferenceServiceModelsInPlace === true;\n\t\t\tif (modelsMissing !== undefined && !consentGranted && !hasEnablingTestSeam && !serviceModelsDeclared) {\n\t\t\t\tvectorState = \"consent-required\";\n\t\t\t\tconsentNeededInfo = {\n\t\t\t\t\tmodels: modelsMissing.split(\" + \"),\n\t\t\t\t\tapproximateBytes: MODEL_MIN_WEIGHT_BYTES[memoryMode] + RERANKER_MIN_WEIGHT_BYTES,\n\t\t\t\t};\n\t\t\t\tvectorInitPromise = undefined;\n\t\t\t\tenablingSettled?.();\n\t\t\t\tlogger?.info(\n\t\t\t\t\t`memory models missing (${modelsMissing}); download waits for user consent (memory_enable tool)`,\n\t\t\t\t);\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\t// 服务路径不下载 (模型归服务所有); 该日志只属于本地装配的下载分支。\n\t\t\tif (modelsMissing !== undefined && !serviceModelsDeclared) {\n\t\t\t\tlogger?.info(`memory enabling: model files missing (${modelsMissing}); downloading via configured mirrors`);\n\t\t\t}\n\t\t\t// 服务装配路径 (Slice B2, 裁决 C「根治」): 模型在位且无本地装配测试缝时,\n\t\t\t// 装配经共享推理服务 — 模型与索引全机一份 (主会话 + 全部 subagent 共享),\n\t\t\t// 本进程零重依赖加载。失败按 enabling failed 呈现 (裁决 A: 不回退本地\n\t\t\t// 装配 — 回退即重开多进程风险)。loadImpl 缝走下方本地装配路径 (既有语义)。\n\t\t\tconst useInferenceService = (modelsMissing === undefined || serviceModelsDeclared) && !hasEnablingTestSeam;\n\t\t\tif (useInferenceService) {\n\t\t\t\t// 端口解析也走结构化失败: 非法 env 值若在此裸抛, vectorInitPromise\n\t\t\t\t// 直接 reject 且 failEnabling 不运行 — 状态机被钉死在 enabling,\n\t\t\t\t// 写路径 (fire-and-forget) 还会丢成 unhandled rejection。\n\t\t\t\tlet servicePort: number;\n\t\t\t\ttry {\n\t\t\t\t\tservicePort = inferenceServicePort ?? resolveMemoryInferencePort(undefined, process.env);\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn failEnabling(\n\t\t\t\t\t\t`inference service assembly failed (invalid ${MEMORY_INFERENCE_PORT_ENV}: ${\n\t\t\t\t\t\t\terror instanceof Error ? error.message : String(error)\n\t\t\t\t\t\t})`,\n\t\t\t\t\t\tserviceFailureActionList(MEMORY_INFERENCE_DEFAULT_PORT),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tlet client: MemoryInferenceClientV1 | undefined;\n\t\t\t\ttry {\n\t\t\t\t\tclient = await ensureInferenceServiceChannel({\n\t\t\t\t\t\tagentDir,\n\t\t\t\t\t\tmemoryMode,\n\t\t\t\t\t\tport: servicePort,\n\t\t\t\t\t\t...(inferenceServiceSpawnImpl === undefined ? {} : { spawnImpl: inferenceServiceSpawnImpl }),\n\t\t\t\t\t});\n\t\t\t\t\tif (capabilityDisposed) return failEnablingDisposed(() => client!.close());\n\t\t\t\t\t// agentDir 身份校验 (2026-10-06 串线修复): 固定端口单例服务可能\n\t\t\t\t\t// 属于另一个 --agent-dir 的会话 (hello 此前只回报模型身份, 后连\n\t\t\t\t\t// 者握手/冒烟全过却把读写投影进对方的 LanceDB)。在冒烟与档位比\n\t\t\t\t\t// 对之前先核对身份 — 不一致或缺失都绝不触碰该服务。\n\t\t\t\t\tconst helloAgentDir: string | undefined = client.hello.agentDir;\n\t\t\t\t\tif (helloAgentDir === undefined) {\n\t\t\t\t\t\tvoid closeResource(\"inference client\", () => client!.close());\n\t\t\t\t\t\treturn failEnabling(\n\t\t\t\t\t\t\t`inference service on port ${servicePort} reports no agent-dir identity — the service was started by an older version; wait for its idle exit or stop it manually, then restart the session`,\n\t\t\t\t\t\t\tserviceFailureActionList(servicePort),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tif (normalizeMemoryAgentDirIdentity(helloAgentDir) !== normalizeMemoryAgentDirIdentity(agentDir)) {\n\t\t\t\t\t\tvoid closeResource(\"inference client\", () => client!.close());\n\t\t\t\t\t\treturn failEnabling(\n\t\t\t\t\t\t\t`inference service on port ${servicePort} belongs to agent-dir ${helloAgentDir}, this session runs in ${agentDir} — its memory projection lives in another agent-dir; wait for its idle exit or stop it manually, then restart the session`,\n\t\t\t\t\t\t\tserviceFailureActionList(servicePort),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tconst channel: ActiveVectorChannelV1 = {\n\t\t\t\t\t\tembed: client.embedProvider,\n\t\t\t\t\t\treranker: client.reranker,\n\t\t\t\t\t\tindex: client.vectorIndex,\n\t\t\t\t\t\tqueryPrefix: preset.queryPrefix,\n\t\t\t\t\t\tembeddingModelId: client.hello.embeddingModelId,\n\t\t\t\t\t};\n\t\t\t\t\t// 冒烟经 wire (服务端首次 embed 完成模型加载, 预算放宽)。\n\t\t\t\t\tawait channel.embed.embed([\"memory enabling smoke test\"]);\n\t\t\t\t\tif (capabilityDisposed) return failEnablingDisposed(() => client!.close());\n\t\t\t\t\tif (client.hello.embeddingModelId !== preset.embeddingModelId) {\n\t\t\t\t\t\tvoid closeResource(\"inference client\", () => client!.close());\n\t\t\t\t\t\treturn failEnabling(\n\t\t\t\t\t\t\t`inference service runs embedding model ${client.hello.embeddingModelId}, session preset is ${preset.embeddingModelId} — the service was spawned for another memory tier; wait for its idle exit or stop it, then restart the session`,\n\t\t\t\t\t\t\tserviceFailureActionList(servicePort),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tconst storedModelId = await channel.index.getStoredModelId();\n\t\t\t\t\tif (!capabilityDisposed && storedModelId !== undefined && storedModelId !== preset.embeddingModelId) {\n\t\t\t\t\t\tlogger?.warn(\n\t\t\t\t\t\t\t`memory projection was built for ${storedModelId}, preset is ${preset.embeddingModelId}; startup reconciliation will rebuild it`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\t// dispose 竞态: teardown 已清引用 (capabilityDisposed) 时, 装配成功\n\t\t\t\t\t// 分支不得把新 IPC 连接赋回去——关闭它并落结构化失败, 让在途的\n\t\t\t\t\t// enablingOutcome() 等待者 (如 memory-preheat) 落定为失败而非悬挂。\n\t\t\t\t\tif (capabilityDisposed) return failEnablingDisposed(() => client!.close());\n\t\t\t\t\tinferenceClient = client;\n\t\t\t\t\tvectorChannel = channel;\n\t\t\t\t\tvectorState = \"ready\";\n\t\t\t\t\tlogger?.info(\n\t\t\t\t\t\t`memory ready via shared inference service (mode=${memoryMode}, embedding=${preset.embeddingModelId})`,\n\t\t\t\t\t);\n\t\t\t\t\tenablingSettled?.();\n\t\t\t\t\treturn channel;\n\t\t\t\t} catch (error) {\n\t\t\t\t\t// 连接已建立后的失败 (冒烟/档位比对/getStoredModelId) 必须关掉\n\t\t\t\t\t// 客户端: 悬挂连接会让服务端 connections>0, 空闲自杀永不触发。\n\t\t\t\t\tif (client !== undefined) void closeResource(\"inference client\", () => client!.close());\n\t\t\t\t\treturn failEnabling(\n\t\t\t\t\t\t`inference service assembly failed (${error instanceof Error ? error.message : String(error)})`,\n\t\t\t\t\t\tserviceFailureActionList(servicePort),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\t// 检查 3: 磁盘余量 (light ≥ 500MB / full ≥ 2GB)。服务装配路径不下载, 已在上面 return。\n\t\t\tconst diskProblem = await diskHeadroomCheck(agentDir, DISK_HEADROOM_MIN_BYTES[memoryMode]);\n\t\t\tif (diskProblem !== undefined) return failEnabling(diskProblem);\n\t\t\t// dispose 竞态 (本地装配路径, 第一道): 已 teardown 就不再打开 LanceDB/\n\t\t\t// 拉起重依赖; 装配完成点还有第二道检查兜住模型下载窗口。\n\t\t\tif (capabilityDisposed) return failEnablingDisposed();\n\t\t\t// 加载: transformers/lancedb 的动态 import 都在这些模块内部, 这里只做\n\t\t\t// 模块级懒加载, 保持未触发会话零重依赖。进度周期性落一行 (下载可达\n\t\t\t// 数百 MB), 完成后清除。\n\t\t\tconst progressTimer = setInterval(() => {\n\t\t\t\tif (!capabilityDisposed) logger?.info(\"memory enabling still in progress (downloading/loading models)\");\n\t\t\t}, ENABLING_PROGRESS_LOG_INTERVAL_MS);\n\t\t\tif (typeof progressTimer === \"object\" && \"unref\" in progressTimer) progressTimer.unref();\n\t\t\tlet closeAcquired: (() => Promise<void>) | undefined;\n\t\t\tlet published = false;\n\t\t\ttry {\n\t\t\t\tconst [vectorIndexModule, embeddingModule, rerankerModule] = await Promise.all([\n\t\t\t\t\timport(\"./vector-index.ts\"),\n\t\t\t\t\timport(\"./embedding-provider.ts\"),\n\t\t\t\t\timport(\"./embedding-reranker.ts\"),\n\t\t\t\t]);\n\t\t\t\tif (capabilityDisposed) return failEnablingDisposed();\n\t\t\t\tconst index = await vectorIndexModule.createMemoryVectorIndex({\n\t\t\t\t\tdbPath: join(agentDir, \"memory\", VECTOR_DB_DIRNAME),\n\t\t\t\t\tdimensions: preset.dimensions,\n\t\t\t\t\t...(hostLancedbEntryPath === undefined ? {} : { moduleEntryPath: hostLancedbEntryPath }),\n\t\t\t\t});\n\t\t\t\tlet indexClosePromise: Promise<void> | undefined;\n\t\t\t\tcloseAcquired = () => {\n\t\t\t\t\tindexClosePromise ??= closeResource(\"vector index\", () => index.close());\n\t\t\t\t\treturn indexClosePromise;\n\t\t\t\t};\n\t\t\t\tcloseOwnedLocalResources = closeAcquired;\n\t\t\t\tif (capabilityDisposed) return failEnablingDisposed();\n\t\t\t\tconst remoteHosts = remoteHostsForEnabling();\n\t\t\t\tconst channel: ActiveVectorChannelV1 = {\n\t\t\t\t\tembed: embeddingModule.createTransformersEmbeddingProvider({\n\t\t\t\t\t\tmodelId: preset.embeddingModelId,\n\t\t\t\t\t\tdimensions: preset.dimensions,\n\t\t\t\t\t\tcacheDir: modelCacheDir,\n\t\t\t\t\t\tremoteHosts,\n\t\t\t\t\t\t...(hostTransformersEntryPath === undefined ? {} : { moduleEntryPath: hostTransformersEntryPath }),\n\t\t\t\t\t\t...(enablingOverride?.embeddingLoadImpl === undefined\n\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t: { loadImpl: enablingOverride.embeddingLoadImpl }),\n\t\t\t\t\t}),\n\t\t\t\t\treranker: rerankerModule.createTransformersReranker({\n\t\t\t\t\t\tmodelId: VECTOR_RERANKER_MODEL_ID,\n\t\t\t\t\t\tcacheDir: modelCacheDir,\n\t\t\t\t\t\tremoteHosts,\n\t\t\t\t\t\t...(hostTransformersEntryPath === undefined ? {} : { moduleEntryPath: hostTransformersEntryPath }),\n\t\t\t\t\t\t...(enablingOverride?.rerankerLoadImpl === undefined\n\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t: { loadImpl: enablingOverride.rerankerLoadImpl }),\n\t\t\t\t\t}),\n\t\t\t\t\tindex,\n\t\t\t\t\tqueryPrefix: preset.queryPrefix,\n\t\t\t\t\tembeddingModelId: preset.embeddingModelId,\n\t\t\t\t};\n\t\t\t\tlet channelClosePromise: Promise<void> | undefined;\n\t\t\t\tcloseAcquired = () => {\n\t\t\t\t\tchannelClosePromise ??= closeLocalChannel(channel);\n\t\t\t\t\treturn channelClosePromise;\n\t\t\t\t};\n\t\t\t\tcloseOwnedLocalResources = closeAcquired;\n\t\t\t\t// 冒烟: embed + rerank 各一条 (同时完成两个模型的下载与加载) +\n\t\t\t\t// 投影档位比对。rerank 冒烟 2026-10-06 live E2E 补齐: reranker\n\t\t\t\t// 懒加载, 只 embed 的冒烟会让 \"ready\" 携带未下载的精排权重 —\n\t\t\t\t// 共享推理服务 (两项文件均前置检查、永不自主下载) 对该会话拒启,\n\t\t\t\t// \"fully usable\" 的自述与服务前置条件必须一致。\n\t\t\t\tawait channel.embed.embed([\"memory enabling smoke test\"]);\n\t\t\t\tif (capabilityDisposed) return failEnablingDisposed();\n\t\t\t\tif (channel.embed.modelId !== preset.embeddingModelId) {\n\t\t\t\t\treturn failEnabling(\n\t\t\t\t\t\t`smoke check failed: embedding modelId ${channel.embed.modelId} does not match the ${memoryMode} preset ${preset.embeddingModelId}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (channel.reranker !== undefined) {\n\t\t\t\t\tawait channel.reranker.rerank(\"memory enabling smoke test\", [\"memory enabling smoke test\"]);\n\t\t\t\t\tif (capabilityDisposed) return failEnablingDisposed();\n\t\t\t\t}\n\t\t\t\tconst storedModelId = await channel.index.getStoredModelId();\n\t\t\t\tif (!capabilityDisposed && storedModelId !== undefined && storedModelId !== preset.embeddingModelId) {\n\t\t\t\t\tlogger?.warn(\n\t\t\t\t\t\t`memory projection was built for ${storedModelId}, preset is ${preset.embeddingModelId}; startup reconciliation will rebuild it`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\t// dispose 竞态 (本地装配路径, 第二道, 兜住模型下载窗口): 不把索引句柄\n\t\t\t\t// 赋回引用——关闭刚打开的 LanceDB 并落结构化失败。\n\t\t\t\tif (capabilityDisposed) return failEnablingDisposed();\n\t\t\t\tvectorChannel = channel;\n\t\t\t\tpublished = true;\n\t\t\t\tvectorState = \"ready\";\n\t\t\t\tlogger?.info(`memory ready (mode=${memoryMode}, embedding=${preset.embeddingModelId})`);\n\t\t\t\tenablingSettled?.();\n\t\t\t\treturn channel;\n\t\t\t} catch (error) {\n\t\t\t\treturn failEnabling(\n\t\t\t\t\t`model load or smoke check failed (${error instanceof Error ? error.message : String(error)})`,\n\t\t\t\t);\n\t\t\t} finally {\n\t\t\t\tclearInterval(progressTimer);\n\t\t\t\tif (!published && closeAcquired !== undefined) {\n\t\t\t\t\tawait closeAcquired();\n\t\t\t\t\tif (closeOwnedLocalResources === closeAcquired) closeOwnedLocalResources = undefined;\n\t\t\t\t}\n\t\t\t}\n\t\t})();\n\t\treturn vectorInitPromise;\n\t};\n\n\t// ---- 征询门执行面 (2026-10-05 用户裁决「首次使用征询、拒绝/失败可跳过」) ----\n\t// memory_enable 是 consent-required / failed 态的唯一下载入口: consentGranted\n\t// 只在这里置位, recall/auto-recall 永不触发下载。decline 同时持久化\n\t// (writeMemoryConsentDeclined), 只抑制默认档——用户显式设置 memory.mode 后\n\t// 下次启用会在首次使用时再次走到征询门。\n\t// ---- 记忆模型下载控制面 (2026-10-05 流程裁决「后台预热、不阻塞提问」) ----\n\t// 生产入口 (交互模式会话绑定后) 经公共工具面调用 memory_enable download\n\t// 触发后台预热; 命令面 /memory off|retry 是用户的直接出口。两处共用同一对\n\t// 闭包; decline 持久化只抑制默认档。\n\tconst declineMemory = (): { status: \"completed\"; message: string } => {\n\t\t// 总是落盘 (幂等写): 升降档会清理文件里的拒绝标记, 之后再次 off 必须\n\t\t// 重新写入——不能用内存 flag 跳过持久化。\n\t\tconst firstDecline = !consentDeclined;\n\t\tconsentDeclined = true;\n\t\twriteMemoryConsentDeclined(agentDir);\n\t\tif (firstDecline) {\n\t\t\tlogger?.info(\"memory disabled by user decision (persisted to the memory agent-dir config)\");\n\t\t}\n\t\treturn {\n\t\t\tstatus: \"completed\",\n\t\t\tmessage:\n\t\t\t\t\"memory disabled for this machine (persisted). Set memory.mode (light|full) in settings.json and restart the session to re-enable\",\n\t\t};\n\t};\n\tconst downloadMemory = async (): Promise<\n\t\t| { status: \"completed\"; message: string }\n\t\t| { status: \"failed\"; message: string; actions?: readonly string[]; next?: string }\n\t> => {\n\t\tif (consentDeclined) {\n\t\t\treturn {\n\t\t\t\tstatus: \"failed\",\n\t\t\t\tmessage:\n\t\t\t\t\t\"memory was declined on this machine — set memory.mode (light|full) in settings.json and restart the session to re-enable\",\n\t\t\t};\n\t\t}\n\t\tconsentGranted = true;\n\t\tif (vectorState === \"failed\" || vectorState === \"consent-required\") {\n\t\t\tvectorState = \"enabling\";\n\t\t\tenablingFailure = undefined;\n\t\t\tvectorInitPromise = undefined;\n\t\t}\n\t\tconst channel = await vectorEnsure();\n\t\tif (channel === undefined) {\n\t\t\tconst failure = enablingFailure ?? {\n\t\t\t\treason: `memory enabling did not complete (state=${vectorState})`,\n\t\t\t\tactions: [] as const,\n\t\t\t};\n\t\t\treturn {\n\t\t\t\tstatus: \"failed\",\n\t\t\t\tmessage: `memory enabling failed: ${failure.reason}`,\n\t\t\t\tactions: failure.actions,\n\t\t\t\tnext: 'Tell the user the download failed and ask whether to skip memory (call memory_enable with action \"decline\" or /memory off — both persist off) or fix the environment and retry (/memory retry)',\n\t\t\t};\n\t\t}\n\t\t// 就绪: 补跑启动对账, 把预热期间写入的 ledger 记忆补进向量投影。\n\t\tresetReconcile();\n\t\treconcileOnce();\n\t\treturn { status: \"completed\", message: \"memory models ready — the memory family is fully usable\" };\n\t};\n\n\t// 会话切换重绑/插件卸载的共享资源释放 (TUI 每次会话切换都重走装配, 不释放\n\t// 即每次泄漏一条 IPC 连接: 服务端 connections>0 抑制空闲自杀, 嵌入方进程因\n\t// socket 未关无法自然退出)。清引用先行: close 的错误经独立 stderr 诊断, 且\n\t// 二次调用因引用已空自然 no-op。服务路径与本地路径互斥 (服务路径的 index\n\t// 归服务进程持有, 客户端只断连; 本地路径才关 LanceDB 句柄)。\n\t// capabilityDisposed 是 teardown 与在途 enabling 的竞态闩锁: teardown 之后\n\t// 才完成的装配在成功分支让位 (见 vectorEnsure 的 failEnablingDisposed),\n\t// 不复活无人关闭的连接/句柄。\n\tlet capabilityDisposed = false;\n\tconst capabilityTeardown = (): void => {\n\t\tcapabilityDisposed = true;\n\t\tif (closeOwnedLocalResources !== undefined) {\n\t\t\tconst close = closeOwnedLocalResources;\n\t\t\tcloseOwnedLocalResources = undefined;\n\t\t\tvectorChannel = undefined;\n\t\t\tvoid close();\n\t\t\treturn;\n\t\t}\n\t\tif (inferenceClient !== undefined) {\n\t\t\tconst client = inferenceClient;\n\t\t\tinferenceClient = undefined;\n\t\t\tvectorChannel = undefined;\n\t\t\tvoid closeResource(\"inference client\", () => client.close());\n\t\t\treturn;\n\t\t}\n\t\tif (vectorChannel !== undefined) {\n\t\t\tconst channel = vectorChannel;\n\t\t\tvectorChannel = undefined;\n\t\t\tvoid closeLocalChannel(channel);\n\t\t}\n\t};\n\n\treturn {\n\t\tstate: (): \"off\" | MemoryCapabilityStateV1 => (consentDeclined ? \"off\" : vectorState),\n\t\trawState: (): MemoryCapabilityStateV1 => vectorState,\n\t\tenabled: vectorEnabled,\n\t\treadyChannel: (): ActiveVectorChannelV1 | undefined => vectorChannel,\n\t\tisDisposed: (): boolean => capabilityDisposed,\n\t\tdeclined: (): boolean => consentDeclined,\n\t\tclearDeclined: (): void => {\n\t\t\tconsentDeclined = false;\n\t\t},\n\t\tconsentAsked: (): boolean => consentAsked,\n\t\tmarkConsentAsked: (): void => {\n\t\t\tconsentAsked = true;\n\t\t},\n\t\tprimeConsentGate,\n\t\tconsentAsk: (): MemoryConsentAskV1 | undefined =>\n\t\t\tvectorState === \"consent-required\" && consentNeededInfo !== undefined\n\t\t\t\t? { message: consentAskMessage(), actions: consentAskActions(), block: consentAskBlock() }\n\t\t\t\t: undefined,\n\t\twarming: (): boolean => vectorState === \"enabling\" && vectorInitPromise !== undefined && !consentDeclined,\n\t\tfailure: (): MemoryEnablingFailureV1 | undefined => enablingFailure,\n\t\tmarkDegraded: (): void => {\n\t\t\tvectorState = \"degraded\";\n\t\t},\n\t\trecoverDegraded: (): void => {\n\t\t\tif (vectorState === \"degraded\") vectorState = \"ready\";\n\t\t},\n\t\tensure: vectorEnsure,\n\t\tenablingOutcome: async (): Promise<\"ready\" | MemoryEnablingFailureV1> => {\n\t\t\tif (vectorState === \"enabling\") void vectorEnsure();\n\t\t\tawait enablingSettledPromise;\n\t\t\treturn enablingFailure ?? \"ready\";\n\t\t},\n\t\tdecline: declineMemory,\n\t\tdownload: downloadMemory,\n\t\tdispose: capabilityTeardown,\n\t};\n}\n"]}
|