pi-fabric 0.92.0 → 0.92.1

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.
@@ -7,7 +7,7 @@ import {
7
7
  emptyCompiledSurface,
8
8
  withExclusiveFileLock,
9
9
  withExclusiveFileLockAsync
10
- } from "./chunk-5MDFFHOO.js";
10
+ } from "./chunk-BSGA3KSB.js";
11
11
  import {
12
12
  sessionDirForCwd,
13
13
  sessionsDirRoot
@@ -1715,4 +1715,4 @@ export {
1715
1715
  formatEntropyCompileNotice,
1716
1716
  runEntropyTrial
1717
1717
  };
1718
- //# sourceMappingURL=chunk-LLJXPPTA.js.map
1718
+ //# sourceMappingURL=chunk-6ELA5OWI.js.map
@@ -39,6 +39,7 @@ var emptyCompiledSurface = () => ({
39
39
  evidenceDigest: stableJsonHash([])
40
40
  });
41
41
  var compiledSurfaceEffectChanged = (before, after) => stableJsonHash(before?.version === COMPILED_SURFACE_VERSION ? before.normalizations ?? [] : []) !== stableJsonHash(after.version === COMPILED_SURFACE_VERSION ? after.normalizations ?? [] : []);
42
+ var comparableCompiledSurfaceScore = (file, metricVersion) => file?.version === COMPILED_SURFACE_VERSION && file.metricVersion === metricVersion ? file.gate.afterScore : void 0;
42
43
  var isPlainRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
43
44
  var schemaDigest = (schema) => stableJsonHash(schema);
44
45
  var effectiveSchemaFor = (_ref, liveSchema, _file) => liveSchema;
@@ -622,6 +623,7 @@ export {
622
623
  MAX_COMPILED_SURFACE_PROPOSALS,
623
624
  emptyCompiledSurface,
624
625
  compiledSurfaceEffectChanged,
626
+ comparableCompiledSurfaceScore,
625
627
  schemaDigest,
626
628
  effectiveSchemaFor,
627
629
  applyCompiledSurface,
@@ -639,4 +641,4 @@ export {
639
641
  saveCompiledSurface,
640
642
  saveCompiledSurfaceAsync
641
643
  };
642
- //# sourceMappingURL=chunk-5MDFFHOO.js.map
644
+ //# sourceMappingURL=chunk-BSGA3KSB.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/entropy/types.ts", "../../src/entropy/compiled-surface.ts", "../../src/entropy/compiled-store.ts", "../../src/core/file-lock.ts"],
4
+ "sourcesContent": ["// Deterministic tool-entropy measurement for the Fabric tool surface.\n//\n// The operational score is an invocation rejection fraction, not bits.\n// Shape, failure-stage, flow, churn, navigation, lexicon, and schema freedom\n// remain separate diagnostics from typed traces, repairs, and live schemas.\n// No model judges anything; identical inputs and metric version give the\n// same report. Derived metrics are rounded to six decimal places.\n\nexport const ENTROPY_METRIC_VERSION = 3 as const;\n\n// Legacy diagnostic weights retained for export compatibility. In v3 only\n// staticFreedom scales staticScore; none contribute to the operational score.\n// Changes to metric formulas require an ENTROPY_METRIC_VERSION bump.\nexport const ENTROPY_WEIGHTS = {\n shape: 1,\n failureStage: 1,\n churn: 4,\n navigation: 4,\n flow: 1,\n lexicon: 2,\n staticFreedom: 0.25,\n} as const;\n\n// Failure stages that mean \"the surface rejected the call before it could\n// take effect\" \u2014 the offline residue class behind repair fingerprints.\nexport const ENTROPY_INVOCATION_STAGES: readonly string[] = [\"resolve\", \"prepare\", \"validate\"];\n\nexport type EntropyOutcome = \"succeeded\" | \"failed\" | \"aborted\" | \"timed_out\";\n\nexport interface EntropySurfaceAction {\n ref: string;\n inputSchema: unknown;\n}\n\nexport interface EntropySurfaceSnapshot {\n version: 1;\n actions: EntropySurfaceAction[];\n}\n\nexport interface EntropyOperationInput {\n ref: string;\n args: Record<string, unknown>;\n outcome: EntropyOutcome;\n failureStage?: string;\n normalization?: import(\"./normal-form.js\").NormalFormWitness;\n}\n\nexport interface EntropyTraceInput {\n operations: EntropyOperationInput[];\n taskKey?: string;\n /** Producing model, stamped from the session scan as `provider/modelId`. */\n model?: string;\n}\n\n// Normalized compatibility alias: `ref` is the canonical target the row\n// repairs toward.\nexport interface EntropyRepairRowInput {\n kind: \"keyAlias\" | \"actionAlias\";\n ref: string;\n from: string;\n to: string;\n}\n\n// One verbatim argument value observed in persisted audits: the value-level\n// corpus for enum-tighten. Trace V1 projects values away per ref; audits\n// carry every argument the call actually used. Pooled observations carry\n// `count` multiplicity instead of one entry per call.\nexport interface EntropyValueObservation {\n ref: string;\n key: string;\n value: string | number | boolean;\n /** Observation multiplicity; window scans emit one entry per call, pools emit one per distinct value. */\n count?: number;\n}\n\n// One verbatim call per persisted audit: the authoritative record of the\n// arguments a call actually used. Trace V1 projects values away per ref, so\n// replay validation consults these, never the projected trace args.\nexport interface EntropyAuditCall {\n ref: string;\n args: Record<string, unknown>;\n}\n\nexport interface EntropyShapeSignature {\n signature: string;\n count: number;\n}\n\nexport interface EntropyRefReport {\n ref: string;\n calls: number;\n succeeded: number;\n failed: number;\n shapeSignatures: EntropyShapeSignature[];\n /** Shannon entropy of argument shapes, in bits. */\n shapeEntropyBits: number;\n /** Shannon entropy of failed-call stages, in bits. */\n failureStageEntropyBits: number;\n /** Mean normalized shape distance between a failure and the next same-ref call. */\n churnRate: number;\n /** Count of repair rows targeting this ref. */\n lexiconRows: number;\n /** Heuristic schema-freedom units; zero for an unknown schema. */\n staticFreedom: number;\n /** Invocation rejections / calls, a fraction in [0, 1]. */\n score: number;\n}\n\nexport interface EntropyTotals {\n traces: number;\n operations: number;\n actionOperations: number;\n discoveryOperations: number;\n workflowOperations: number;\n succeeded: number;\n failed: number;\n aborted: number;\n timedOut: number;\n invocationRejections: number;\n invocationRejectionsPer1k: number;\n}\n\n// Per-model behavioral attribution over stamped traces only.\nexport interface EntropyModelReport {\n model: string;\n operations: number;\n actionOperations: number;\n succeeded: number;\n invocationRejections: number;\n invocationRejectionsPer1k: number;\n /** Invocation rejections / action operations for this model, in [0, 1]; zero if none. */\n behavioralScore: number;\n}\n\nexport interface EntropyReport {\n metricVersion: typeof ENTROPY_METRIC_VERSION;\n catalogDigest: string;\n totals: EntropyTotals;\n /** Call-weighted mean per-ref shape entropy, in bits. */\n shapeEntropyBits: number;\n /** Failed-call-weighted mean per-ref failure-stage entropy, in bits. */\n failureStageEntropyBits: number;\n /** Mean normalized failure-to-next-same-ref shape distance within traces. */\n churnRate: number;\n /** Discovery operations / action operations; zero without action operations. */\n navigationRatio: number;\n /** Trace-weighted mean per-task action-sequence entropy, in bits. */\n flowEntropyBits: number;\n /** Total count of supplied repair rows. */\n lexiconRows: number;\n /** Sum of heuristic schema-freedom units over distinct called refs. */\n staticFreedom: number;\n /** 0.25 \u00D7 call-weighted mean schema freedom; unknown schemas contribute zero.\n * Diagnostic only, zero without action calls; never added to score. */\n staticScore: number;\n /** Identical to score: invocation rejection fraction, not entropy bits. */\n behavioralScore: number;\n /** Failed resolve/prepare/validate calls / all action operations, in [0, 1].\n * Zero without action operations. Discovery/workflow operations are excluded. */\n score: number;\n refs: EntropyRefReport[];\n /** Behavioral attribution per producing model; empty when no trace carries one. */\n byModel: EntropyModelReport[];\n}\n\nexport type EntropyProposal =\n | {\n kind: \"normal-form\";\n ref: string;\n baseSchemaDigest: string;\n rules: import(\"./normal-form.js\").NormalFormRule[];\n }\n | {\n kind: \"enum-tighten\";\n ref: string;\n key: string;\n values: (string | number | boolean)[];\n calls: number;\n distinct: number;\n topShare: number;\n }\n | {\n kind: \"declare-enum\";\n ref: string;\n key: string;\n values: (string | number | boolean)[];\n calls: number;\n distinct: number;\n topShare: number;\n }\n | {\n kind: \"overload-split\";\n ref: string;\n shapeEntropyBits: number;\n clusters: { keys: string[]; calls: number }[];\n }\n | {\n kind: \"sequence-fuse\";\n sequence: string[];\n occurrences: number;\n }\n | {\n kind: \"noise-quarantine\";\n ref: string;\n calls: number;\n succeeded: number;\n failed: number;\n failureStageEntropyBits: number;\n };\n\nexport interface EntropyGateResult {\n passed: boolean;\n beforeScore: number;\n afterScore: number;\n delta: number;\n reasons: string[];\n}\n\n// Trend of a score sequence, oldest to newest: the ratchet's line. A\n// negative slopePerStep means the surface is compiling down.\nexport interface EntropyTrend {\n count: number;\n first?: number;\n last?: number;\n slopePerStep: number;\n}\n", "// Version 2 compiles compatibility normal forms, never schema restrictions.\n// Version 1 restriction artifacts remain readable for migration but are inert.\nimport { Value } from \"typebox/value\";\nimport { stableJsonHash } from \"../core/stable-hash.js\";\nimport { ENTROPY_METRIC_VERSION } from \"./types.js\";\nimport { MAX_NORMAL_FORM_PLANS, provesNormalFormPlan, type NormalFormPlan } from \"./normal-form.js\";\nimport type { EntropyAuditCall, EntropyProposal, EntropySurfaceSnapshot, EntropyTraceInput } from \"./types.js\";\n\nexport const COMPILED_SURFACE_VERSION = 2 as const;\nexport const MAX_COMPILED_SURFACE_PROPOSALS = 256;\nexport interface CompiledSurfaceOverlayEntry {\n ref: string;\n inputSchema: Record<string, unknown>;\n baseSchemaDigest: string;\n}\nexport interface CompiledSurfaceQuarantineEntry { ref: string; baseSchemaDigest: string }\nexport interface CompiledSurfaceAppliedProposal { kind: EntropyProposal[\"kind\"]; ref: string; detail: string }\nexport interface CompiledSurfaceGateRecord { passed: boolean; beforeScore: number; afterScore: number; reasons: string[] }\nexport interface CompiledSurfaceFile {\n version: 1 | typeof COMPILED_SURFACE_VERSION;\n metricVersion: number;\n /** Legacy restrictions are retained only when reading version 1. Never enforced. */\n actions: CompiledSurfaceOverlayEntry[];\n quarantined: CompiledSurfaceQuarantineEntry[];\n normalizations?: NormalFormPlan[];\n applied: CompiledSurfaceAppliedProposal[];\n gate: CompiledSurfaceGateRecord;\n evidenceDigest: string;\n}\n\nexport const emptyCompiledSurface = (): CompiledSurfaceFile => ({\n version: COMPILED_SURFACE_VERSION, metricVersion: ENTROPY_METRIC_VERSION,\n actions: [], quarantined: [], normalizations: [], applied: [],\n gate: { passed: true, beforeScore: 0, afterScore: 0, reasons: [] },\n evidenceDigest: stableJsonHash([]),\n});\nexport const compiledSurfaceEffectChanged = (before: CompiledSurfaceFile | undefined, after: CompiledSurfaceFile): boolean =>\n stableJsonHash(before?.version === COMPILED_SURFACE_VERSION ? before.normalizations ?? [] : []) !==\n stableJsonHash(after.version === COMPILED_SURFACE_VERSION ? after.normalizations ?? [] : []);\n// Scores are comparable across compiles only under the same metric version;\n// legacy (v1) or stale-metric artifacts yield no baseline for a lowering.\nexport const comparableCompiledSurfaceScore = (\n file: CompiledSurfaceFile | undefined,\n metricVersion: number,\n): number | undefined =>\n file?.version === COMPILED_SURFACE_VERSION && file.metricVersion === metricVersion\n ? file.gate.afterScore\n : undefined;\nconst isPlainRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\nexport const schemaDigest = (schema: unknown): string => stableJsonHash(schema);\n\n// These compatibility APIs deliberately preserve the entire declaration.\n// Neither a legacy artifact nor an imported schema may remove capabilities.\nexport const effectiveSchemaFor = (_ref: string, liveSchema: unknown, _file?: CompiledSurfaceFile): unknown => liveSchema;\nexport const applyCompiledSurface = (live: EntropySurfaceSnapshot, _file?: CompiledSurfaceFile): EntropySurfaceSnapshot => live;\nexport const quarantinedRefNames = (_file?: CompiledSurfaceFile): ReadonlySet<string> => new Set();\nexport const isQuarantinedRef = (_ref: string, _liveSchema: unknown, _file?: CompiledSurfaceFile): boolean => false;\n\nexport interface MergedCompiledSurface {\n file: CompiledSurfaceFile;\n droppedOverlays: number;\n droppedQuarantines: number;\n droppedNormalizations: number;\n}\n\n// Import proves the complete rule plan by re-derivation, not merely a base\n// digest. Forged rule kinds/targets, drift, and every legacy restriction drop.\nexport const mergeCompiledSurfaces = (\n local: CompiledSurfaceFile | undefined,\n incoming: CompiledSurfaceFile,\n live: EntropySurfaceSnapshot,\n): MergedCompiledSurface => {\n const schemas = new Map(live.actions.map((action) => [action.ref, action.inputSchema]));\n const plans = new Map<string, NormalFormPlan>();\n let droppedNormalizations = 0;\n for (const file of [local, incoming]) {\n if (!file || file.version !== COMPILED_SURFACE_VERSION) continue;\n for (const plan of file.normalizations ?? []) {\n if (!provesNormalFormPlan(plan, schemas.get(plan.ref))) { droppedNormalizations++; continue; }\n if (plans.size >= MAX_NORMAL_FORM_PLANS || plans.has(plan.ref)) continue;\n plans.set(plan.ref, plan);\n }\n }\n const normalizations = [...plans.values()].sort((a, b) => a.ref < b.ref ? -1 : a.ref > b.ref ? 1 : 0);\n return {\n file: {\n ...emptyCompiledSurface(), normalizations,\n applied: normalizations.slice(0, MAX_COMPILED_SURFACE_PROPOSALS).map((plan) => ({ kind: \"normal-form\", ref: plan.ref, detail: `${plan.rules.length} proven rules` })),\n evidenceDigest: stableJsonHash(normalizations),\n },\n droppedOverlays: (local?.actions.length ?? 0) + incoming.actions.length,\n droppedQuarantines: (local?.quarantined.length ?? 0) + incoming.quarantined.length,\n droppedNormalizations,\n };\n};\n\nexport interface ReplayViolation {\n ref: string;\n reason: string;\n}\n\n// Replay preservation: every successful call to a ref the compile touched\n// must still parse against the candidate surface \u2014 resolution plus the same\n// TypeBox check the registry's validate stage uses. Untouched refs keep\n// their schema by identity, so replay stays scoped to the touched set.\n// When a touched ref has verbatim audit calls, they are the replay corpus:\n// trace V1 projects values away per ref, so validating the projected trace\n// args would phantom-reject calls that actually parsed. Audits the declared\n// surface already rejected are not protected \u2014 those calls never executed,\n// so no compile can invalidate them.\nexport const replaySuccessfulCalls = (\n surface: EntropySurfaceSnapshot,\n before: EntropySurfaceSnapshot,\n traces: readonly EntropyTraceInput[],\n touchedRefs: ReadonlySet<string>,\n auditCalls?: readonly EntropyAuditCall[],\n): ReplayViolation[] => {\n const schemaByRef = new Map(surface.actions.map((action) => [action.ref, action.inputSchema]));\n const beforeByRef = new Map(before.actions.map((action) => [action.ref, action.inputSchema]));\n const accepts = (schema: unknown, args: Record<string, unknown>): boolean => {\n try {\n return isPlainRecord(schema) && Value.Check(schema, args);\n } catch {\n return false;\n }\n };\n const violations: ReplayViolation[] = [];\n const auditedRefs = new Set<string>();\n if (auditCalls) {\n const auditArgsByRef = new Map<string, Record<string, unknown>[]>();\n for (const call of auditCalls) {\n if (!touchedRefs.has(call.ref)) continue;\n const bucket = auditArgsByRef.get(call.ref) ?? [];\n bucket.push(call.args);\n auditArgsByRef.set(call.ref, bucket);\n }\n for (const [ref, argsList] of auditArgsByRef) {\n auditedRefs.add(ref);\n const schema = schemaByRef.get(ref);\n if (schema === undefined) {\n violations.push({ ref, reason: \"absent from the candidate surface\" });\n continue;\n }\n const declared = beforeByRef.get(ref);\n for (const args of argsList) {\n if (declared !== undefined && !accepts(declared, args)) continue;\n if (!accepts(schema, args)) {\n violations.push({\n ref,\n reason: \"recorded arguments no longer validate against the compiled schema\",\n });\n }\n }\n }\n }\n for (const sourceTrace of traces) {\n for (const operation of sourceTrace.operations) {\n if (operation.outcome !== \"succeeded\") continue;\n if (operation.ref.startsWith(\"fabric.\")) continue;\n if (!touchedRefs.has(operation.ref)) continue;\n if (auditedRefs.has(operation.ref)) continue;\n const schema = schemaByRef.get(operation.ref);\n if (schema === undefined) {\n violations.push({ ref: operation.ref, reason: \"absent from the candidate surface\" });\n continue;\n }\n if (!accepts(schema, operation.args)) {\n violations.push({\n ref: operation.ref,\n reason: \"recorded arguments no longer validate against the compiled schema\",\n });\n }\n }\n }\n return violations;\n};\n\nconst COOPERATIVE_REPLAY_CHUNK = 64;\n\nconst replayYield = (): Promise<void> =>\n new Promise((resolve) => setImmediate(resolve));\n\n// Hook-safe replay gate. The ordering and validation rules match the pure\n// certification path exactly, with fixed operation chunks between TUI turns.\nexport const replaySuccessfulCallsAsync = async (\n surface: EntropySurfaceSnapshot,\n before: EntropySurfaceSnapshot,\n traces: readonly EntropyTraceInput[],\n touchedRefs: ReadonlySet<string>,\n auditCalls?: readonly EntropyAuditCall[],\n): Promise<ReplayViolation[]> => {\n const schemaByRef = new Map(surface.actions.map((action) => [action.ref, action.inputSchema]));\n const beforeByRef = new Map(before.actions.map((action) => [action.ref, action.inputSchema]));\n const accepts = (schema: unknown, args: Record<string, unknown>): boolean => {\n try {\n return isPlainRecord(schema) && Value.Check(schema, args);\n } catch {\n return false;\n }\n };\n const violations: ReplayViolation[] = [];\n const auditedRefs = new Set<string>();\n let processed = 0;\n await replayYield();\n if (auditCalls) {\n const auditArgsByRef = new Map<string, Record<string, unknown>[]>();\n for (const call of auditCalls) {\n if (touchedRefs.has(call.ref)) {\n const bucket = auditArgsByRef.get(call.ref) ?? [];\n bucket.push(call.args);\n auditArgsByRef.set(call.ref, bucket);\n }\n processed += 1;\n if (processed % COOPERATIVE_REPLAY_CHUNK === 0) await replayYield();\n }\n for (const [ref, argsList] of auditArgsByRef) {\n auditedRefs.add(ref);\n const schema = schemaByRef.get(ref);\n if (schema === undefined) {\n violations.push({ ref, reason: \"absent from the candidate surface\" });\n continue;\n }\n const declared = beforeByRef.get(ref);\n for (const args of argsList) {\n if (declared === undefined || accepts(declared, args)) {\n if (!accepts(schema, args)) {\n violations.push({\n ref,\n reason: \"recorded arguments no longer validate against the compiled schema\",\n });\n }\n }\n processed += 1;\n if (processed % COOPERATIVE_REPLAY_CHUNK === 0) await replayYield();\n }\n }\n }\n for (const sourceTrace of traces) {\n for (const operation of sourceTrace.operations) {\n if (\n operation.outcome === \"succeeded\" &&\n !operation.ref.startsWith(\"fabric.\") &&\n touchedRefs.has(operation.ref) &&\n !auditedRefs.has(operation.ref)\n ) {\n const schema = schemaByRef.get(operation.ref);\n if (schema === undefined) {\n violations.push({ ref: operation.ref, reason: \"absent from the candidate surface\" });\n } else if (!accepts(schema, operation.args)) {\n violations.push({\n ref: operation.ref,\n reason: \"recorded arguments no longer validate against the compiled schema\",\n });\n }\n }\n processed += 1;\n if (processed % COOPERATIVE_REPLAY_CHUNK === 0) await replayYield();\n }\n }\n return violations;\n};\n", "// Persistence for the compiled entropy surface: <agent dir>/fabric/entropy/\n// compiled.json, locked across Pi processes sharing the agent directory.\n// A damaged artifact surfaces as an error and blocks compiles from\n// overwriting it \u2014 the same discipline as the repair table. The artifact is\n// clock-free, so saving byte-identical content is a no-op.\n\nimport fs from \"node:fs\";\nimport { isNormalFormPlan, MAX_NORMAL_FORM_PLANS } from \"./normal-form.js\";\nimport path from \"node:path\";\nimport { writeJsonAtomic, writeJsonAtomicAsync } from \"../core/atomic-write.js\";\nimport { withExclusiveFileLock, withExclusiveFileLockAsync } from \"../core/file-lock.js\";\nimport {\n COMPILED_SURFACE_VERSION,\n MAX_COMPILED_SURFACE_PROPOSALS,\n type CompiledSurfaceAppliedProposal,\n type CompiledSurfaceFile,\n type CompiledSurfaceGateRecord,\n type CompiledSurfaceOverlayEntry,\n type CompiledSurfaceQuarantineEntry,\n} from \"./compiled-surface.js\";\n\nconst COMPILED_LOCK_ATTEMPTS = 50;\nconst COMPILED_LOCK_DELAY_MS = 5;\nconst COMPILED_STALE_LOCK_MS = 30_000;\n\nexport const compiledSurfaceDirectory = (agentDir: string): string =>\n path.join(agentDir, \"fabric\", \"entropy\");\n\nconst compiledPath = (directory: string): string => path.join(directory, \"compiled.json\");\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst errorCode = (error: unknown): string | undefined =>\n isRecord(error) && typeof error.code === \"string\" ? error.code : undefined;\n\nconst errorText = (error: unknown): string =>\n (error instanceof Error ? error.message : String(error)).slice(0, 200);\n\nconst parseOverlayEntry = (value: unknown): CompiledSurfaceOverlayEntry | undefined => {\n if (!isRecord(value) || typeof value.ref !== \"string\" || !value.ref.trim()) return undefined;\n if (!isRecord(value.inputSchema)) return undefined;\n if (typeof value.baseSchemaDigest !== \"string\" || !value.baseSchemaDigest.trim()) {\n return undefined;\n }\n return {\n ref: value.ref.trim(),\n inputSchema: value.inputSchema,\n baseSchemaDigest: value.baseSchemaDigest.trim(),\n };\n};\n\nconst parseQuarantineEntry = (value: unknown): CompiledSurfaceQuarantineEntry | undefined => {\n if (!isRecord(value) || typeof value.ref !== \"string\" || !value.ref.trim()) return undefined;\n if (typeof value.baseSchemaDigest !== \"string\" || !value.baseSchemaDigest.trim()) {\n return undefined;\n }\n return { ref: value.ref.trim(), baseSchemaDigest: value.baseSchemaDigest.trim() };\n};\n\nconst parseAppliedProposal = (value: unknown): CompiledSurfaceAppliedProposal | undefined => {\n if (!isRecord(value)) return undefined;\n if (typeof value.kind !== \"string\" || !value.kind.trim()) return undefined;\n if (typeof value.ref !== \"string\" || !value.ref.trim()) return undefined;\n if (typeof value.detail !== \"string\" || !value.detail.trim()) return undefined;\n return {\n kind: value.kind.trim() as CompiledSurfaceAppliedProposal[\"kind\"],\n ref: value.ref.trim(),\n detail: value.detail.trim(),\n };\n};\n\nconst parseGateRecord = (value: unknown): CompiledSurfaceGateRecord | undefined => {\n if (!isRecord(value) || typeof value.passed !== \"boolean\") return undefined;\n if (typeof value.beforeScore !== \"number\" || typeof value.afterScore !== \"number\" ||\n !Number.isFinite(value.beforeScore) || !Number.isFinite(value.afterScore)) {\n return undefined;\n }\n if (!Array.isArray(value.reasons) || !value.reasons.every((r) => typeof r === \"string\")) {\n return undefined;\n }\n return {\n passed: value.passed,\n beforeScore: value.beforeScore,\n afterScore: value.afterScore,\n reasons: value.reasons,\n };\n};\n\n// Version 1 is accepted only as inert migration data. Version 2 cannot carry\n// restrictions. Its bounded plans are re-proved against live schemas at use;\n// a persisted gate flag or metric version never grants execution authority.\nconst parseCompiledSurfaceFile = (value: unknown): CompiledSurfaceFile | undefined => {\n if (!isRecord(value) || (value.version !== 1 && value.version !== COMPILED_SURFACE_VERSION)) return undefined;\n if (value.version === COMPILED_SURFACE_VERSION) {\n if (!Array.isArray(value.normalizations) || value.normalizations.length > MAX_NORMAL_FORM_PLANS ||\n !value.normalizations.every(isNormalFormPlan) ||\n new Set(value.normalizations.map((plan) => plan.ref)).size !== value.normalizations.length) return undefined;\n if (!Array.isArray(value.actions) || value.actions.length !== 0 ||\n !Array.isArray(value.quarantined) || value.quarantined.length !== 0) return undefined;\n }\n if (!Number.isSafeInteger(value.metricVersion) || (value.metricVersion as number) < 1) {\n return undefined;\n }\n if (!Array.isArray(value.actions) || !value.actions.every((entry) => parseOverlayEntry(entry))) {\n return undefined;\n }\n if (\n !Array.isArray(value.quarantined) ||\n !value.quarantined.every((entry) => parseQuarantineEntry(entry))\n ) {\n return undefined;\n }\n if (\n !Array.isArray(value.applied) ||\n value.applied.length > MAX_COMPILED_SURFACE_PROPOSALS ||\n !value.applied.every((entry) => parseAppliedProposal(entry))\n ) {\n return undefined;\n }\n if (!parseGateRecord(value.gate)) return undefined;\n if (typeof value.evidenceDigest !== \"string\" || !value.evidenceDigest.trim()) return undefined;\n const overlaySeen = new Set<string>();\n for (const entry of value.actions) {\n const parsed = parseOverlayEntry(entry)!;\n if (overlaySeen.has(parsed.ref)) return undefined;\n overlaySeen.add(parsed.ref);\n }\n return {\n version: value.version,\n ...(value.version === COMPILED_SURFACE_VERSION ? { normalizations: value.normalizations as import(\"./normal-form.js\").NormalFormPlan[] } : {}),\n metricVersion: value.metricVersion as number,\n actions: value.actions.map((entry) => parseOverlayEntry(entry)!),\n quarantined: value.quarantined.map((entry) => parseQuarantineEntry(entry)!),\n applied: value.applied.map((entry) => parseAppliedProposal(entry)!),\n gate: parseGateRecord(value.gate)!,\n evidenceDigest: value.evidenceDigest.trim(),\n };\n};\n\n// Public guarded parse for artifact files that did not come from this\n// agent dir: exported artifacts being imported, or certification fixtures.\n// The same validation the store applies to its own file, so nothing trusts\n// an artifact shape the store would refuse to load.\nexport const parseCompiledSurfaceArtifact = (\n value: unknown,\n): CompiledSurfaceFile | undefined => parseCompiledSurfaceFile(value);\n\nexport interface LoadedCompiledSurface {\n file?: CompiledSurfaceFile;\n error?: string;\n}\n\nexport const loadCompiledSurface = (agentDir: string): LoadedCompiledSurface => {\n const file = compiledPath(compiledSurfaceDirectory(agentDir));\n let raw: string;\n try {\n raw = fs.readFileSync(file, \"utf8\");\n } catch (error) {\n // A missing artifact means the surface was never compiled; anything\n // else is damage that callers must surface, not silently rebuild.\n if (errorCode(error) === \"ENOENT\") return {};\n return { error: `compiled surface is unreadable: ${errorText(error)}` };\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n return { error: \"compiled surface is malformed JSON\" };\n }\n const parsedFile = parseCompiledSurfaceFile(parsed);\n if (!parsedFile) return { error: \"compiled surface is invalid\" };\n return { file: parsedFile };\n};\n\nexport const loadCompiledSurfaceAsync = async (\n agentDir: string,\n): Promise<LoadedCompiledSurface> => {\n const file = compiledPath(compiledSurfaceDirectory(agentDir));\n let raw: string;\n try {\n raw = await fs.promises.readFile(file, \"utf8\");\n } catch (error) {\n if (errorCode(error) === \"ENOENT\") return {};\n return { error: `compiled surface is unreadable: ${errorText(error)}` };\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n return { error: \"compiled surface is malformed JSON\" };\n }\n const parsedFile = parseCompiledSurfaceFile(parsed);\n return parsedFile ? { file: parsedFile } : { error: \"compiled surface is invalid\" };\n};\n\nexport interface SavedCompiledSurface {\n file: CompiledSurfaceFile;\n written: boolean;\n}\n\nexport const saveCompiledSurface = (\n agentDir: string,\n file: CompiledSurfaceFile,\n): SavedCompiledSurface =>\n withExclusiveFileLock(\n {\n directory: compiledSurfaceDirectory(agentDir),\n lockName: \"compiled.lock\",\n timeoutMessage: \"Timed out waiting for the compiled entropy surface lock\",\n attempts: COMPILED_LOCK_ATTEMPTS,\n delayMs: COMPILED_LOCK_DELAY_MS,\n staleMs: COMPILED_STALE_LOCK_MS,\n },\n () => {\n // A damaged artifact must never be silently rebuilt; fail so the\n // compile records the rejection and leaves the file for recovery.\n const loaded = loadCompiledSurface(agentDir);\n if (loaded.error) throw new Error(loaded.error);\n const target = compiledPath(compiledSurfaceDirectory(agentDir));\n const serialized = `${JSON.stringify(file, null, 2)}\\n`;\n try {\n if (fs.readFileSync(target, \"utf8\") === serialized) return { file, written: false };\n } catch {\n // Missing file: proceed to write.\n }\n writeJsonAtomic(target, file, { space: 2, newline: true, mode: 0o600, dirMode: 0o700 });\n return { file, written: true };\n },\n );\n\nexport const saveCompiledSurfaceAsync = async (\n agentDir: string,\n file: CompiledSurfaceFile,\n): Promise<SavedCompiledSurface> =>\n withExclusiveFileLockAsync(\n {\n directory: compiledSurfaceDirectory(agentDir),\n lockName: \"compiled.lock\",\n timeoutMessage: \"Timed out waiting for the compiled entropy surface lock\",\n attempts: COMPILED_LOCK_ATTEMPTS,\n delayMs: COMPILED_LOCK_DELAY_MS,\n staleMs: COMPILED_STALE_LOCK_MS,\n },\n async () => {\n const loaded = await loadCompiledSurfaceAsync(agentDir);\n if (loaded.error) throw new Error(loaded.error);\n const target = compiledPath(compiledSurfaceDirectory(agentDir));\n const serialized = `${JSON.stringify(file, null, 2)}\\n`;\n try {\n if (await fs.promises.readFile(target, \"utf8\") === serialized) {\n return { file, written: false };\n }\n } catch {\n // Missing file: proceed to write.\n }\n await writeJsonAtomicAsync(target, file, {\n space: 2,\n newline: true,\n mode: 0o600,\n dirMode: 0o700,\n });\n return { file, written: true };\n },\n );\n", "// Cross-process exclusive lock for Fabric's durable stores (the repair\n// table, the compiled entropy surface). Acquisition is a bounded retry over\n// mkdir; stale-lock recovery is an exclusive rename claim, so racing\n// reapers can never delete a lock a fresh writer owns.\n\nimport { randomUUID } from \"node:crypto\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\n\nconst DEFAULT_LOCK_ATTEMPTS = 50;\nconst DEFAULT_LOCK_DELAY_MS = 5;\nconst DEFAULT_STALE_LOCK_MS = 30_000;\n\nexport interface ExclusiveLockOptions {\n directory: string;\n lockName: string;\n /** Error message when acquisition times out. */\n timeoutMessage: string;\n staleMs?: number;\n attempts?: number;\n delayMs?: number;\n}\n\nconst errorCode = (error: unknown): string | undefined =>\n typeof error === \"object\" && error !== null && \"code\" in error\n ? String((error as { code?: unknown }).code)\n : undefined;\n\nconst sleepSync = (() => {\n try {\n const buffer = new Int32Array(new SharedArrayBuffer(4));\n return (ms: number): void => {\n Atomics.wait(buffer, 0, 0, ms);\n };\n } catch {\n return (): void => undefined;\n }\n})();\n\nconst processAlive = (pid: number): boolean => {\n if (!Number.isSafeInteger(pid) || pid <= 0) return false;\n try {\n process.kill(pid, 0);\n return true;\n } catch {\n return false;\n }\n};\n\nconst sleepAsync = (ms: number): Promise<void> =>\n new Promise((resolve) => setTimeout(resolve, ms));\n\nconst reapStaleLockAsync = async (\n lock: string,\n verify: (claimed: string) => Promise<boolean>,\n): Promise<boolean> => {\n const claim = `${lock}.reap-${process.pid}-${randomUUID()}`;\n try {\n await fs.promises.rename(lock, claim);\n } catch {\n return false;\n }\n if (!(await verify(claim))) {\n try {\n await fs.promises.rename(claim, lock);\n } catch {\n if (await verify(claim)) {\n await fs.promises.rm(claim, { recursive: true, force: true });\n }\n }\n return false;\n }\n await fs.promises.rm(claim, { recursive: true, force: true });\n return true;\n};\n\nexport const withExclusiveFileLockAsync = async <T>(\n options: ExclusiveLockOptions,\n operation: () => T | Promise<T>,\n): Promise<T> => {\n const attempts = options.attempts ?? DEFAULT_LOCK_ATTEMPTS;\n const delayMs = options.delayMs ?? DEFAULT_LOCK_DELAY_MS;\n const staleMs = options.staleMs ?? DEFAULT_STALE_LOCK_MS;\n await fs.promises.mkdir(options.directory, { recursive: true, mode: 0o700 });\n const lock = path.join(options.directory, options.lockName);\n const ownerPath = path.join(lock, \"owner\");\n const token = randomUUID();\n let acquired = false;\n for (let attempt = 0; attempt < attempts; attempt++) {\n try {\n await fs.promises.mkdir(lock, { mode: 0o700 });\n try {\n await fs.promises.writeFile(ownerPath, `${token}\\n${process.pid}\\n${Date.now()}\\n`, {\n encoding: \"utf-8\",\n mode: 0o600,\n });\n } catch (error) {\n await fs.promises.rm(lock, { recursive: true, force: true });\n throw error;\n }\n acquired = true;\n break;\n } catch (error) {\n if (errorCode(error) !== \"EEXIST\") throw error;\n try {\n const firstOwner = await fs.promises.readFile(ownerPath, \"utf8\");\n const [, pidText, createdText] = firstOwner.trim().split(\"\\n\");\n const stale = Date.now() - Number(createdText) > staleMs;\n if (stale && !processAlive(Number(pidText))) {\n const secondOwner = await fs.promises.readFile(ownerPath, \"utf8\");\n if (\n secondOwner === firstOwner &&\n await reapStaleLockAsync(lock, async (claimed) => {\n try {\n const owner = await fs.promises.readFile(path.join(claimed, \"owner\"), \"utf8\");\n const [, pid, created] = owner.trim().split(\"\\n\");\n return Date.now() - Number(created) > staleMs && !processAlive(Number(pid));\n } catch {\n return false;\n }\n })\n ) {\n continue;\n }\n }\n } catch {\n try {\n const first = await fs.promises.stat(lock);\n if (\n Date.now() - first.mtimeMs > staleMs &&\n await reapStaleLockAsync(lock, async (claimed) => {\n try {\n return Date.now() - (await fs.promises.stat(claimed)).mtimeMs > staleMs;\n } catch {\n return false;\n }\n })\n ) {\n continue;\n }\n } catch {\n // Lock creation or stale recovery raced; retry the bounded acquisition.\n }\n }\n if (attempt === attempts - 1) break;\n await sleepAsync(delayMs);\n }\n }\n if (!acquired) throw new Error(options.timeoutMessage);\n try {\n return await operation();\n } finally {\n try {\n const owner = await fs.promises.readFile(ownerPath, \"utf8\");\n if (owner.startsWith(`${token}\\n`)) {\n await fs.promises.rm(lock, { recursive: true, force: true });\n }\n } catch {\n // A recovering process already removed this lock.\n }\n }\n};\n\n// Stale-lock recovery must be an exclusive claim. Stat-then-delete is\n// TOCTOU: two reapers (or a reaper and a fresh writer that recreated the\n// lock in between) can both pass their checks, and the slower rm then\n// deletes a lock the faster one already replaced. rename() is the claim \u2014\n// only one process can move the directory, and removal targets the claimed\n// path, never the live lock path. A claim that turns out to hold a live\n// lock is renamed back before any destructive step; a live lock is never\n// deleted, even if the rename-back races a fresh writer.\nconst reapStaleLock = (lock: string, verify: (claimed: string) => boolean): boolean => {\n const claim = `${lock}.reap-${process.pid}-${randomUUID()}`;\n try {\n fs.renameSync(lock, claim);\n } catch {\n return false;\n }\n if (!verify(claim)) {\n try {\n fs.renameSync(claim, lock);\n } catch {\n // `lock` was recreated after the claim. Re-verify before any\n // destructive step so a claimed live lock is only ever abandoned as\n // garbage, never deleted.\n if (verify(claim)) fs.rmSync(claim, { recursive: true, force: true });\n }\n return false;\n }\n fs.rmSync(claim, { recursive: true, force: true });\n return true;\n};\n\nexport const withExclusiveFileLock = <T>(\n options: ExclusiveLockOptions,\n operation: () => T,\n): T => {\n const attempts = options.attempts ?? DEFAULT_LOCK_ATTEMPTS;\n const delayMs = options.delayMs ?? DEFAULT_LOCK_DELAY_MS;\n const staleMs = options.staleMs ?? DEFAULT_STALE_LOCK_MS;\n fs.mkdirSync(options.directory, { recursive: true, mode: 0o700 });\n const lock = path.join(options.directory, options.lockName);\n const ownerPath = path.join(lock, \"owner\");\n const token = randomUUID();\n let acquired = false;\n for (let attempt = 0; attempt < attempts; attempt++) {\n try {\n fs.mkdirSync(lock, { mode: 0o700 });\n try {\n fs.writeFileSync(ownerPath, `${token}\\n${process.pid}\\n${Date.now()}\\n`, {\n encoding: \"utf-8\",\n mode: 0o600,\n });\n } catch (error) {\n fs.rmSync(lock, { recursive: true, force: true });\n throw error;\n }\n acquired = true;\n break;\n } catch (error) {\n if (errorCode(error) !== \"EEXIST\") throw error;\n try {\n const firstOwner = fs.readFileSync(ownerPath, \"utf8\");\n const [, pidText, createdText] = firstOwner.trim().split(\"\\n\");\n const stale = Date.now() - Number(createdText) > staleMs;\n if (stale && !processAlive(Number(pidText))) {\n const secondOwner = fs.readFileSync(ownerPath, \"utf8\");\n if (\n secondOwner === firstOwner &&\n reapStaleLock(lock, (claimed) => {\n try {\n const owner = fs.readFileSync(path.join(claimed, \"owner\"), \"utf8\");\n const [, pid, created] = owner.trim().split(\"\\n\");\n return Date.now() - Number(created) > staleMs && !processAlive(Number(pid));\n } catch {\n return false;\n }\n })\n ) {\n continue;\n }\n }\n } catch {\n try {\n // Ownerless lock (crash between mkdir and the owner write): age is\n // the only signal, and the claim re-verifies it after the rename.\n const first = fs.statSync(lock);\n if (\n Date.now() - first.mtimeMs > staleMs &&\n reapStaleLock(lock, (claimed) => {\n try {\n return Date.now() - fs.statSync(claimed).mtimeMs > staleMs;\n } catch {\n return false;\n }\n })\n ) {\n continue;\n }\n } catch {\n // Lock creation or stale recovery raced; retry the bounded acquisition.\n }\n }\n if (attempt === attempts - 1) break;\n sleepSync(delayMs);\n }\n }\n if (!acquired) throw new Error(options.timeoutMessage);\n try {\n return operation();\n } finally {\n try {\n const owner = fs.readFileSync(ownerPath, \"utf8\");\n if (owner.startsWith(`${token}\\n`)) {\n fs.rmSync(lock, { recursive: true, force: true });\n }\n } catch {\n // A recovering process already removed this lock.\n }\n }\n};"],
5
+ "mappings": ";;;;;;;;;;;;;;AAQO,IAAM,yBAAyB;AAK/B,IAAM,kBAAkB;AAAA,EAC7B,OAAO;AAAA,EACP,cAAc;AAAA,EACd,OAAO;AAAA,EACP,YAAY;AAAA,EACZ,MAAM;AAAA,EACN,SAAS;AAAA,EACT,eAAe;AACjB;AAIO,IAAM,4BAA+C,CAAC,WAAW,WAAW,UAAU;;;ACvB7F,SAAS,aAAa;AAMf,IAAM,2BAA2B;AACjC,IAAM,iCAAiC;AAqBvC,IAAM,uBAAuB,OAA4B;AAAA,EAC9D,SAAS;AAAA,EAA0B,eAAe;AAAA,EAClD,SAAS,CAAC;AAAA,EAAG,aAAa,CAAC;AAAA,EAAG,gBAAgB,CAAC;AAAA,EAAG,SAAS,CAAC;AAAA,EAC5D,MAAM,EAAE,QAAQ,MAAM,aAAa,GAAG,YAAY,GAAG,SAAS,CAAC,EAAE;AAAA,EACjE,gBAAgB,eAAe,CAAC,CAAC;AACnC;AACO,IAAM,+BAA+B,CAAC,QAAyC,UACpF,eAAe,QAAQ,YAAY,2BAA2B,OAAO,kBAAkB,CAAC,IAAI,CAAC,CAAC,MAC9F,eAAe,MAAM,YAAY,2BAA2B,MAAM,kBAAkB,CAAC,IAAI,CAAC,CAAC;AAGtF,IAAM,iCAAiC,CAC5C,MACA,kBAEA,MAAM,YAAY,4BAA4B,KAAK,kBAAkB,gBACjE,KAAK,KAAK,aACV;AACN,IAAM,gBAAgB,CAAC,UACrB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC9D,IAAM,eAAe,CAAC,WAA4B,eAAe,MAAM;AAIvE,IAAM,qBAAqB,CAAC,MAAc,YAAqB,UAAyC;AACxG,IAAM,uBAAuB,CAA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ACtD,QAAI,OAAO,MAAO,OAAM,IAAI,MAAM,OAAO,KAAK;AAC9C,UAAM,SAAS,aAAa,yBAAyB,QAAQ,CAAC;AAC9D,UAAM,aAAa,GAAG,KAAK,UAAU,MAAM,MAAM,CAAC,CAAC;AAAA;AACnD,QAAI;AACF,UAAI,MAAMA,IAAG,SAAS,SAAS,QAAQ,MAAM,MAAM,YAAY;AAC7D,eAAO,EAAE,MAAM,SAAS,MAAM;AAAA,MAChC;AAAA,IACF,QAAQ;AAAA,IAER;AACA,UAAM,qBAAqB,QAAQ,MAAM;AAAA,MACvC,OAAO;AAAA,MACP,SAAS;AAAA,MACT,MAAM;AAAA,MACN,SAAS;AAAA,IACX,CAAC;AACD,WAAO,EAAE,MAAM,SAAS,KAAK;AAAA,EAC/B;AACF;",
6
+ "names": ["fs", "path", "path", "errorCode", "fs"]
7
+ }
@@ -35,6 +35,7 @@ export interface CompiledSurfaceFile {
35
35
  }
36
36
  export declare const emptyCompiledSurface: () => CompiledSurfaceFile;
37
37
  export declare const compiledSurfaceEffectChanged: (before: CompiledSurfaceFile | undefined, after: CompiledSurfaceFile) => boolean;
38
+ export declare const comparableCompiledSurfaceScore: (file: CompiledSurfaceFile | undefined, metricVersion: number) => number | undefined;
38
39
  export declare const schemaDigest: (schema: unknown) => string;
39
40
  export declare const effectiveSchemaFor: (_ref: string, liveSchema: unknown, _file?: CompiledSurfaceFile) => unknown;
40
41
  export declare const applyCompiledSurface: (live: EntropySurfaceSnapshot, _file?: CompiledSurfaceFile) => EntropySurfaceSnapshot;
@@ -1 +1 @@
1
- {"version":3,"file":"compiled-surface.d.ts","sourceRoot":"","sources":["../../src/entropy/compiled-surface.ts"],"names":[],"mappings":"AAKA,OAAO,EAA+C,KAAK,cAAc,EAAE,MAAM,kBAAkB,CAAC;AACpG,OAAO,KAAK,EAAE,gBAAgB,EAAE,eAAe,EAAE,sBAAsB,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAE/G,eAAO,MAAM,wBAA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,QAAQ,SAAS,iBAAiB,EAAE,EACpC,aAAa,WAAW,CAAC,MAAM,CAAC,EAChC,aAAa,SAAS,gBAAgB,EAAE,KACvC,OAAO,CAAC,eAAe,EAAE,CAsE3B,CAAC"}
@@ -50,7 +50,7 @@ import {
50
50
  sessionWindowEvidence,
51
51
  sessionWindowEvidenceAsync,
52
52
  surfaceFreedomReport
53
- } from "../chunks/chunk-LLJXPPTA.js";
53
+ } from "../chunks/chunk-6ELA5OWI.js";
54
54
  import {
55
55
  COMPILED_SURFACE_VERSION,
56
56
  ENTROPY_INVOCATION_STAGES,
@@ -58,6 +58,7 @@ import {
58
58
  ENTROPY_WEIGHTS,
59
59
  MAX_COMPILED_SURFACE_PROPOSALS,
60
60
  applyCompiledSurface,
61
+ comparableCompiledSurfaceScore,
61
62
  compiledSurfaceDirectory,
62
63
  compiledSurfaceEffectChanged,
63
64
  effectiveSchemaFor,
@@ -73,7 +74,7 @@ import {
73
74
  saveCompiledSurface,
74
75
  saveCompiledSurfaceAsync,
75
76
  schemaDigest
76
- } from "../chunks/chunk-5MDFFHOO.js";
77
+ } from "../chunks/chunk-BSGA3KSB.js";
77
78
  import "../chunks/chunk-KNBPIZF7.js";
78
79
  import "../chunks/chunk-VJJFD42F.js";
79
80
  import "../chunks/chunk-KAD7UWT2.js";
@@ -116,6 +117,7 @@ export {
116
117
  applyCompiledSurface,
117
118
  applyNormalFormPlan,
118
119
  applyProposalsToSurface,
120
+ comparableCompiledSurfaceScore,
119
121
  compareCodeUnits,
120
122
  compileEntropySurface,
121
123
  compileEntropySurfaceAsync,
@@ -55,7 +55,7 @@ import {
55
55
  import {
56
56
  loadCompiledSurface,
57
57
  withExclusiveFileLockAsync
58
- } from "./chunks/chunk-5MDFFHOO.js";
58
+ } from "./chunks/chunk-BSGA3KSB.js";
59
59
  import {
60
60
  MemoryProvider
61
61
  } from "./chunks/chunk-6GT4YJT2.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,YAAY,EAEb,MAAM,iCAAiC,CAAC;AAyJzC,eAAO,MAAM,2BAA2B,IAAI,CAAC;AAC7C,YAAY,EAAE,wBAAwB,EAAE,MAAM,mBAAmB,CAAC;AAClE,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,mBAAmB,CAAC;AAElE,wBAA8B,QAAQ,CAAC,EAAE,EAAE,YAAY,EAAE,OAAO,GAAE;IAAE,WAAW,CAAC,EAAE,wBAAwB,CAAA;CAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CA6tBhI;AAED,cAAc,kBAAkB,CAAC;AACjC,cAAc,oBAAoB,CAAC;AACnC,cAAc,eAAe,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,YAAY,EAEb,MAAM,iCAAiC,CAAC;AAyJzC,eAAO,MAAM,2BAA2B,IAAI,CAAC;AAC7C,YAAY,EAAE,wBAAwB,EAAE,MAAM,mBAAmB,CAAC;AAClE,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,mBAAmB,CAAC;AAElE,wBAA8B,QAAQ,CAAC,EAAE,EAAE,YAAY,EAAE,OAAO,GAAE;IAAE,WAAW,CAAC,EAAE,wBAAwB,CAAA;CAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAguBhI;AAED,cAAc,kBAAkB,CAAC;AACjC,cAAc,oBAAoB,CAAC;AACnC,cAAc,eAAe,CAAC"}
package/dist/index.js CHANGED
@@ -142,7 +142,7 @@ import {
142
142
  sessionWindowEvidence,
143
143
  sessionWindowEvidenceAsync,
144
144
  surfaceFreedomReport
145
- } from "./chunks/chunk-LLJXPPTA.js";
145
+ } from "./chunks/chunk-6ELA5OWI.js";
146
146
  import {
147
147
  COMPILED_SURFACE_VERSION,
148
148
  ENTROPY_INVOCATION_STAGES,
@@ -150,6 +150,7 @@ import {
150
150
  ENTROPY_WEIGHTS,
151
151
  MAX_COMPILED_SURFACE_PROPOSALS,
152
152
  applyCompiledSurface,
153
+ comparableCompiledSurfaceScore,
153
154
  compiledSurfaceDirectory,
154
155
  compiledSurfaceEffectChanged,
155
156
  effectiveSchemaFor,
@@ -165,7 +166,7 @@ import {
165
166
  saveCompiledSurface,
166
167
  saveCompiledSurfaceAsync,
167
168
  schemaDigest
168
- } from "./chunks/chunk-5MDFFHOO.js";
169
+ } from "./chunks/chunk-BSGA3KSB.js";
169
170
  import "./chunks/chunk-KNBPIZF7.js";
170
171
  import "./chunks/chunk-VJJFD42F.js";
171
172
  import {
@@ -5459,9 +5460,10 @@ async function piFabric(pi, options = {}) {
5459
5460
  const saved = await saveCompiledSurfaceAsync(agentDir, outcome.artifact);
5460
5461
  if (current()) {
5461
5462
  setActiveCompiledSurface(saved.file);
5462
- if (saved.written && compiledSurfaceEffectChanged(loaded.file, saved.file) && context.hasUI) {
5463
+ const previousScore = comparableCompiledSurfaceScore(loaded.file, saved.file.metricVersion);
5464
+ if (previousScore !== void 0 && outcome.report.score < previousScore && context.hasUI) {
5463
5465
  context.ui.notify(formatEntropyCompileNotice({
5464
- beforeScore: outcome.report.score,
5466
+ beforeScore: previousScore,
5465
5467
  afterScore: outcome.report.score,
5466
5468
  normalizations: saved.file.normalizations?.length ?? 0
5467
5469
  }), "info");
@@ -5863,6 +5865,7 @@ export {
5863
5865
  applyCompiledSurface,
5864
5866
  applyNormalFormPlan,
5865
5867
  applyProposalsToSurface,
5868
+ comparableCompiledSurfaceScore,
5866
5869
  compareCodeUnits,
5867
5870
  compileEntropySurface,
5868
5871
  compileEntropySurfaceAsync,