pi-fabric 0.79.0 → 0.79.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.
- package/dist/chunks/{chunk-5IFANSBG.js → chunk-7O2SJRDL.js} +2 -2
- package/dist/chunks/{chunk-5IFANSBG.js.map → chunk-7O2SJRDL.js.map} +2 -2
- package/dist/chunks/{chunk-UKZ452XN.js → chunk-NQIGNZBM.js} +2 -2
- package/dist/chunks/{chunk-NXTORPRY.js → chunk-R6KHFESZ.js} +21 -7
- package/dist/chunks/chunk-R6KHFESZ.js.map +7 -0
- package/dist/chunks/{fabric-runtime-state-YKNG3IDT.js → fabric-runtime-state-SX47QTFW.js} +3 -3
- package/dist/core/action-registry.d.ts +5 -1
- package/dist/core/action-registry.d.ts.map +1 -1
- package/dist/core/action-registry.js +1 -1
- package/dist/entropy/index.js +1 -1
- package/dist/entropy/surface.d.ts +1 -0
- package/dist/entropy/surface.d.ts.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +33 -12
- package/dist/index.js.map +2 -2
- package/docs/entropy.md +10 -5
- package/docs/speculation.md +13 -0
- package/package.json +1 -1
- package/dist/chunks/chunk-NXTORPRY.js.map +0 -7
- /package/dist/chunks/{chunk-UKZ452XN.js.map → chunk-NQIGNZBM.js.map} +0 -0
- /package/dist/chunks/{fabric-runtime-state-YKNG3IDT.js.map → fabric-runtime-state-SX47QTFW.js.map} +0 -0
|
@@ -676,7 +676,7 @@ var surfaceInvocationContext = (input) => ({
|
|
|
676
676
|
});
|
|
677
677
|
var liveSurfaceSnapshot = async (input) => {
|
|
678
678
|
const actions = await input.registry.list(
|
|
679
|
-
{ limit: SURFACE_LIST_LIMIT },
|
|
679
|
+
{ limit: SURFACE_LIST_LIMIT, declared: true },
|
|
680
680
|
surfaceInvocationContext(input)
|
|
681
681
|
);
|
|
682
682
|
return {
|
|
@@ -1043,4 +1043,4 @@ export {
|
|
|
1043
1043
|
AUTO_APPLY_PROPOSAL_KINDS,
|
|
1044
1044
|
compileEntropySurface
|
|
1045
1045
|
};
|
|
1046
|
-
//# sourceMappingURL=chunk-
|
|
1046
|
+
//# sourceMappingURL=chunk-7O2SJRDL.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/entropy/types.ts", "../../src/entropy/fingerprint.ts", "../../src/entropy/meter.ts", "../../src/entropy/passes.ts", "../../src/entropy/surface.ts", "../../src/entropy/compiler.ts", "../../src/entropy/corpus.ts", "../../src/entropy/sessions.ts"],
|
|
4
|
-
"sourcesContent": ["// Deterministic tool-entropy measurement for the Fabric tool surface.\n//\n// Entropy here is operational, not psychological: it counts the bits of\n// corrective freedom a surface leaves open, measured only from artifacts\n// Fabric already records in typed form (trace V1 operations, the repair\n// table, live JSON schemas). No model judges anything; the same inputs and\n// the same metric version always produce the same report.\n\nexport const ENTROPY_METRIC_VERSION = 2 as const;\n\n// Fixed weights per metric version. Changing any weight bumps\n// ENTROPY_METRIC_VERSION so trend lines never mix formulas.\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}\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 catalog-repair row: `ref` is the target the row 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.\nexport interface EntropyValueObservation {\n ref: string;\n key: string;\n value: string | number | boolean;\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 shapeEntropyBits: number;\n failureStageEntropyBits: number;\n churnRate: number;\n lexiconRows: number;\n staticFreedom: number;\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: each stamped trace measures against the\n// same surface, so the breakdown names which model exercised the freedom.\nexport interface EntropyModelReport {\n model: string;\n operations: number;\n actionOperations: number;\n succeeded: number;\n invocationRejections: number;\n invocationRejectionsPer1k: number;\n behavioralScore: number;\n}\n\nexport interface EntropyReport {\n metricVersion: typeof ENTROPY_METRIC_VERSION;\n catalogDigest: string;\n totals: EntropyTotals;\n shapeEntropyBits: number;\n failureStageEntropyBits: number;\n churnRate: number;\n navigationRatio: number;\n flowEntropyBits: number;\n lexiconRows: number;\n staticFreedom: number;\n /** Surface share of the score: static freedom of the refs the corpus used. */\n staticScore: number;\n /** Everything models exercised: wobble, churn, rejections, navigation, flow, lexicon. */\n behavioralScore: number;\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: \"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: \"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 | {\n kind: \"modal-rename\";\n level: \"key\" | \"action\";\n ref: string;\n from: string;\n to: string;\n note: string;\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", "// Deterministic fingerprints for the entropy meter: canonical call-shape\n// signatures, signature distance (retry churn), Shannon entropy in bits, and\n// the static freedom score of a JSON Schema. Everything here is a pure\n// function of its inputs; the same value always yields the same fingerprint.\n\nimport type { EntropyTrend } from \"./types.js\";\n\nconst SIGNATURE_MAX_KEYS = 32;\nconst SIGNATURE_MAX_DEPTH = 3;\n// Enum cardinality whose freedom saturates at 1.0 (log2 of 64 values).\nconst ENUM_SATURATION_BITS = 6;\n\nconst isPlainRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n// Fixed rounding for every reported metric value. Same inputs, same floats,\n// same six decimal places \u2014 report JSON is byte-stable. Negative zero\n// collapses to zero so single-class entropies compare equal to zero.\nexport const roundMetric = (value: number): number => {\n const rounded = Math.round(value * 1e6) / 1e6;\n return rounded === 0 ? 0 : rounded;\n};\n\n// Code-unit string comparison: locale-independent, so ordering never varies\n// with the host's ICU data.\nexport const compareCodeUnits = (left: string, right: string): number =>\n left < right ? -1 : left > right ? 1 : 0;\n\nconst typeTag = (value: unknown, depth: number): string => {\n if (value === null) return \"null\";\n if (Array.isArray(value)) return \"arr\";\n switch (typeof value) {\n case \"string\":\n return \"str\";\n case \"number\":\n return \"num\";\n case \"boolean\":\n return \"bool\";\n case \"object\": {\n if (depth >= SIGNATURE_MAX_DEPTH) return \"obj\";\n try {\n const record = value as Record<string, unknown>;\n const keys = Object.keys(record).sort();\n const head = keys\n .slice(0, SIGNATURE_MAX_KEYS)\n .map((key) => `${key}:${typeTag(record[key], depth + 1)}`);\n if (keys.length > SIGNATURE_MAX_KEYS) {\n head.push(`\u2026+${keys.length - SIGNATURE_MAX_KEYS}`);\n }\n return `{${head.join(\",\")}}`;\n } catch {\n return \"obj\";\n }\n }\n default:\n return \"other\";\n }\n};\n\n// Canonical argument-shape signature: sorted parameter names with a bounded\n// value-type tag each. Key order and value contents never matter \u2014 only the\n// shape the model chose.\nexport const shapeSignature = (args: Record<string, unknown>): string => {\n const keys = Object.keys(args).sort();\n const head = keys\n .slice(0, SIGNATURE_MAX_KEYS)\n .map((key) => `${key}:${typeTag(args[key], 1)}`);\n if (keys.length > SIGNATURE_MAX_KEYS) {\n head.push(`\u2026+${keys.length - SIGNATURE_MAX_KEYS}`);\n }\n return `(${head.join(\",\")})`;\n};\n\n// Normalized Levenshtein distance between two signatures, in [0, 1]. Retry\n// churn is the distance between a failed call's shape and the next attempt's.\nexport const signatureDistance = (left: string, right: string): number => {\n if (left === right) return 0;\n const bound = Math.max(left.length, right.length);\n if (bound === 0) return 0;\n let previous: number[] = [];\n for (let index = 0; index <= right.length; index++) {\n previous.push(index);\n }\n for (let index = 1; index <= left.length; index++) {\n const current: number[] = [index];\n for (let inner = 1; inner <= right.length; inner++) {\n const substitution = previous[inner - 1]! + (left[index - 1] === right[inner - 1] ? 0 : 1);\n const insertion = current[inner - 1]! + 1;\n const deletion = previous[inner]! + 1;\n current.push(Math.min(substitution, insertion, deletion));\n }\n previous = current;\n }\n return roundMetric(previous[right.length]! / bound);\n};\n\n// Shannon entropy in bits over a count distribution, rounded to 1e-6.\n// A single class is zero bits; a uniform split over k classes is log2(k).\nexport const shannonEntropyBits = (counts: readonly number[]): number => {\n const total = counts.reduce((sum, value) => sum + value, 0);\n if (total <= 0) return 0;\n let bits = 0;\n for (const count of counts) {\n if (count <= 0) continue;\n const probability = count / total;\n bits += probability * Math.log2(probability);\n }\n return roundMetric(-bits);\n};\n\nconst schemaFreedom = (schema: unknown, depth: number): number => {\n if (depth > SIGNATURE_MAX_DEPTH) return 0.5;\n if (!isPlainRecord(schema)) return 0.5;\n const union = Array.isArray(schema.anyOf)\n ? schema.anyOf\n : Array.isArray(schema.oneOf)\n ? schema.oneOf\n : undefined;\n if (union) {\n const scores = union.map((branch) => schemaFreedom(branch, depth + 1));\n const widest = scores.length > 0 ? Math.max(...scores) : 0;\n return roundMetric(widest + 0.1 * Math.max(0, union.length - 1));\n }\n if (Array.isArray(schema.enum)) {\n return roundMetric(\n Math.min(1, Math.log2(Math.max(1, schema.enum.length)) / ENUM_SATURATION_BITS),\n );\n }\n if (\"const\" in schema) return 0;\n const type = schema.type;\n if (typeof type !== \"string\") return 0.75;\n if (type === \"boolean\") return 0.1;\n if (type === \"number\" || type === \"integer\") return 0.5;\n if (type === \"string\") return 1;\n if (type === \"array\") return roundMetric(0.5 + 0.5 * schemaFreedom(schema.items, depth + 1));\n if (type === \"object\") {\n const properties = schema.properties;\n if (!isPlainRecord(properties)) return 1;\n const keys = Object.keys(properties).sort();\n if (keys.length === 0) return 1;\n const required = Array.isArray(schema.required)\n ? schema.required.filter((entry): entry is string => typeof entry === \"string\")\n : [];\n let score = 0;\n for (const key of keys) {\n score += schemaFreedom(properties[key], depth + 1);\n if (!required.includes(key)) score += 0.25;\n }\n if (schema.additionalProperties !== false) score += 0.5;\n return roundMetric(score);\n }\n return 0.75;\n};\n\n// Static freedom of one action's input schema: free strings dominate, enums\n// shrink with log2 cardinality, literals cost nothing, and optional or\n// open-ended parameters add tax. Computable with an empty corpus, which is\n// what lets the compiler score candidate surfaces before deployment.\nexport const staticFreedomFromSchema = (schema: unknown): number => schemaFreedom(schema, 0);\n\n// Least-squares slope of a score sequence, oldest to newest. The on-demand\n// session trend feeds this per-session scores; a flat or negative slope is\n// the ratchet holding.\nexport const trendFromScores = (scores: readonly number[]): EntropyTrend => {\n const count = scores.length;\n const first = count > 0 ? scores[0] : undefined;\n const last = count > 0 ? scores[count - 1] : undefined;\n let slope = 0;\n if (count >= 2) {\n const meanX = (count - 1) / 2;\n const meanY = scores.reduce((sum, value) => sum + value, 0) / count;\n let numerator = 0;\n let denominator = 0;\n for (let index = 0; index < count; index++) {\n numerator += (index - meanX) * (scores[index]! - meanY);\n denominator += (index - meanX) ** 2;\n }\n slope = denominator > 0 ? numerator / denominator : 0;\n }\n return {\n count,\n ...(first !== undefined ? { first: roundMetric(first) } : {}),\n ...(last !== undefined ? { last: roundMetric(last) } : {}),\n slopePerStep: roundMetric(slope),\n };\n};\n", "import {\n ENTROPY_INVOCATION_STAGES,\n ENTROPY_METRIC_VERSION,\n ENTROPY_WEIGHTS,\n type EntropyModelReport,\n type EntropyRefReport,\n type EntropyRepairRowInput,\n type EntropyReport,\n type EntropyShapeSignature,\n type EntropySurfaceSnapshot,\n type EntropyTotals,\n type EntropyTraceInput,\n} from \"./types.js\";\nimport {\n compareCodeUnits,\n roundMetric,\n shannonEntropyBits,\n shapeSignature,\n signatureDistance,\n staticFreedomFromSchema,\n} from \"./fingerprint.js\";\n\n// The meter is a pure function of its inputs: typed trace operations, an\n// optional surface snapshot, and the normalized repair table. It reads no\n// clocks, no randomness, and no prose \u2014 only the residues of non-canonical\n// behavior Fabric already records. Same inputs and metric version, same\n// report, on every run.\n\nexport interface EntropyMeterInput {\n traces: readonly EntropyTraceInput[];\n surface?: EntropySurfaceSnapshot;\n repairs?: readonly EntropyRepairRowInput[];\n catalogDigest?: string;\n}\n\nconst DISCOVERY_PREFIX = \"fabric.discovery.\";\nconst WORKFLOW_PREFIX = \"fabric.workflow.\";\nconst DEFAULT_TASK_KEY = \"(none)\";\nconst TOP_SIGNATURES = 8;\n\ninterface RefAccumulator {\n calls: number;\n succeeded: number;\n failed: number;\n signatures: Map<string, number>;\n stages: Map<string, number>;\n churnPairs: number;\n churnSum: number;\n}\n\n// The core pass without per-model attribution; measureEntropy wraps it so\n// each model's behavioral terms come from the same formula over its own\n// traces, measured against the same surface.\ntype EntropyReportCore = Omit<EntropyReport, \"byModel\">;\n\nconst measureOnce = (input: EntropyMeterInput): EntropyReportCore => {\n const surfaceByRef = new Map<string, unknown>();\n if (input.surface) {\n for (const action of input.surface.actions) surfaceByRef.set(action.ref, action.inputSchema);\n }\n\n const lexiconByRef = new Map<string, number>();\n let lexiconRows = 0;\n for (const row of input.repairs ?? []) {\n lexiconByRef.set(row.ref, (lexiconByRef.get(row.ref) ?? 0) + 1);\n lexiconRows += 1;\n }\n\n const totals: EntropyTotals = {\n traces: input.traces.length,\n operations: 0,\n actionOperations: 0,\n discoveryOperations: 0,\n workflowOperations: 0,\n succeeded: 0,\n failed: 0,\n aborted: 0,\n timedOut: 0,\n invocationRejections: 0,\n invocationRejectionsPer1k: 0,\n };\n\n const refs = new Map<string, RefAccumulator>();\n const taskSequences = new Map<string, Map<string, number>>();\n let churnPairs = 0;\n let churnSum = 0;\n\n const accumulator = (ref: string): RefAccumulator => {\n const existing = refs.get(ref);\n if (existing) return existing;\n const created: RefAccumulator = {\n calls: 0,\n succeeded: 0,\n failed: 0,\n signatures: new Map<string, number>(),\n stages: new Map<string, number>(),\n churnPairs: 0,\n churnSum: 0,\n };\n refs.set(ref, created);\n return created;\n };\n\n for (const sourceTrace of input.traces) {\n const taskKey = sourceTrace.taskKey ?? DEFAULT_TASK_KEY;\n const sequence: string[] = [];\n const pendingFailed = new Map<string, string>();\n for (const operation of sourceTrace.operations) {\n totals.operations += 1;\n if (operation.ref.startsWith(DISCOVERY_PREFIX)) {\n totals.discoveryOperations += 1;\n continue;\n }\n if (operation.ref.startsWith(WORKFLOW_PREFIX)) {\n totals.workflowOperations += 1;\n continue;\n }\n totals.actionOperations += 1;\n sequence.push(operation.ref);\n const acc = accumulator(operation.ref);\n acc.calls += 1;\n if (operation.outcome === \"succeeded\") {\n totals.succeeded += 1;\n acc.succeeded += 1;\n } else if (operation.outcome === \"failed\") {\n totals.failed += 1;\n acc.failed += 1;\n } else if (operation.outcome === \"aborted\") {\n totals.aborted += 1;\n } else {\n totals.timedOut += 1;\n }\n const signature = shapeSignature(operation.args);\n acc.signatures.set(signature, (acc.signatures.get(signature) ?? 0) + 1);\n if (operation.outcome === \"failed\") {\n const stage = operation.failureStage ?? \"unknown\";\n acc.stages.set(stage, (acc.stages.get(stage) ?? 0) + 1);\n if (ENTROPY_INVOCATION_STAGES.includes(stage)) totals.invocationRejections += 1;\n }\n const pending = pendingFailed.get(operation.ref);\n if (pending !== undefined) {\n const distance = signatureDistance(pending, signature);\n acc.churnPairs += 1;\n acc.churnSum += distance;\n churnPairs += 1;\n churnSum += distance;\n pendingFailed.delete(operation.ref);\n }\n if (operation.outcome === \"failed\") pendingFailed.set(operation.ref, signature);\n }\n if (sequence.length > 0) {\n const key = sequence.join(\"\u2192\");\n const perTask = taskSequences.get(taskKey) ?? new Map<string, number>();\n perTask.set(key, (perTask.get(key) ?? 0) + 1);\n taskSequences.set(taskKey, perTask);\n }\n }\n\n // Sorted iteration keeps every downstream sum independent of input order.\n const refEntries = [...refs.entries()].sort(([left], [right]) => compareCodeUnits(left, right));\n const refReports: EntropyRefReport[] = [];\n let staticFreedomTotal = 0;\n let staticWeighted = 0;\n let shapeWeighted = 0;\n let failureStageWeighted = 0;\n let scoreSum = 0;\n for (const [ref, acc] of refEntries) {\n const shapeEntropyBits = shannonEntropyBits([...acc.signatures.values()]);\n const failureStageEntropyBits = shannonEntropyBits([...acc.stages.values()]);\n const refChurnRate = acc.churnPairs > 0 ? roundMetric(acc.churnSum / acc.churnPairs) : 0;\n const lexicon = lexiconByRef.get(ref) ?? 0;\n const staticFreedom = surfaceByRef.has(ref)\n ? staticFreedomFromSchema(surfaceByRef.get(ref))\n : 0;\n staticFreedomTotal += staticFreedom;\n staticWeighted += ENTROPY_WEIGHTS.staticFreedom * staticFreedom;\n shapeWeighted += shapeEntropyBits * acc.calls;\n failureStageWeighted += failureStageEntropyBits * acc.failed;\n const score = roundMetric(\n ENTROPY_WEIGHTS.shape * shapeEntropyBits +\n ENTROPY_WEIGHTS.failureStage * failureStageEntropyBits +\n ENTROPY_WEIGHTS.churn * refChurnRate +\n ENTROPY_WEIGHTS.lexicon * lexicon +\n ENTROPY_WEIGHTS.staticFreedom * staticFreedom,\n );\n scoreSum += score;\n const shapeSignatures: EntropyShapeSignature[] = [...acc.signatures.entries()]\n .map(([signature, count]) => ({ signature, count }))\n .sort(\n (left, right) => right.count - left.count || compareCodeUnits(left.signature, right.signature),\n )\n .slice(0, TOP_SIGNATURES);\n refReports.push({\n ref,\n calls: acc.calls,\n succeeded: acc.succeeded,\n failed: acc.failed,\n shapeSignatures,\n shapeEntropyBits,\n failureStageEntropyBits,\n churnRate: refChurnRate,\n lexiconRows: lexicon,\n staticFreedom,\n score,\n });\n }\n\n const navigationRatio =\n totals.actionOperations > 0\n ? roundMetric(totals.discoveryOperations / totals.actionOperations)\n : 0;\n let flowWeighted = 0;\n let flowOccurrences = 0;\n for (const perTask of taskSequences.values()) {\n const counts = [...perTask.values()];\n const occurrences = counts.reduce((sum, value) => sum + value, 0);\n flowWeighted += shannonEntropyBits(counts) * occurrences;\n flowOccurrences += occurrences;\n }\n const flowEntropyBits = flowOccurrences > 0 ? roundMetric(flowWeighted / flowOccurrences) : 0;\n totals.invocationRejectionsPer1k =\n totals.actionOperations > 0\n ? roundMetric((totals.invocationRejections / totals.actionOperations) * 1000)\n : 0;\n\n const score = roundMetric(\n (scoreSum +\n ENTROPY_WEIGHTS.navigation * navigationRatio +\n ENTROPY_WEIGHTS.flow * flowEntropyBits) /\n Math.max(1, totals.succeeded),\n );\n // Decomposition: the surface share prices the potential the corpus used;\n // everything else is freedom models actually exercised. Good is\n // behavioralScore \u2192 0 with staticScore shrinking only through compiled\n // surface changes.\n const staticScore = roundMetric(staticWeighted / Math.max(1, totals.succeeded));\n const behavioralScore = roundMetric(score - staticScore);\n\n const sortedRefs = [...refReports].sort(\n (left, right) => right.score - left.score || compareCodeUnits(left.ref, right.ref),\n );\n\n return {\n metricVersion: ENTROPY_METRIC_VERSION,\n catalogDigest: input.catalogDigest ?? \"\",\n totals,\n shapeEntropyBits:\n totals.actionOperations > 0 ? roundMetric(shapeWeighted / totals.actionOperations) : 0,\n failureStageEntropyBits: totals.failed > 0 ? roundMetric(failureStageWeighted / totals.failed) : 0,\n churnRate: churnPairs > 0 ? roundMetric(churnSum / churnPairs) : 0,\n navigationRatio,\n flowEntropyBits,\n lexiconRows,\n staticFreedom: roundMetric(staticFreedomTotal),\n staticScore,\n behavioralScore,\n score,\n refs: sortedRefs,\n };\n};\n\nexport const measureEntropy = (input: EntropyMeterInput): EntropyReport => {\n const report = measureOnce(input);\n const groups = new Map<string, EntropyTraceInput[]>();\n for (const sourceTrace of input.traces) {\n if (!sourceTrace.model) continue;\n const group = groups.get(sourceTrace.model) ?? [];\n group.push(sourceTrace);\n groups.set(sourceTrace.model, group);\n }\n // Only stamped traces attribute; everything else stays in the global\n // report. Sorted iteration keeps the breakdown order stable.\n const byModel: EntropyModelReport[] = [...groups.entries()]\n .sort(([left], [right]) => compareCodeUnits(left, right))\n .map(([model, traces]) => {\n const scoped = measureOnce({ ...input, traces });\n return {\n model,\n operations: scoped.totals.operations,\n actionOperations: scoped.totals.actionOperations,\n succeeded: scoped.totals.succeeded,\n invocationRejections: scoped.totals.invocationRejections,\n invocationRejectionsPer1k: scoped.totals.invocationRejectionsPer1k,\n behavioralScore: scoped.behavioralScore,\n };\n });\n return { ...report, byModel };\n};\n", "import type {\n EntropyGateResult,\n EntropyProposal,\n EntropyRefReport,\n EntropyReport,\n EntropyRepairRowInput,\n EntropySurfaceAction,\n EntropySurfaceSnapshot,\n EntropyTraceInput,\n EntropyValueObservation,\n} from \"./types.js\";\nimport { compareCodeUnits, roundMetric } from \"./fingerprint.js\";\n\n// Deterministic reduction proposals. Each pass is a pure function over the\n// same typed artifacts the meter reads, with fixed thresholds, and every\n// proposal carries the evidence that triggered it. `applyProposalsToSurface`\n// rewrites the surface for the mechanically applicable kinds; overload-split\n// and sequence-fuse author new composite definitions, so they stay\n// review-only. The gate is the ratchet: a compiled surface must never\n// increase the measured score and must never drop successful calls.\n\nexport interface EntropyProposalInput {\n report: EntropyReport;\n traces: readonly EntropyTraceInput[];\n surface?: EntropySurfaceSnapshot;\n repairs?: readonly EntropyRepairRowInput[];\n valueObservations?: readonly EntropyValueObservation[];\n}\n\nconst ENUM_MIN_OBSERVATIONS = 8;\nconst ENUM_MAX_DISTINCT = 8;\nconst ENUM_MIN_TOP_SHARE = 0.5;\nconst SPLIT_MIN_SHAPE_ENTROPY_BITS = 1;\nconst SPLIT_MIN_CLUSTER_CALLS = 2;\nconst FUSE_MIN_SEQUENCE_LENGTH = 3;\nconst FUSE_MAX_SEQUENCE_LENGTH = 6;\nconst FUSE_MIN_OCCURRENCES = 2;\nconst QUARANTINE_MIN_CALLS = 3;\nconst QUARANTINE_MIN_STAGE_ENTROPY_BITS = 1;\nconst MAX_PROPOSALS_PER_KIND = 8;\n\nconst isPlainRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst valueKey = (value: string | number | boolean): string => `${typeof value}:${String(value)}`;\n\nconst schemaProperties = (schema: unknown): Record<string, unknown> | undefined => {\n if (!isPlainRecord(schema)) return undefined;\n const properties = schema.properties;\n return isPlainRecord(properties) ? properties : undefined;\n};\n\nconst enumKeys = (schema: unknown): Set<string> | undefined => {\n if (!isPlainRecord(schema) || !Array.isArray(schema.enum)) return undefined;\n const keys = new Set<string>();\n for (const entry of schema.enum) {\n if (typeof entry === \"string\" || typeof entry === \"number\" || typeof entry === \"boolean\") {\n keys.add(valueKey(entry));\n }\n }\n return keys;\n};\n\nconst contains = (outer: readonly string[], inner: readonly string[]): boolean => {\n if (outer.length < inner.length) return false;\n for (let start = 0; start + inner.length <= outer.length; start++) {\n let matches = true;\n for (let index = 0; index < inner.length; index++) {\n if (outer[start + index] !== inner[index]) {\n matches = false;\n break;\n }\n }\n if (matches) return true;\n }\n return false;\n};\n\nexport const proposeEntropyReductions = (input: EntropyProposalInput): EntropyProposal[] => {\n const calledRefs = new Map<string, EntropyRefReport>();\n for (const ref of input.report.refs) calledRefs.set(ref.ref, ref);\n const surfaceByRef = new Map<string, unknown>();\n const surfaceRefs = new Set<string>();\n if (input.surface) {\n for (const action of input.surface.actions) {\n surfaceByRef.set(action.ref, action.inputSchema);\n surfaceRefs.add(action.ref);\n }\n }\n\n const proposals: EntropyProposal[] = [];\n\n // enum-tighten: a parameter whose observed values are few and concentrated\n // compiles into an enum, so future off-modal values fail (or repair)\n // deterministically instead of slipping through a free string.\n const observations = new Map<\n string,\n {\n ref: string;\n key: string;\n counts: Map<string, { value: string | number | boolean; count: number }>;\n total: number;\n }\n >();\n const observeValue = (ref: string, key: string, value: string | number | boolean): void => {\n const id = `${ref}\\u0000${key}`;\n const entry =\n observations.get(id) ??\n {\n ref,\n key,\n counts: new Map<string, { value: string | number | boolean; count: number }>(),\n total: 0,\n };\n const valueId = valueKey(value);\n const existing = entry.counts.get(valueId);\n entry.counts.set(valueId, { value, count: (existing?.count ?? 0) + 1 });\n entry.total += 1;\n observations.set(id, entry);\n };\n // Verbatim audit observations are the authoritative value corpus when\n // supplied: audits carry every argument, including the parameters the\n // trace projection drops. Without them the scan uses the projected trace\n // args.\n if (input.valueObservations) {\n for (const observation of input.valueObservations) {\n observeValue(observation.ref, observation.key, observation.value);\n }\n } else {\n for (const sourceTrace of input.traces) {\n for (const operation of sourceTrace.operations) {\n if (operation.ref.startsWith(\"fabric.\")) continue;\n for (const [key, value] of Object.entries(operation.args)) {\n if (typeof value !== \"string\" && typeof value !== \"number\" && typeof value !== \"boolean\") {\n continue;\n }\n observeValue(operation.ref, key, value);\n }\n }\n }\n }\n const enumCandidates = [...observations.values()]\n .filter((entry) => entry.total >= ENUM_MIN_OBSERVATIONS)\n .filter((entry) => entry.counts.size >= 2 && entry.counts.size <= ENUM_MAX_DISTINCT)\n .map((entry) => {\n const ranked = [...entry.counts.values()].sort(\n (left, right) =>\n right.count - left.count || compareCodeUnits(valueKey(left.value), valueKey(right.value)),\n );\n return { entry, ranked, topShare: roundMetric(ranked[0]!.count / entry.total) };\n })\n .filter((candidate) => candidate.topShare >= ENUM_MIN_TOP_SHARE)\n .filter((candidate) => {\n // Idempotence: skip when the live schema's enum already covers every\n // observed value, so a compiled surface stops re-proposing.\n if (!input.surface) return true;\n const properties = schemaProperties(surfaceByRef.get(candidate.entry.ref));\n const target = properties ? properties[candidate.entry.key] : undefined;\n const existing = enumKeys(target);\n if (!existing) return true;\n return [...candidate.entry.counts.keys()].some((observed) => !existing.has(observed));\n })\n .sort((left, right) =>\n compareCodeUnits(`${left.entry.ref}\\u0000${left.entry.key}`, `${right.entry.ref}\\u0000${right.entry.key}`),\n )\n .slice(0, MAX_PROPOSALS_PER_KIND);\n for (const candidate of enumCandidates) {\n proposals.push({\n kind: \"enum-tighten\",\n ref: candidate.entry.ref,\n key: candidate.entry.key,\n values: candidate.ranked.map((item) => item.value),\n calls: candidate.entry.total,\n distinct: candidate.entry.counts.size,\n topShare: candidate.topShare,\n });\n }\n\n // modal-rename: a repair row whose target is called means the spilled\n // spelling is the model's modal grammar. Compile it into the schema and\n // retire the row instead of paying the map forever.\n const repairRows = [...(input.repairs ?? [])].sort(\n (left, right) =>\n compareCodeUnits(left.ref, right.ref) ||\n compareCodeUnits(left.from, right.from) ||\n compareCodeUnits(left.to, right.to),\n );\n for (const row of repairRows) {\n if (!calledRefs.has(row.ref)) continue;\n if (input.surface) {\n if (row.kind === \"keyAlias\") {\n const properties = schemaProperties(surfaceByRef.get(row.ref));\n if (properties && row.from in properties) continue;\n } else {\n const provider = row.ref.split(\".\")[0] ?? row.ref;\n if (surfaceRefs.has(`${provider}.${row.from}`)) continue;\n }\n }\n proposals.push({\n kind: \"modal-rename\",\n level: row.kind === \"keyAlias\" ? \"key\" : \"action\",\n ref: row.ref,\n from: row.from,\n to: row.to,\n note:\n row.kind === \"keyAlias\"\n ? \"the spilled spelling dominates observed calls; rename the declared key and retire the repair row\"\n : \"the spilled action name dominates observed calls; rename the declared action and retire the repair row\",\n });\n }\n\n // overload-split: one ref carrying two disjoint parameter key-sets is an\n // overloaded action; splitting removes the per-call either/or freedom.\n const overloadRefs = new Set(\n input.report.refs\n .filter((ref) => ref.shapeEntropyBits >= SPLIT_MIN_SHAPE_ENTROPY_BITS)\n .map((ref) => ref.ref),\n );\n if (overloadRefs.size > 0) {\n const keySets = new Map<string, Map<string, { keys: string[]; calls: number }>>();\n for (const sourceTrace of input.traces) {\n for (const operation of sourceTrace.operations) {\n if (!overloadRefs.has(operation.ref)) continue;\n const keys = Object.keys(operation.args).sort();\n const id = keys.join(\"\\u0000\");\n const perRef = keySets.get(operation.ref) ?? new Map<string, { keys: string[]; calls: number }>();\n const cluster = perRef.get(id) ?? { keys, calls: 0 };\n cluster.calls += 1;\n perRef.set(id, cluster);\n keySets.set(operation.ref, perRef);\n }\n }\n let overloadCount = 0;\n for (const [ref, perRef] of [...keySets.entries()].sort(([left], [right]) =>\n compareCodeUnits(left, right),\n )) {\n if (overloadCount >= MAX_PROPOSALS_PER_KIND) break;\n const clusters = [...perRef.values()]\n .filter((cluster) => cluster.calls >= SPLIT_MIN_CLUSTER_CALLS)\n .sort(\n (left, right) =>\n right.calls - left.calls || compareCodeUnits(left.keys.join(\",\"), right.keys.join(\",\")),\n );\n const disjoint: { keys: string[]; calls: number }[] = [];\n for (const cluster of clusters) {\n const keys = new Set(cluster.keys);\n if (disjoint.every((candidate) => candidate.keys.every((key) => !keys.has(key)))) {\n disjoint.push(cluster);\n }\n }\n if (disjoint.length >= 2) {\n overloadCount += 1;\n const report = calledRefs.get(ref);\n proposals.push({\n kind: \"overload-split\",\n ref,\n shapeEntropyBits: report?.shapeEntropyBits ?? 0,\n clusters: disjoint.slice(0, MAX_PROPOSALS_PER_KIND).map((cluster) => ({\n keys: cluster.keys,\n calls: cluster.calls,\n })),\n });\n }\n }\n }\n\n // sequence-fuse: a contiguous multi-ref action sequence that repeats across\n // executions is a composite action (or skill) waiting to be extracted.\n const sequenceCounts = new Map<string, { sequence: string[]; occurrences: number }>();\n for (const sourceTrace of input.traces) {\n const refs = sourceTrace.operations\n .filter((operation) => !operation.ref.startsWith(\"fabric.\"))\n .map((operation) => operation.ref);\n for (\n let length = FUSE_MIN_SEQUENCE_LENGTH;\n length <= Math.min(FUSE_MAX_SEQUENCE_LENGTH, refs.length);\n length++\n ) {\n for (let start = 0; start + length <= refs.length; start++) {\n const sequence = refs.slice(start, start + length);\n if (new Set(sequence).size < 2) continue;\n const id = sequence.join(\"\u2192\");\n const entry = sequenceCounts.get(id) ?? { sequence, occurrences: 0 };\n entry.occurrences += 1;\n sequenceCounts.set(id, entry);\n }\n }\n }\n const fuseCandidates = [...sequenceCounts.values()]\n .filter((entry) => entry.occurrences >= FUSE_MIN_OCCURRENCES)\n .sort(\n (left, right) =>\n right.sequence.length - left.sequence.length ||\n right.occurrences - left.occurrences ||\n compareCodeUnits(left.sequence.join(\"\u2192\"), right.sequence.join(\"\u2192\")),\n );\n const selected: { sequence: string[]; occurrences: number }[] = [];\n for (const candidate of fuseCandidates) {\n if (selected.length >= MAX_PROPOSALS_PER_KIND) break;\n const redundant = selected.some(\n (chosen) =>\n contains(candidate.sequence, chosen.sequence) || contains(chosen.sequence, candidate.sequence),\n );\n if (redundant) continue;\n selected.push(candidate);\n }\n for (const candidate of selected) {\n proposals.push({\n kind: \"sequence-fuse\",\n sequence: candidate.sequence,\n occurrences: candidate.occurrences,\n });\n }\n\n // noise-quarantine: a called ref that fails more than it succeeds, with\n // more than one failure stage, is a candidate to hide from the\n // model-facing catalog. The precondition (more failures than successes)\n // carries the replay-safety argument for retiring it.\n const quarantineCandidates = input.report.refs\n .filter(\n (ref) =>\n ref.calls >= QUARANTINE_MIN_CALLS &&\n ref.failed > ref.succeeded &&\n ref.failureStageEntropyBits >= QUARANTINE_MIN_STAGE_ENTROPY_BITS,\n )\n .filter((ref) => !input.surface || surfaceRefs.has(ref.ref))\n .slice(0, MAX_PROPOSALS_PER_KIND);\n for (const ref of quarantineCandidates) {\n proposals.push({\n kind: \"noise-quarantine\",\n ref: ref.ref,\n calls: ref.calls,\n succeeded: ref.succeeded,\n failed: ref.failed,\n failureStageEntropyBits: ref.failureStageEntropyBits,\n });\n }\n\n return proposals;\n};\n\nconst deepCloneJson = (value: unknown): unknown =>\n value === undefined ? {} : (JSON.parse(JSON.stringify(value)) as unknown);\n\n// Apply the mechanically applicable proposals as a pure surface rewrite.\n// The input surface is never mutated; enum-tighten injects the observed\n// enum, noise-quarantine removes the action, modal-rename renames the\n// declared key or action to the model's modal spelling. Overload-split and\n// sequence-fuse produce review-only proposals and are skipped here.\nexport const applyProposalsToSurface = (\n surface: EntropySurfaceSnapshot,\n proposals: readonly EntropyProposal[],\n): EntropySurfaceSnapshot => {\n const actions: EntropySurfaceAction[] = surface.actions.map((action) => ({\n ref: action.ref,\n inputSchema: deepCloneJson(action.inputSchema),\n }));\n const quarantined = new Set<string>();\n for (const proposal of proposals) {\n if (proposal.kind === \"noise-quarantine\") {\n quarantined.add(proposal.ref);\n continue;\n }\n if (proposal.kind === \"modal-rename\" && proposal.level === \"action\") {\n const provider = proposal.ref.split(\".\")[0] ?? proposal.ref;\n const renamed = `${provider}.${proposal.from}`;\n for (const action of actions) {\n if (action.ref === proposal.ref) action.ref = renamed;\n }\n continue;\n }\n if (proposal.kind === \"enum-tighten\" || (proposal.kind === \"modal-rename\" && proposal.level === \"key\")) {\n const action = actions.find((candidate) => candidate.ref === proposal.ref);\n if (!action || !isPlainRecord(action.inputSchema)) continue;\n const schema = action.inputSchema;\n const properties = schemaProperties(schema);\n if (!properties) continue;\n if (proposal.kind === \"enum-tighten\") {\n if (!isPlainRecord(properties[proposal.key])) continue;\n properties[proposal.key] = {\n ...(properties[proposal.key] as Record<string, unknown>),\n enum: [...proposal.values],\n };\n continue;\n }\n if (!(proposal.to in properties) || proposal.from in properties) continue;\n properties[proposal.from] = properties[proposal.to]!;\n delete properties[proposal.to];\n if (Array.isArray(schema.required)) {\n schema.required = schema.required.map((key) => (key === proposal.to ? proposal.from : key));\n }\n }\n }\n const survivors = actions\n .filter((action) => !quarantined.has(action.ref))\n .sort((left, right) => compareCodeUnits(left.ref, right.ref));\n return { version: 1, actions: survivors };\n};\n\n// The ratchet: a compiled surface must not increase the measured score and\n// must preserve every successful call. Monotonicity is measured, never\n// argued.\nexport const evaluateGate = (before: EntropyReport, after: EntropyReport): EntropyGateResult => {\n const reasons: string[] = [];\n if (after.score > before.score) {\n reasons.push(`score increased ${before.score} \u2192 ${after.score}`);\n }\n if (after.totals.succeeded < before.totals.succeeded) {\n reasons.push(\n `successful calls dropped ${before.totals.succeeded} \u2192 ${after.totals.succeeded}`,\n );\n }\n return {\n passed: reasons.length === 0,\n beforeScore: before.score,\n afterScore: after.score,\n delta: roundMetric(after.score - before.score),\n reasons,\n };\n};\n", "// Live surface snapshots for the entropy meter. Discovery is Fabric's\n// authorization-free read path (read-only, no approval budget, no side\n// effects): providers answer `list` from static descriptors, in-memory\n// catalogs, or the MCP descriptor cache, so a minimal synthetic invocation\n// context is safe for command-time surface listing.\n\nimport type { ExtensionContext } from \"@earendil-works/pi-coding-agent\";\nimport type { FabricInvocationContext } from \"../protocol.js\";\nimport { stableJsonHash } from \"../core/stable-hash.js\";\nimport { compareCodeUnits, roundMetric, staticFreedomFromSchema } from \"./fingerprint.js\";\nimport type { EntropySurfaceSnapshot } from \"./types.js\";\n\nconst SURFACE_LIST_LIMIT = 1_000;\n\nexport interface EntropySurfaceListAction {\n ref: string;\n inputSchema: unknown;\n}\n\nexport interface EntropySurfaceRegistry {\n list(\n request: { limit?: number },\n context: FabricInvocationContext,\n ): Promise<readonly EntropySurfaceListAction[]>;\n}\n\nconst surfaceInvocationContext = (input: {\n extensionContext: ExtensionContext;\n cwd: string;\n}): FabricInvocationContext => ({\n cwd: input.cwd,\n signal: undefined,\n parentToolCallId: \"fabric-entropy-surface\",\n nestedToolCallId: \"fabric-entropy-surface\",\n extensionContext: input.extensionContext,\n update: () => {},\n});\n\n// Snapshot the live action surface (ref + input schema per action) through\n// the registry's discovery path. Sorted by ref so the snapshot hashes and\n// diffs deterministically.\nexport const liveSurfaceSnapshot = async (input: {\n registry: EntropySurfaceRegistry;\n extensionContext: ExtensionContext;\n cwd: string;\n}): Promise<EntropySurfaceSnapshot> => {\n const actions = await input.registry.list(\n { limit: SURFACE_LIST_LIMIT },\n surfaceInvocationContext(input),\n );\n return {\n version: 1,\n actions: actions\n .map((action) => ({ ref: action.ref, inputSchema: action.inputSchema }))\n .sort((left, right) => compareCodeUnits(left.ref, right.ref)),\n };\n};\n\nexport const entropySurfaceHash = (surface: EntropySurfaceSnapshot): string =>\n stableJsonHash(surface);\n\nexport interface EntropySurfaceFreedomEntry {\n ref: string;\n freedom: number;\n}\n\nexport interface EntropySurfaceFreedomReport {\n actions: EntropySurfaceFreedomEntry[];\n total: number;\n mean: number;\n}\n\n// Static freedom of a whole surface: per-action scores sorted worst-first,\n// with the total and mean the ratchet tracks. Computable with no corpus at\n// all, which is what lets a candidate surface be scored before any session\n// runs against it.\nexport const surfaceFreedomReport = (\n surface: EntropySurfaceSnapshot,\n): EntropySurfaceFreedomReport => {\n const actions = surface.actions\n .map((action) => ({ ref: action.ref, freedom: staticFreedomFromSchema(action.inputSchema) }))\n .sort((left, right) => right.freedom - left.freedom || compareCodeUnits(left.ref, right.ref));\n const total = roundMetric(actions.reduce((sum, entry) => sum + entry.freedom, 0));\n return {\n actions,\n total,\n mean: actions.length > 0 ? roundMetric(total / actions.length) : 0,\n };\n};\n", "// The autonomous compile step: measure \u2192 propose \u2192 apply the mechanical\n// subset \u2192 re-measure \u2192 gate. The gate proves two things on the retained\n// corpus: the score never increases, and every successful call to a ref\n// the compile touched still parses against the candidate surface.\n// Overload-split and sequence-fuse author new composite definitions, and a\n// pure modal rename drops the declared key that every successful call\n// recorded, so all three stay surfaced for review and never auto-apply.\n\nimport { stableJsonHash } from \"../core/stable-hash.js\";\nimport { measureEntropy } from \"./meter.js\";\nimport { applyProposalsToSurface, evaluateGate, proposeEntropyReductions } from \"./passes.js\";\nimport {\n COMPILED_SURFACE_VERSION,\n MAX_COMPILED_SURFACE_PROPOSALS,\n applyCompiledSurface,\n replaySuccessfulCalls,\n schemaDigest,\n type CompiledSurfaceAppliedProposal,\n type CompiledSurfaceFile,\n} from \"./compiled-surface.js\";\nimport { entropySurfaceHash } from \"./surface.js\";\nimport { ENTROPY_METRIC_VERSION } from \"./types.js\";\nimport type {\n EntropyGateResult,\n EntropyProposal,\n EntropyRepairRowInput,\n EntropyReport,\n EntropySurfaceSnapshot,\n EntropyTraceInput,\n EntropyValueObservation,\n} from \"./types.js\";\n\n// The kinds the autonomous loop may apply. Every other proposal carries its\n// evidence to the surfaced review queue instead.\nexport const AUTO_APPLY_PROPOSAL_KINDS: readonly string[] = [\"enum-tighten\", \"noise-quarantine\"];\n\nexport interface CompileEntropyInput {\n traces: readonly EntropyTraceInput[];\n surface: EntropySurfaceSnapshot;\n repairs?: readonly EntropyRepairRowInput[];\n valueObservations?: readonly EntropyValueObservation[];\n artifact?: CompiledSurfaceFile;\n catalogDigest?: string;\n}\n\nexport type CompileEntropyStatus = \"compiled\" | \"converged\" | \"rejected\";\n\nexport interface CompileEntropyOutcome {\n status: CompileEntropyStatus;\n /** The maintained artifact: new when compiled, the input artifact otherwise. */\n artifact?: CompiledSurfaceFile;\n report: EntropyReport;\n after?: EntropyReport;\n proposals: EntropyProposal[];\n gate?: EntropyGateResult;\n}\n\nconst proposalDetail = (proposal: EntropyProposal): { ref: string; detail: string } => {\n if (proposal.kind === \"enum-tighten\") {\n return { ref: proposal.ref, detail: `${proposal.key}: ${proposal.values.length} observed values` };\n }\n if (proposal.kind === \"noise-quarantine\") {\n return { ref: proposal.ref, detail: `${proposal.failed} failed vs ${proposal.succeeded} succeeded` };\n }\n return { ref: \"n/a\", detail: \"review-only\" };\n};\n\n// Refs the compile touched: tightened schemas and quarantined actions. The\n// replay gate scopes to this set; untouched refs keep their schema by\n// identity, so projection artifacts elsewhere cannot poison a compile.\nconst touchedRefs = (before: EntropySurfaceSnapshot, after: EntropySurfaceSnapshot): Set<string> => {\n const beforeByRef = new Map(before.actions.map((action) => [action.ref, action.inputSchema]));\n const touched = new Set<string>();\n for (const action of after.actions) {\n if (stableJsonHash(beforeByRef.get(action.ref)) !== stableJsonHash(action.inputSchema)) {\n touched.add(action.ref);\n }\n }\n for (const ref of beforeByRef.keys()) {\n if (!after.actions.some((action) => action.ref === ref)) touched.add(ref);\n }\n return touched;\n};\n\n// Build the maintained artifact from the candidate surface against the live\n// surface: overlay entries carry the live base digest, quarantined actions\n// carry theirs, and the applied ledger accumulates across compiles.\nconst artifactFromCandidate = (\n live: EntropySurfaceSnapshot,\n candidate: EntropySurfaceSnapshot,\n proposals: readonly EntropyProposal[],\n gate: { passed: boolean; beforeScore: number; afterScore: number; reasons: string[] },\n evidenceDigest: string,\n previous?: CompiledSurfaceFile,\n): CompiledSurfaceFile => {\n const liveByRef = new Map(live.actions.map((action) => [action.ref, action.inputSchema]));\n const actions = candidate.actions\n .filter(\n (action) => stableJsonHash(action.inputSchema) !== stableJsonHash(liveByRef.get(action.ref)),\n )\n .map((action) => ({\n ref: action.ref,\n inputSchema: action.inputSchema as Record<string, unknown>,\n baseSchemaDigest: schemaDigest(liveByRef.get(action.ref)),\n }));\n const candidateRefs = new Set(candidate.actions.map((action) => action.ref));\n const quarantined = live.actions\n .filter((action) => !candidateRefs.has(action.ref))\n .map((action) => ({ ref: action.ref, baseSchemaDigest: schemaDigest(action.inputSchema) }));\n const applied: CompiledSurfaceAppliedProposal[] = [...(previous?.applied ?? [])];\n const seen = new Set(applied.map((entry) => `${entry.kind}:${entry.ref}:${entry.detail}`));\n for (const proposal of proposals) {\n const { ref, detail } = proposalDetail(proposal);\n const identity = `${proposal.kind}:${ref}:${detail}`;\n if (seen.has(identity)) continue;\n seen.add(identity);\n applied.push({ kind: proposal.kind, ref, detail });\n }\n return {\n version: COMPILED_SURFACE_VERSION,\n metricVersion: ENTROPY_METRIC_VERSION,\n actions,\n quarantined,\n applied: applied.slice(0, MAX_COMPILED_SURFACE_PROPOSALS),\n gate,\n evidenceDigest,\n };\n};\n\nexport const compileEntropySurface = (input: CompileEntropyInput): CompileEntropyOutcome => {\n const effective = applyCompiledSurface(input.surface, input.artifact);\n const report = measureEntropy({\n traces: input.traces,\n surface: effective,\n ...(input.repairs ? { repairs: input.repairs } : {}),\n catalogDigest: input.catalogDigest ?? entropySurfaceHash(effective),\n });\n const proposals = proposeEntropyReductions({\n report,\n traces: input.traces,\n surface: effective,\n ...(input.repairs ? { repairs: input.repairs } : {}),\n ...(input.valueObservations ? { valueObservations: input.valueObservations } : {}),\n });\n const auto = proposals.filter((proposal) =>\n (AUTO_APPLY_PROPOSAL_KINDS as readonly string[]).includes(proposal.kind),\n );\n if (auto.length === 0) {\n return {\n status: \"converged\",\n ...(input.artifact ? { artifact: input.artifact } : {}),\n report,\n proposals,\n };\n }\n const candidate = applyProposalsToSurface(effective, auto);\n const after = measureEntropy({\n traces: input.traces,\n surface: candidate,\n ...(input.repairs ? { repairs: input.repairs } : {}),\n catalogDigest: entropySurfaceHash(candidate),\n });\n const scoreGate = evaluateGate(report, after);\n const violations = replaySuccessfulCalls(\n candidate,\n input.traces,\n touchedRefs(effective, candidate),\n );\n const reasons = [\n ...scoreGate.reasons,\n ...violations.map((violation) => `${violation.ref}: ${violation.reason}`),\n ];\n const gate: EntropyGateResult = {\n passed: scoreGate.passed && violations.length === 0,\n beforeScore: report.score,\n afterScore: after.score,\n delta: scoreGate.delta,\n reasons: scoreGate.passed && violations.length === 0 ? [] : reasons,\n };\n if (gate.passed) {\n const evidenceDigest = stableJsonHash({\n traces: input.traces.length,\n operations: report.totals.operations,\n succeeded: report.totals.succeeded,\n failed: report.totals.failed,\n surface: entropySurfaceHash(effective),\n repairs: input.repairs?.length ?? 0,\n });\n return {\n status: \"compiled\",\n artifact: artifactFromCandidate(\n input.surface,\n candidate,\n auto,\n { passed: true, beforeScore: report.score, afterScore: after.score, reasons: [] },\n evidenceDigest,\n input.artifact,\n ),\n report,\n after,\n proposals,\n gate,\n };\n }\n return {\n status: \"rejected\",\n ...(input.artifact ? { artifact: input.artifact } : {}),\n report,\n after,\n proposals,\n gate,\n };\n};", "// Corpus shaping for the entropy meter: turn persisted Fabric execution\n// traces and session JSONL into meter traces, and normalize catalog repair\n// rows. Only guarded, typed records are consumed \u2014 never rendered prose.\n\nimport {\n FABRIC_EXECUTION_TRACE_KIND,\n readFabricExecutionTraceV1,\n type FabricExecutionTraceV1,\n} from \"../audit/trace.js\";\nimport { stableJsonHash } from \"../core/stable-hash.js\";\nimport type { CatalogRepair } from \"../repairs/types.js\";\nimport type {\n EntropyReport,\n EntropyRepairRowInput,\n EntropyTraceInput,\n EntropyValueObservation,\n} from \"./types.js\";\n\nconst DEFAULT_TASK_KEY = \"(none)\";\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n// One Fabric execution trace becomes one meter trace. The first persisted\n// workflow phase is the deterministic task key for flow entropy.\nexport const entropyTraceFromFabricTrace = (\n trace: FabricExecutionTraceV1,\n model?: string,\n): EntropyTraceInput => ({\n operations: trace.operations.map((operation) => ({\n ref: operation.ref,\n args: operation.args,\n outcome: operation.outcome,\n ...(operation.failureStage !== undefined ? { failureStage: operation.failureStage } : {}),\n })),\n taskKey: trace.phases[0] ?? DEFAULT_TASK_KEY,\n ...(model ? { model } : {}),\n});\n\nconst MODEL_CHANGE_FILTER = '\"type\":\"model_change\"';\nconst ASSISTANT_FILTER = '\"role\":\"assistant\"';\n\n// Model identity for one parsed session record: `model_change` entries name\n// the provider/model from that point on, and assistant messages carry the\n// provider/model that produced the turn. A toolResult's producing model is\n// the one active at its line, so the scan tracks it in order.\nconst modelFromRecord = (parsed: Record<string, unknown>): string | undefined => {\n if (parsed.type === \"model_change\") {\n const provider = typeof parsed.provider === \"string\" ? parsed.provider : \"\";\n const modelId = typeof parsed.modelId === \"string\" ? parsed.modelId : \"\";\n return provider && modelId ? `${provider}/${modelId}` : undefined;\n }\n const message = isRecord(parsed.message) ? parsed.message : undefined;\n if (!message || message.role !== \"assistant\") return undefined;\n const provider = typeof message.provider === \"string\" ? message.provider : \"\";\n const modelId = typeof message.model === \"string\" ? message.model : \"\";\n return provider && modelId ? `${provider}/${modelId}` : undefined;\n};\n\ninterface ScannedSessionRecord {\n details: Record<string, unknown>;\n model?: string;\n}\n\n// Cheap pre-filters keep on-demand multi-session scans fast on large logs:\n// only lines that can carry a trace envelope or a model identity get parsed.\n// The substring gates are lossy by design; the guarded parse decides.\nconst sessionRecords = (lines: readonly string[]): ScannedSessionRecord[] => {\n const records: ScannedSessionRecord[] = [];\n let currentModel: string | undefined;\n for (const line of lines) {\n const trimmed = line.trim();\n if (trimmed === \"\") continue;\n const traceLine = trimmed.includes(FABRIC_EXECUTION_TRACE_KIND);\n const modelLine =\n !traceLine &&\n (trimmed.includes(MODEL_CHANGE_FILTER) || trimmed.includes(ASSISTANT_FILTER));\n if (!traceLine && !modelLine) continue;\n let parsed: unknown;\n try {\n parsed = JSON.parse(trimmed);\n } catch {\n continue;\n }\n if (!isRecord(parsed)) continue;\n if (modelLine) {\n const model = modelFromRecord(parsed);\n if (model) currentModel = model;\n continue;\n }\n const details = isRecord(parsed.details)\n ? parsed.details\n : isRecord(parsed.message) && isRecord(parsed.message.details)\n ? parsed.message.details\n : undefined;\n if (isRecord(details)) {\n records.push({ details, ...(currentModel ? { model: currentModel } : {}) });\n }\n }\n return records;\n};\n\n// Extract meter traces from Pi session JSONL lines. Malformed lines, non-trace\n// entries, and envelopes that fail the trace guard are skipped without\n// throwing; only typed, guarded trace V1 envelopes count.\nexport const entropyTracesFromSessionJsonl = (lines: readonly string[]): EntropyTraceInput[] => {\n const traces: EntropyTraceInput[] = [];\n for (const record of sessionRecords(lines)) {\n const trace = readFabricExecutionTraceV1(record.details.trace);\n if (trace) traces.push(entropyTraceFromFabricTrace(trace, record.model));\n }\n return traces;\n};\n\n// Verbatim audit arguments are the authoritative value corpus for\n// enum-tighten: trace V1 projects values away per ref (external and MCP calls\n// keep none), while persisted audits carry every argument the call used. The\n// observations stay local to the session record, exactly like the audits.\nexport const entropyValueObservationsFromSessionJsonl = (\n lines: readonly string[],\n): EntropyValueObservation[] => {\n const observations: EntropyValueObservation[] = [];\n for (const record of sessionRecords(lines)) {\n const details = record.details;\n if (!Array.isArray(details.audits)) continue;\n for (const audit of details.audits) {\n if (!isRecord(audit)) continue;\n const ref = typeof audit.ref === \"string\" ? audit.ref : undefined;\n const args = isRecord(audit.args) ? audit.args : undefined;\n if (!ref || !args) continue;\n for (const [key, value] of Object.entries(args)) {\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n observations.push({ ref, key, value });\n }\n }\n }\n }\n return observations;\n};\n\n// Normalize catalog repair rows for the meter. `ref` is the target the row\n// repairs toward: the declared key's action for key aliases, or\n// provider.declared-action for action aliases.\nexport const entropyRepairRows = (repairs: readonly CatalogRepair[]): EntropyRepairRowInput[] =>\n repairs.map((repair) =>\n repair.kind === \"keyAlias\"\n ? { kind: \"keyAlias\", ref: repair.ref, from: repair.from, to: repair.to }\n : {\n kind: \"actionAlias\",\n ref: `${repair.provider}.${repair.to}`,\n from: repair.from,\n to: repair.to,\n },\n );\n\n// Stable hash of a report \u2014 the determinism check compares these.\nexport const entropyReportHash = (report: EntropyReport): string => stableJsonHash(report);\n", "// On-demand session measurement. Session JSONL is the source of truth, so\n// entropy is never recorded: the newest project sessions are read live,\n// measured against the current surface, and the trend is the per-session\n// slope. The repair table and the compiled entropy surface are the only\n// durable derived artifacts, because they are the only ones that change\n// runtime behavior.\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { sessionDirForCwd } from \"../memory/discovery.js\";\nimport {\n entropyTracesFromSessionJsonl,\n entropyValueObservationsFromSessionJsonl,\n} from \"./corpus.js\";\nimport { measureEntropy } from \"./meter.js\";\nimport { compareCodeUnits, trendFromScores } from \"./fingerprint.js\";\nimport type {\n EntropyModelReport,\n EntropyReport,\n EntropySurfaceSnapshot,\n EntropyTraceInput,\n EntropyTrend,\n EntropyValueObservation,\n} from \"./types.js\";\n\nconst DEFAULT_SESSION_WINDOW = 8;\n\nexport interface SessionCorpusEntry {\n file: string;\n operations: number;\n report: EntropyReport;\n}\n\n// Per-model trend across the session window: the attribution that names\n// which model's behavior moved, with the surface share staying global.\nexport interface SessionModelTrend {\n model: string;\n sessions: number;\n latestBehavioralScore: number;\n slopePerSession: number;\n latestRejectionsPer1k: number;\n}\n\nexport interface SessionCorpusResult {\n files: readonly string[];\n sessions: SessionCorpusEntry[];\n latest?: EntropyReport;\n trend: EntropyTrend;\n models: SessionModelTrend[];\n}\n\n// Newest-first session JSONL files for one project cwd, bounded by `limit`.\n// Mtime ties break by path so the ordering is stable.\nexport const projectSessionFiles = (\n agentDir: string,\n cwd: string,\n limit = DEFAULT_SESSION_WINDOW,\n): string[] => {\n const dir = sessionDirForCwd(cwd, agentDir);\n let entries: fs.Dirent[] = [];\n try {\n entries = fs.readdirSync(dir, { withFileTypes: true });\n } catch {\n return [];\n }\n const stamped = entries\n .filter((entry) => entry.isFile() && entry.name.endsWith(\".jsonl\"))\n .map((entry) => {\n const file = path.join(dir, entry.name);\n let mtime = 0;\n try {\n mtime = fs.statSync(file).mtimeMs;\n } catch {\n mtime = 0;\n }\n return { file, mtime };\n });\n stamped.sort(\n (left, right) =>\n right.mtime - left.mtime || (left.file < right.file ? -1 : left.file > right.file ? 1 : 0),\n );\n return stamped.slice(0, Math.max(1, limit)).map((entry) => entry.file);\n};\n\n// Measure each session file independently against the same surface; sessions\n// without fabric_exec traces contribute nothing. `files` must be newest\n// first; the trend runs oldest to newest.\nexport const measureSessionCorpus = (input: {\n files: readonly string[];\n surface?: EntropySurfaceSnapshot;\n catalogDigest?: string;\n}): SessionCorpusResult => {\n const sessions: SessionCorpusEntry[] = [];\n for (const file of input.files) {\n let text: string;\n try {\n text = fs.readFileSync(file, \"utf8\");\n } catch {\n continue;\n }\n const traces = entropyTracesFromSessionJsonl(text.split(\"\\n\"));\n if (traces.length === 0) continue;\n const report = measureEntropy({\n traces,\n ...(input.surface ? { surface: input.surface } : {}),\n ...(input.catalogDigest !== undefined ? { catalogDigest: input.catalogDigest } : {}),\n });\n if (report.totals.operations === 0) continue;\n sessions.push({ file, operations: report.totals.operations, report });\n }\n const chronological = [...sessions].reverse();\n const modelScores = new Map<string, { behavioral: number[]; latest: EntropyModelReport }>();\n for (const session of chronological) {\n for (const model of session.report.byModel) {\n const entry = modelScores.get(model.model) ?? { behavioral: [], latest: model };\n entry.behavioral.push(model.behavioralScore);\n entry.latest = model;\n modelScores.set(model.model, entry);\n }\n }\n const models: SessionModelTrend[] = [...modelScores.entries()]\n .sort(([left], [right]) => compareCodeUnits(left, right))\n .map(([model, entry]) => ({\n model,\n sessions: entry.behavioral.length,\n latestBehavioralScore: entry.latest.behavioralScore,\n slopePerSession: trendFromScores(entry.behavioral).slopePerStep,\n latestRejectionsPer1k: entry.latest.invocationRejectionsPer1k,\n }));\n return {\n files: input.files,\n sessions,\n ...(sessions.length > 0 ? { latest: sessions[0]!.report } : {}),\n trend: trendFromScores(chronological.map((session) => session.report.score)),\n models,\n };\n};\n\n// One read per file yields both meter traces and the verbatim audit value\n// corpus, so the autonomous compile and the command share a single window\n// scan.\nexport interface SessionWindowEvidence {\n traces: EntropyTraceInput[];\n valueObservations: EntropyValueObservation[];\n}\n\nexport const sessionWindowEvidence = (\n files: readonly string[],\n): SessionWindowEvidence => {\n const traces: EntropyTraceInput[] = [];\n const valueObservations: EntropyValueObservation[] = [];\n for (const file of files) {\n let text: string;\n try {\n text = fs.readFileSync(file, \"utf8\");\n } catch {\n continue;\n }\n const lines = text.split(\"\\n\");\n traces.push(...entropyTracesFromSessionJsonl(lines));\n valueObservations.push(...entropyValueObservationsFromSessionJsonl(lines));\n }\n return { traces, valueObservations };\n};\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;AAQO,IAAM,yBAAyB;AAI/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;;;ACjB7F,IAAM,qBAAqB;AAC3B,IAAM,sBAAsB;AAE5B,IAAM,uBAAuB;AAE7B,IAAM,gBAAgB,CAAC,UACrB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAK9D,IAAM,cAAc,CAAC,UAA0B;AACpD,QAAM,UAAU,KAAK,MAAM,QAAQ,GAAG,IAAI;AAC1C,SAAO,YAAY,IAAI,IAAI;AAC7B;AAIO,IAAM,mBAAmB,CAAC,MAAc,UAC7C,OAAO,QAAQ,KAAK,OAAO,QAAQ,IAAI;AAEzC,IAAM,UAAU,CAAC,OAAgB,UAA0B;AACzD,MAAI,UAAU,KAAM,QAAO;AAC3B,MAAI,MAAM,QAAQ,KAAK,EAAG,QAAO;AACjC,UAAQ,OAAO,OAAO;AAAA,IACpB,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK,UAAU;AACb,UAAI,SAAS,oBAAqB,QAAO;AACzC,UAAI;AACF,cAAM,SAAS;AACf,cAAM,OAAO,OAAO,KAAK,MAAM,EAAE,KAAK;AACtC,cAAM,OAAO,KACV,MAAM,GAAG,kBAAkB,EAC3B,IAAI,CAAC,QAAQ,GAAG,GAAG,IAAI,QAAQ,OAAO,GAAG,GAAG,QAAQ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AA,IACpC,iBAAiB,gBAAgB,MAAM,UAAU,EAAE;AAAA,IACnD,uBAAuB,MAAM,OAAO;AAAA,EACtC,EAAE;AACJ,SAAO;AAAA,IACL,OAAO,MAAM;AAAA,IACb;AAAA,IACA,GAAI,SAAS,SAAS,IAAI,EAAE,QAAQ,SAAS,CAAC,EAAG,OAAO,IAAI,CAAC;AAAA,IAC7D,OAAO,gBAAgB,cAAc,IAAI,CAAC,YAAY,QAAQ,OAAO,KAAK,CAAC;AAAA,IAC3E;AAAA,EACF;AACF;AAUO,IAAM,wBAAwB,CACnC,UAC0B;AAC1B,QAAM,SAA8B,CAAC;AACrC,QAAM,oBAA+C,CAAC;AACtD,aAAW,QAAQ,OAAO;AACxB,QAAI;AACJ,QAAI;AACF,aAAO,GAAG,aAAa,MAAM,MAAM;AAAA,IACrC,QAAQ;AACN;AAAA,IACF;AACA,UAAM,QAAQ,KAAK,MAAM,IAAI;AAC7B,WAAO,KAAK,GAAG,8BAA8B,KAAK,CAAC;AACnD,sBAAkB,KAAK,GAAG,yCAAyC,KAAK,CAAC;AAAA,EAC3E;AACA,SAAO,EAAE,QAAQ,kBAAkB;AACrC;",
|
|
4
|
+
"sourcesContent": ["// Deterministic tool-entropy measurement for the Fabric tool surface.\n//\n// Entropy here is operational, not psychological: it counts the bits of\n// corrective freedom a surface leaves open, measured only from artifacts\n// Fabric already records in typed form (trace V1 operations, the repair\n// table, live JSON schemas). No model judges anything; the same inputs and\n// the same metric version always produce the same report.\n\nexport const ENTROPY_METRIC_VERSION = 2 as const;\n\n// Fixed weights per metric version. Changing any weight bumps\n// ENTROPY_METRIC_VERSION so trend lines never mix formulas.\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}\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 catalog-repair row: `ref` is the target the row 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.\nexport interface EntropyValueObservation {\n ref: string;\n key: string;\n value: string | number | boolean;\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 shapeEntropyBits: number;\n failureStageEntropyBits: number;\n churnRate: number;\n lexiconRows: number;\n staticFreedom: number;\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: each stamped trace measures against the\n// same surface, so the breakdown names which model exercised the freedom.\nexport interface EntropyModelReport {\n model: string;\n operations: number;\n actionOperations: number;\n succeeded: number;\n invocationRejections: number;\n invocationRejectionsPer1k: number;\n behavioralScore: number;\n}\n\nexport interface EntropyReport {\n metricVersion: typeof ENTROPY_METRIC_VERSION;\n catalogDigest: string;\n totals: EntropyTotals;\n shapeEntropyBits: number;\n failureStageEntropyBits: number;\n churnRate: number;\n navigationRatio: number;\n flowEntropyBits: number;\n lexiconRows: number;\n staticFreedom: number;\n /** Surface share of the score: static freedom of the refs the corpus used. */\n staticScore: number;\n /** Everything models exercised: wobble, churn, rejections, navigation, flow, lexicon. */\n behavioralScore: number;\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: \"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: \"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 | {\n kind: \"modal-rename\";\n level: \"key\" | \"action\";\n ref: string;\n from: string;\n to: string;\n note: string;\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", "// Deterministic fingerprints for the entropy meter: canonical call-shape\n// signatures, signature distance (retry churn), Shannon entropy in bits, and\n// the static freedom score of a JSON Schema. Everything here is a pure\n// function of its inputs; the same value always yields the same fingerprint.\n\nimport type { EntropyTrend } from \"./types.js\";\n\nconst SIGNATURE_MAX_KEYS = 32;\nconst SIGNATURE_MAX_DEPTH = 3;\n// Enum cardinality whose freedom saturates at 1.0 (log2 of 64 values).\nconst ENUM_SATURATION_BITS = 6;\n\nconst isPlainRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n// Fixed rounding for every reported metric value. Same inputs, same floats,\n// same six decimal places \u2014 report JSON is byte-stable. Negative zero\n// collapses to zero so single-class entropies compare equal to zero.\nexport const roundMetric = (value: number): number => {\n const rounded = Math.round(value * 1e6) / 1e6;\n return rounded === 0 ? 0 : rounded;\n};\n\n// Code-unit string comparison: locale-independent, so ordering never varies\n// with the host's ICU data.\nexport const compareCodeUnits = (left: string, right: string): number =>\n left < right ? -1 : left > right ? 1 : 0;\n\nconst typeTag = (value: unknown, depth: number): string => {\n if (value === null) return \"null\";\n if (Array.isArray(value)) return \"arr\";\n switch (typeof value) {\n case \"string\":\n return \"str\";\n case \"number\":\n return \"num\";\n case \"boolean\":\n return \"bool\";\n case \"object\": {\n if (depth >= SIGNATURE_MAX_DEPTH) return \"obj\";\n try {\n const record = value as Record<string, unknown>;\n const keys = Object.keys(record).sort();\n const head = keys\n .slice(0, SIGNATURE_MAX_KEYS)\n .map((key) => `${key}:${typeTag(record[key], depth + 1)}`);\n if (keys.length > SIGNATURE_MAX_KEYS) {\n head.push(`\u2026+${keys.length - SIGNATURE_MAX_KEYS}`);\n }\n return `{${head.join(\",\")}}`;\n } catch {\n return \"obj\";\n }\n }\n default:\n return \"other\";\n }\n};\n\n// Canonical argument-shape signature: sorted parameter names with a bounded\n// value-type tag each. Key order and value contents never matter \u2014 only the\n// shape the model chose.\nexport const shapeSignature = (args: Record<string, unknown>): string => {\n const keys = Object.keys(args).sort();\n const head = keys\n .slice(0, SIGNATURE_MAX_KEYS)\n .map((key) => `${key}:${typeTag(args[key], 1)}`);\n if (keys.length > SIGNATURE_MAX_KEYS) {\n head.push(`\u2026+${keys.length - SIGNATURE_MAX_KEYS}`);\n }\n return `(${head.join(\",\")})`;\n};\n\n// Normalized Levenshtein distance between two signatures, in [0, 1]. Retry\n// churn is the distance between a failed call's shape and the next attempt's.\nexport const signatureDistance = (left: string, right: string): number => {\n if (left === right) return 0;\n const bound = Math.max(left.length, right.length);\n if (bound === 0) return 0;\n let previous: number[] = [];\n for (let index = 0; index <= right.length; index++) {\n previous.push(index);\n }\n for (let index = 1; index <= left.length; index++) {\n const current: number[] = [index];\n for (let inner = 1; inner <= right.length; inner++) {\n const substitution = previous[inner - 1]! + (left[index - 1] === right[inner - 1] ? 0 : 1);\n const insertion = current[inner - 1]! + 1;\n const deletion = previous[inner]! + 1;\n current.push(Math.min(substitution, insertion, deletion));\n }\n previous = current;\n }\n return roundMetric(previous[right.length]! / bound);\n};\n\n// Shannon entropy in bits over a count distribution, rounded to 1e-6.\n// A single class is zero bits; a uniform split over k classes is log2(k).\nexport const shannonEntropyBits = (counts: readonly number[]): number => {\n const total = counts.reduce((sum, value) => sum + value, 0);\n if (total <= 0) return 0;\n let bits = 0;\n for (const count of counts) {\n if (count <= 0) continue;\n const probability = count / total;\n bits += probability * Math.log2(probability);\n }\n return roundMetric(-bits);\n};\n\nconst schemaFreedom = (schema: unknown, depth: number): number => {\n if (depth > SIGNATURE_MAX_DEPTH) return 0.5;\n if (!isPlainRecord(schema)) return 0.5;\n const union = Array.isArray(schema.anyOf)\n ? schema.anyOf\n : Array.isArray(schema.oneOf)\n ? schema.oneOf\n : undefined;\n if (union) {\n const scores = union.map((branch) => schemaFreedom(branch, depth + 1));\n const widest = scores.length > 0 ? Math.max(...scores) : 0;\n return roundMetric(widest + 0.1 * Math.max(0, union.length - 1));\n }\n if (Array.isArray(schema.enum)) {\n return roundMetric(\n Math.min(1, Math.log2(Math.max(1, schema.enum.length)) / ENUM_SATURATION_BITS),\n );\n }\n if (\"const\" in schema) return 0;\n const type = schema.type;\n if (typeof type !== \"string\") return 0.75;\n if (type === \"boolean\") return 0.1;\n if (type === \"number\" || type === \"integer\") return 0.5;\n if (type === \"string\") return 1;\n if (type === \"array\") return roundMetric(0.5 + 0.5 * schemaFreedom(schema.items, depth + 1));\n if (type === \"object\") {\n const properties = schema.properties;\n if (!isPlainRecord(properties)) return 1;\n const keys = Object.keys(properties).sort();\n if (keys.length === 0) return 1;\n const required = Array.isArray(schema.required)\n ? schema.required.filter((entry): entry is string => typeof entry === \"string\")\n : [];\n let score = 0;\n for (const key of keys) {\n score += schemaFreedom(properties[key], depth + 1);\n if (!required.includes(key)) score += 0.25;\n }\n if (schema.additionalProperties !== false) score += 0.5;\n return roundMetric(score);\n }\n return 0.75;\n};\n\n// Static freedom of one action's input schema: free strings dominate, enums\n// shrink with log2 cardinality, literals cost nothing, and optional or\n// open-ended parameters add tax. Computable with an empty corpus, which is\n// what lets the compiler score candidate surfaces before deployment.\nexport const staticFreedomFromSchema = (schema: unknown): number => schemaFreedom(schema, 0);\n\n// Least-squares slope of a score sequence, oldest to newest. The on-demand\n// session trend feeds this per-session scores; a flat or negative slope is\n// the ratchet holding.\nexport const trendFromScores = (scores: readonly number[]): EntropyTrend => {\n const count = scores.length;\n const first = count > 0 ? scores[0] : undefined;\n const last = count > 0 ? scores[count - 1] : undefined;\n let slope = 0;\n if (count >= 2) {\n const meanX = (count - 1) / 2;\n const meanY = scores.reduce((sum, value) => sum + value, 0) / count;\n let numerator = 0;\n let denominator = 0;\n for (let index = 0; index < count; index++) {\n numerator += (index - meanX) * (scores[index]! - meanY);\n denominator += (index - meanX) ** 2;\n }\n slope = denominator > 0 ? numerator / denominator : 0;\n }\n return {\n count,\n ...(first !== undefined ? { first: roundMetric(first) } : {}),\n ...(last !== undefined ? { last: roundMetric(last) } : {}),\n slopePerStep: roundMetric(slope),\n };\n};\n", "import {\n ENTROPY_INVOCATION_STAGES,\n ENTROPY_METRIC_VERSION,\n ENTROPY_WEIGHTS,\n type EntropyModelReport,\n type EntropyRefReport,\n type EntropyRepairRowInput,\n type EntropyReport,\n type EntropyShapeSignature,\n type EntropySurfaceSnapshot,\n type EntropyTotals,\n type EntropyTraceInput,\n} from \"./types.js\";\nimport {\n compareCodeUnits,\n roundMetric,\n shannonEntropyBits,\n shapeSignature,\n signatureDistance,\n staticFreedomFromSchema,\n} from \"./fingerprint.js\";\n\n// The meter is a pure function of its inputs: typed trace operations, an\n// optional surface snapshot, and the normalized repair table. It reads no\n// clocks, no randomness, and no prose \u2014 only the residues of non-canonical\n// behavior Fabric already records. Same inputs and metric version, same\n// report, on every run.\n\nexport interface EntropyMeterInput {\n traces: readonly EntropyTraceInput[];\n surface?: EntropySurfaceSnapshot;\n repairs?: readonly EntropyRepairRowInput[];\n catalogDigest?: string;\n}\n\nconst DISCOVERY_PREFIX = \"fabric.discovery.\";\nconst WORKFLOW_PREFIX = \"fabric.workflow.\";\nconst DEFAULT_TASK_KEY = \"(none)\";\nconst TOP_SIGNATURES = 8;\n\ninterface RefAccumulator {\n calls: number;\n succeeded: number;\n failed: number;\n signatures: Map<string, number>;\n stages: Map<string, number>;\n churnPairs: number;\n churnSum: number;\n}\n\n// The core pass without per-model attribution; measureEntropy wraps it so\n// each model's behavioral terms come from the same formula over its own\n// traces, measured against the same surface.\ntype EntropyReportCore = Omit<EntropyReport, \"byModel\">;\n\nconst measureOnce = (input: EntropyMeterInput): EntropyReportCore => {\n const surfaceByRef = new Map<string, unknown>();\n if (input.surface) {\n for (const action of input.surface.actions) surfaceByRef.set(action.ref, action.inputSchema);\n }\n\n const lexiconByRef = new Map<string, number>();\n let lexiconRows = 0;\n for (const row of input.repairs ?? []) {\n lexiconByRef.set(row.ref, (lexiconByRef.get(row.ref) ?? 0) + 1);\n lexiconRows += 1;\n }\n\n const totals: EntropyTotals = {\n traces: input.traces.length,\n operations: 0,\n actionOperations: 0,\n discoveryOperations: 0,\n workflowOperations: 0,\n succeeded: 0,\n failed: 0,\n aborted: 0,\n timedOut: 0,\n invocationRejections: 0,\n invocationRejectionsPer1k: 0,\n };\n\n const refs = new Map<string, RefAccumulator>();\n const taskSequences = new Map<string, Map<string, number>>();\n let churnPairs = 0;\n let churnSum = 0;\n\n const accumulator = (ref: string): RefAccumulator => {\n const existing = refs.get(ref);\n if (existing) return existing;\n const created: RefAccumulator = {\n calls: 0,\n succeeded: 0,\n failed: 0,\n signatures: new Map<string, number>(),\n stages: new Map<string, number>(),\n churnPairs: 0,\n churnSum: 0,\n };\n refs.set(ref, created);\n return created;\n };\n\n for (const sourceTrace of input.traces) {\n const taskKey = sourceTrace.taskKey ?? DEFAULT_TASK_KEY;\n const sequence: string[] = [];\n const pendingFailed = new Map<string, string>();\n for (const operation of sourceTrace.operations) {\n totals.operations += 1;\n if (operation.ref.startsWith(DISCOVERY_PREFIX)) {\n totals.discoveryOperations += 1;\n continue;\n }\n if (operation.ref.startsWith(WORKFLOW_PREFIX)) {\n totals.workflowOperations += 1;\n continue;\n }\n totals.actionOperations += 1;\n sequence.push(operation.ref);\n const acc = accumulator(operation.ref);\n acc.calls += 1;\n if (operation.outcome === \"succeeded\") {\n totals.succeeded += 1;\n acc.succeeded += 1;\n } else if (operation.outcome === \"failed\") {\n totals.failed += 1;\n acc.failed += 1;\n } else if (operation.outcome === \"aborted\") {\n totals.aborted += 1;\n } else {\n totals.timedOut += 1;\n }\n const signature = shapeSignature(operation.args);\n acc.signatures.set(signature, (acc.signatures.get(signature) ?? 0) + 1);\n if (operation.outcome === \"failed\") {\n const stage = operation.failureStage ?? \"unknown\";\n acc.stages.set(stage, (acc.stages.get(stage) ?? 0) + 1);\n if (ENTROPY_INVOCATION_STAGES.includes(stage)) totals.invocationRejections += 1;\n }\n const pending = pendingFailed.get(operation.ref);\n if (pending !== undefined) {\n const distance = signatureDistance(pending, signature);\n acc.churnPairs += 1;\n acc.churnSum += distance;\n churnPairs += 1;\n churnSum += distance;\n pendingFailed.delete(operation.ref);\n }\n if (operation.outcome === \"failed\") pendingFailed.set(operation.ref, signature);\n }\n if (sequence.length > 0) {\n const key = sequence.join(\"\u2192\");\n const perTask = taskSequences.get(taskKey) ?? new Map<string, number>();\n perTask.set(key, (perTask.get(key) ?? 0) + 1);\n taskSequences.set(taskKey, perTask);\n }\n }\n\n // Sorted iteration keeps every downstream sum independent of input order.\n const refEntries = [...refs.entries()].sort(([left], [right]) => compareCodeUnits(left, right));\n const refReports: EntropyRefReport[] = [];\n let staticFreedomTotal = 0;\n let staticWeighted = 0;\n let shapeWeighted = 0;\n let failureStageWeighted = 0;\n let scoreSum = 0;\n for (const [ref, acc] of refEntries) {\n const shapeEntropyBits = shannonEntropyBits([...acc.signatures.values()]);\n const failureStageEntropyBits = shannonEntropyBits([...acc.stages.values()]);\n const refChurnRate = acc.churnPairs > 0 ? roundMetric(acc.churnSum / acc.churnPairs) : 0;\n const lexicon = lexiconByRef.get(ref) ?? 0;\n const staticFreedom = surfaceByRef.has(ref)\n ? staticFreedomFromSchema(surfaceByRef.get(ref))\n : 0;\n staticFreedomTotal += staticFreedom;\n staticWeighted += ENTROPY_WEIGHTS.staticFreedom * staticFreedom;\n shapeWeighted += shapeEntropyBits * acc.calls;\n failureStageWeighted += failureStageEntropyBits * acc.failed;\n const score = roundMetric(\n ENTROPY_WEIGHTS.shape * shapeEntropyBits +\n ENTROPY_WEIGHTS.failureStage * failureStageEntropyBits +\n ENTROPY_WEIGHTS.churn * refChurnRate +\n ENTROPY_WEIGHTS.lexicon * lexicon +\n ENTROPY_WEIGHTS.staticFreedom * staticFreedom,\n );\n scoreSum += score;\n const shapeSignatures: EntropyShapeSignature[] = [...acc.signatures.entries()]\n .map(([signature, count]) => ({ signature, count }))\n .sort(\n (left, right) => right.count - left.count || compareCodeUnits(left.signature, right.signature),\n )\n .slice(0, TOP_SIGNATURES);\n refReports.push({\n ref,\n calls: acc.calls,\n succeeded: acc.succeeded,\n failed: acc.failed,\n shapeSignatures,\n shapeEntropyBits,\n failureStageEntropyBits,\n churnRate: refChurnRate,\n lexiconRows: lexicon,\n staticFreedom,\n score,\n });\n }\n\n const navigationRatio =\n totals.actionOperations > 0\n ? roundMetric(totals.discoveryOperations / totals.actionOperations)\n : 0;\n let flowWeighted = 0;\n let flowOccurrences = 0;\n for (const perTask of taskSequences.values()) {\n const counts = [...perTask.values()];\n const occurrences = counts.reduce((sum, value) => sum + value, 0);\n flowWeighted += shannonEntropyBits(counts) * occurrences;\n flowOccurrences += occurrences;\n }\n const flowEntropyBits = flowOccurrences > 0 ? roundMetric(flowWeighted / flowOccurrences) : 0;\n totals.invocationRejectionsPer1k =\n totals.actionOperations > 0\n ? roundMetric((totals.invocationRejections / totals.actionOperations) * 1000)\n : 0;\n\n const score = roundMetric(\n (scoreSum +\n ENTROPY_WEIGHTS.navigation * navigationRatio +\n ENTROPY_WEIGHTS.flow * flowEntropyBits) /\n Math.max(1, totals.succeeded),\n );\n // Decomposition: the surface share prices the potential the corpus used;\n // everything else is freedom models actually exercised. Good is\n // behavioralScore \u2192 0 with staticScore shrinking only through compiled\n // surface changes.\n const staticScore = roundMetric(staticWeighted / Math.max(1, totals.succeeded));\n const behavioralScore = roundMetric(score - staticScore);\n\n const sortedRefs = [...refReports].sort(\n (left, right) => right.score - left.score || compareCodeUnits(left.ref, right.ref),\n );\n\n return {\n metricVersion: ENTROPY_METRIC_VERSION,\n catalogDigest: input.catalogDigest ?? \"\",\n totals,\n shapeEntropyBits:\n totals.actionOperations > 0 ? roundMetric(shapeWeighted / totals.actionOperations) : 0,\n failureStageEntropyBits: totals.failed > 0 ? roundMetric(failureStageWeighted / totals.failed) : 0,\n churnRate: churnPairs > 0 ? roundMetric(churnSum / churnPairs) : 0,\n navigationRatio,\n flowEntropyBits,\n lexiconRows,\n staticFreedom: roundMetric(staticFreedomTotal),\n staticScore,\n behavioralScore,\n score,\n refs: sortedRefs,\n };\n};\n\nexport const measureEntropy = (input: EntropyMeterInput): EntropyReport => {\n const report = measureOnce(input);\n const groups = new Map<string, EntropyTraceInput[]>();\n for (const sourceTrace of input.traces) {\n if (!sourceTrace.model) continue;\n const group = groups.get(sourceTrace.model) ?? [];\n group.push(sourceTrace);\n groups.set(sourceTrace.model, group);\n }\n // Only stamped traces attribute; everything else stays in the global\n // report. Sorted iteration keeps the breakdown order stable.\n const byModel: EntropyModelReport[] = [...groups.entries()]\n .sort(([left], [right]) => compareCodeUnits(left, right))\n .map(([model, traces]) => {\n const scoped = measureOnce({ ...input, traces });\n return {\n model,\n operations: scoped.totals.operations,\n actionOperations: scoped.totals.actionOperations,\n succeeded: scoped.totals.succeeded,\n invocationRejections: scoped.totals.invocationRejections,\n invocationRejectionsPer1k: scoped.totals.invocationRejectionsPer1k,\n behavioralScore: scoped.behavioralScore,\n };\n });\n return { ...report, byModel };\n};\n", "import type {\n EntropyGateResult,\n EntropyProposal,\n EntropyRefReport,\n EntropyReport,\n EntropyRepairRowInput,\n EntropySurfaceAction,\n EntropySurfaceSnapshot,\n EntropyTraceInput,\n EntropyValueObservation,\n} from \"./types.js\";\nimport { compareCodeUnits, roundMetric } from \"./fingerprint.js\";\n\n// Deterministic reduction proposals. Each pass is a pure function over the\n// same typed artifacts the meter reads, with fixed thresholds, and every\n// proposal carries the evidence that triggered it. `applyProposalsToSurface`\n// rewrites the surface for the mechanically applicable kinds; overload-split\n// and sequence-fuse author new composite definitions, so they stay\n// review-only. The gate is the ratchet: a compiled surface must never\n// increase the measured score and must never drop successful calls.\n\nexport interface EntropyProposalInput {\n report: EntropyReport;\n traces: readonly EntropyTraceInput[];\n surface?: EntropySurfaceSnapshot;\n repairs?: readonly EntropyRepairRowInput[];\n valueObservations?: readonly EntropyValueObservation[];\n}\n\nconst ENUM_MIN_OBSERVATIONS = 8;\nconst ENUM_MAX_DISTINCT = 8;\nconst ENUM_MIN_TOP_SHARE = 0.5;\nconst SPLIT_MIN_SHAPE_ENTROPY_BITS = 1;\nconst SPLIT_MIN_CLUSTER_CALLS = 2;\nconst FUSE_MIN_SEQUENCE_LENGTH = 3;\nconst FUSE_MAX_SEQUENCE_LENGTH = 6;\nconst FUSE_MIN_OCCURRENCES = 2;\nconst QUARANTINE_MIN_CALLS = 3;\nconst QUARANTINE_MIN_STAGE_ENTROPY_BITS = 1;\nconst MAX_PROPOSALS_PER_KIND = 8;\n\nconst isPlainRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst valueKey = (value: string | number | boolean): string => `${typeof value}:${String(value)}`;\n\nconst schemaProperties = (schema: unknown): Record<string, unknown> | undefined => {\n if (!isPlainRecord(schema)) return undefined;\n const properties = schema.properties;\n return isPlainRecord(properties) ? properties : undefined;\n};\n\nconst enumKeys = (schema: unknown): Set<string> | undefined => {\n if (!isPlainRecord(schema) || !Array.isArray(schema.enum)) return undefined;\n const keys = new Set<string>();\n for (const entry of schema.enum) {\n if (typeof entry === \"string\" || typeof entry === \"number\" || typeof entry === \"boolean\") {\n keys.add(valueKey(entry));\n }\n }\n return keys;\n};\n\nconst contains = (outer: readonly string[], inner: readonly string[]): boolean => {\n if (outer.length < inner.length) return false;\n for (let start = 0; start + inner.length <= outer.length; start++) {\n let matches = true;\n for (let index = 0; index < inner.length; index++) {\n if (outer[start + index] !== inner[index]) {\n matches = false;\n break;\n }\n }\n if (matches) return true;\n }\n return false;\n};\n\nexport const proposeEntropyReductions = (input: EntropyProposalInput): EntropyProposal[] => {\n const calledRefs = new Map<string, EntropyRefReport>();\n for (const ref of input.report.refs) calledRefs.set(ref.ref, ref);\n const surfaceByRef = new Map<string, unknown>();\n const surfaceRefs = new Set<string>();\n if (input.surface) {\n for (const action of input.surface.actions) {\n surfaceByRef.set(action.ref, action.inputSchema);\n surfaceRefs.add(action.ref);\n }\n }\n\n const proposals: EntropyProposal[] = [];\n\n // enum-tighten: a parameter whose observed values are few and concentrated\n // compiles into an enum, so future off-modal values fail (or repair)\n // deterministically instead of slipping through a free string.\n const observations = new Map<\n string,\n {\n ref: string;\n key: string;\n counts: Map<string, { value: string | number | boolean; count: number }>;\n total: number;\n }\n >();\n const observeValue = (ref: string, key: string, value: string | number | boolean): void => {\n const id = `${ref}\\u0000${key}`;\n const entry =\n observations.get(id) ??\n {\n ref,\n key,\n counts: new Map<string, { value: string | number | boolean; count: number }>(),\n total: 0,\n };\n const valueId = valueKey(value);\n const existing = entry.counts.get(valueId);\n entry.counts.set(valueId, { value, count: (existing?.count ?? 0) + 1 });\n entry.total += 1;\n observations.set(id, entry);\n };\n // Verbatim audit observations are the authoritative value corpus when\n // supplied: audits carry every argument, including the parameters the\n // trace projection drops. Without them the scan uses the projected trace\n // args.\n if (input.valueObservations) {\n for (const observation of input.valueObservations) {\n observeValue(observation.ref, observation.key, observation.value);\n }\n } else {\n for (const sourceTrace of input.traces) {\n for (const operation of sourceTrace.operations) {\n if (operation.ref.startsWith(\"fabric.\")) continue;\n for (const [key, value] of Object.entries(operation.args)) {\n if (typeof value !== \"string\" && typeof value !== \"number\" && typeof value !== \"boolean\") {\n continue;\n }\n observeValue(operation.ref, key, value);\n }\n }\n }\n }\n const enumCandidates = [...observations.values()]\n .filter((entry) => entry.total >= ENUM_MIN_OBSERVATIONS)\n .filter((entry) => entry.counts.size >= 2 && entry.counts.size <= ENUM_MAX_DISTINCT)\n .map((entry) => {\n const ranked = [...entry.counts.values()].sort(\n (left, right) =>\n right.count - left.count || compareCodeUnits(valueKey(left.value), valueKey(right.value)),\n );\n return { entry, ranked, topShare: roundMetric(ranked[0]!.count / entry.total) };\n })\n .filter((candidate) => candidate.topShare >= ENUM_MIN_TOP_SHARE)\n .filter((candidate) => {\n // Idempotence: skip when the live schema's enum already covers every\n // observed value, so a compiled surface stops re-proposing.\n if (!input.surface) return true;\n const properties = schemaProperties(surfaceByRef.get(candidate.entry.ref));\n const target = properties ? properties[candidate.entry.key] : undefined;\n const existing = enumKeys(target);\n if (!existing) return true;\n return [...candidate.entry.counts.keys()].some((observed) => !existing.has(observed));\n })\n .sort((left, right) =>\n compareCodeUnits(`${left.entry.ref}\\u0000${left.entry.key}`, `${right.entry.ref}\\u0000${right.entry.key}`),\n )\n .slice(0, MAX_PROPOSALS_PER_KIND);\n for (const candidate of enumCandidates) {\n proposals.push({\n kind: \"enum-tighten\",\n ref: candidate.entry.ref,\n key: candidate.entry.key,\n values: candidate.ranked.map((item) => item.value),\n calls: candidate.entry.total,\n distinct: candidate.entry.counts.size,\n topShare: candidate.topShare,\n });\n }\n\n // modal-rename: a repair row whose target is called means the spilled\n // spelling is the model's modal grammar. Compile it into the schema and\n // retire the row instead of paying the map forever.\n const repairRows = [...(input.repairs ?? [])].sort(\n (left, right) =>\n compareCodeUnits(left.ref, right.ref) ||\n compareCodeUnits(left.from, right.from) ||\n compareCodeUnits(left.to, right.to),\n );\n for (const row of repairRows) {\n if (!calledRefs.has(row.ref)) continue;\n if (input.surface) {\n if (row.kind === \"keyAlias\") {\n const properties = schemaProperties(surfaceByRef.get(row.ref));\n if (properties && row.from in properties) continue;\n } else {\n const provider = row.ref.split(\".\")[0] ?? row.ref;\n if (surfaceRefs.has(`${provider}.${row.from}`)) continue;\n }\n }\n proposals.push({\n kind: \"modal-rename\",\n level: row.kind === \"keyAlias\" ? \"key\" : \"action\",\n ref: row.ref,\n from: row.from,\n to: row.to,\n note:\n row.kind === \"keyAlias\"\n ? \"the spilled spelling dominates observed calls; rename the declared key and retire the repair row\"\n : \"the spilled action name dominates observed calls; rename the declared action and retire the repair row\",\n });\n }\n\n // overload-split: one ref carrying two disjoint parameter key-sets is an\n // overloaded action; splitting removes the per-call either/or freedom.\n const overloadRefs = new Set(\n input.report.refs\n .filter((ref) => ref.shapeEntropyBits >= SPLIT_MIN_SHAPE_ENTROPY_BITS)\n .map((ref) => ref.ref),\n );\n if (overloadRefs.size > 0) {\n const keySets = new Map<string, Map<string, { keys: string[]; calls: number }>>();\n for (const sourceTrace of input.traces) {\n for (const operation of sourceTrace.operations) {\n if (!overloadRefs.has(operation.ref)) continue;\n const keys = Object.keys(operation.args).sort();\n const id = keys.join(\"\\u0000\");\n const perRef = keySets.get(operation.ref) ?? new Map<string, { keys: string[]; calls: number }>();\n const cluster = perRef.get(id) ?? { keys, calls: 0 };\n cluster.calls += 1;\n perRef.set(id, cluster);\n keySets.set(operation.ref, perRef);\n }\n }\n let overloadCount = 0;\n for (const [ref, perRef] of [...keySets.entries()].sort(([left], [right]) =>\n compareCodeUnits(left, right),\n )) {\n if (overloadCount >= MAX_PROPOSALS_PER_KIND) break;\n const clusters = [...perRef.values()]\n .filter((cluster) => cluster.calls >= SPLIT_MIN_CLUSTER_CALLS)\n .sort(\n (left, right) =>\n right.calls - left.calls || compareCodeUnits(left.keys.join(\",\"), right.keys.join(\",\")),\n );\n const disjoint: { keys: string[]; calls: number }[] = [];\n for (const cluster of clusters) {\n const keys = new Set(cluster.keys);\n if (disjoint.every((candidate) => candidate.keys.every((key) => !keys.has(key)))) {\n disjoint.push(cluster);\n }\n }\n if (disjoint.length >= 2) {\n overloadCount += 1;\n const report = calledRefs.get(ref);\n proposals.push({\n kind: \"overload-split\",\n ref,\n shapeEntropyBits: report?.shapeEntropyBits ?? 0,\n clusters: disjoint.slice(0, MAX_PROPOSALS_PER_KIND).map((cluster) => ({\n keys: cluster.keys,\n calls: cluster.calls,\n })),\n });\n }\n }\n }\n\n // sequence-fuse: a contiguous multi-ref action sequence that repeats across\n // executions is a composite action (or skill) waiting to be extracted.\n const sequenceCounts = new Map<string, { sequence: string[]; occurrences: number }>();\n for (const sourceTrace of input.traces) {\n const refs = sourceTrace.operations\n .filter((operation) => !operation.ref.startsWith(\"fabric.\"))\n .map((operation) => operation.ref);\n for (\n let length = FUSE_MIN_SEQUENCE_LENGTH;\n length <= Math.min(FUSE_MAX_SEQUENCE_LENGTH, refs.length);\n length++\n ) {\n for (let start = 0; start + length <= refs.length; start++) {\n const sequence = refs.slice(start, start + length);\n if (new Set(sequence).size < 2) continue;\n const id = sequence.join(\"\u2192\");\n const entry = sequenceCounts.get(id) ?? { sequence, occurrences: 0 };\n entry.occurrences += 1;\n sequenceCounts.set(id, entry);\n }\n }\n }\n const fuseCandidates = [...sequenceCounts.values()]\n .filter((entry) => entry.occurrences >= FUSE_MIN_OCCURRENCES)\n .sort(\n (left, right) =>\n right.sequence.length - left.sequence.length ||\n right.occurrences - left.occurrences ||\n compareCodeUnits(left.sequence.join(\"\u2192\"), right.sequence.join(\"\u2192\")),\n );\n const selected: { sequence: string[]; occurrences: number }[] = [];\n for (const candidate of fuseCandidates) {\n if (selected.length >= MAX_PROPOSALS_PER_KIND) break;\n const redundant = selected.some(\n (chosen) =>\n contains(candidate.sequence, chosen.sequence) || contains(chosen.sequence, candidate.sequence),\n );\n if (redundant) continue;\n selected.push(candidate);\n }\n for (const candidate of selected) {\n proposals.push({\n kind: \"sequence-fuse\",\n sequence: candidate.sequence,\n occurrences: candidate.occurrences,\n });\n }\n\n // noise-quarantine: a called ref that fails more than it succeeds, with\n // more than one failure stage, is a candidate to hide from the\n // model-facing catalog. The precondition (more failures than successes)\n // carries the replay-safety argument for retiring it.\n const quarantineCandidates = input.report.refs\n .filter(\n (ref) =>\n ref.calls >= QUARANTINE_MIN_CALLS &&\n ref.failed > ref.succeeded &&\n ref.failureStageEntropyBits >= QUARANTINE_MIN_STAGE_ENTROPY_BITS,\n )\n .filter((ref) => !input.surface || surfaceRefs.has(ref.ref))\n .slice(0, MAX_PROPOSALS_PER_KIND);\n for (const ref of quarantineCandidates) {\n proposals.push({\n kind: \"noise-quarantine\",\n ref: ref.ref,\n calls: ref.calls,\n succeeded: ref.succeeded,\n failed: ref.failed,\n failureStageEntropyBits: ref.failureStageEntropyBits,\n });\n }\n\n return proposals;\n};\n\nconst deepCloneJson = (value: unknown): unknown =>\n value === undefined ? {} : (JSON.parse(JSON.stringify(value)) as unknown);\n\n// Apply the mechanically applicable proposals as a pure surface rewrite.\n// The input surface is never mutated; enum-tighten injects the observed\n// enum, noise-quarantine removes the action, modal-rename renames the\n// declared key or action to the model's modal spelling. Overload-split and\n// sequence-fuse produce review-only proposals and are skipped here.\nexport const applyProposalsToSurface = (\n surface: EntropySurfaceSnapshot,\n proposals: readonly EntropyProposal[],\n): EntropySurfaceSnapshot => {\n const actions: EntropySurfaceAction[] = surface.actions.map((action) => ({\n ref: action.ref,\n inputSchema: deepCloneJson(action.inputSchema),\n }));\n const quarantined = new Set<string>();\n for (const proposal of proposals) {\n if (proposal.kind === \"noise-quarantine\") {\n quarantined.add(proposal.ref);\n continue;\n }\n if (proposal.kind === \"modal-rename\" && proposal.level === \"action\") {\n const provider = proposal.ref.split(\".\")[0] ?? proposal.ref;\n const renamed = `${provider}.${proposal.from}`;\n for (const action of actions) {\n if (action.ref === proposal.ref) action.ref = renamed;\n }\n continue;\n }\n if (proposal.kind === \"enum-tighten\" || (proposal.kind === \"modal-rename\" && proposal.level === \"key\")) {\n const action = actions.find((candidate) => candidate.ref === proposal.ref);\n if (!action || !isPlainRecord(action.inputSchema)) continue;\n const schema = action.inputSchema;\n const properties = schemaProperties(schema);\n if (!properties) continue;\n if (proposal.kind === \"enum-tighten\") {\n if (!isPlainRecord(properties[proposal.key])) continue;\n properties[proposal.key] = {\n ...(properties[proposal.key] as Record<string, unknown>),\n enum: [...proposal.values],\n };\n continue;\n }\n if (!(proposal.to in properties) || proposal.from in properties) continue;\n properties[proposal.from] = properties[proposal.to]!;\n delete properties[proposal.to];\n if (Array.isArray(schema.required)) {\n schema.required = schema.required.map((key) => (key === proposal.to ? proposal.from : key));\n }\n }\n }\n const survivors = actions\n .filter((action) => !quarantined.has(action.ref))\n .sort((left, right) => compareCodeUnits(left.ref, right.ref));\n return { version: 1, actions: survivors };\n};\n\n// The ratchet: a compiled surface must not increase the measured score and\n// must preserve every successful call. Monotonicity is measured, never\n// argued.\nexport const evaluateGate = (before: EntropyReport, after: EntropyReport): EntropyGateResult => {\n const reasons: string[] = [];\n if (after.score > before.score) {\n reasons.push(`score increased ${before.score} \u2192 ${after.score}`);\n }\n if (after.totals.succeeded < before.totals.succeeded) {\n reasons.push(\n `successful calls dropped ${before.totals.succeeded} \u2192 ${after.totals.succeeded}`,\n );\n }\n return {\n passed: reasons.length === 0,\n beforeScore: before.score,\n afterScore: after.score,\n delta: roundMetric(after.score - before.score),\n reasons,\n };\n};\n", "// Live surface snapshots for the entropy meter. Discovery is Fabric's\n// authorization-free read path (read-only, no approval budget, no side\n// effects): providers answer `list` from static descriptors, in-memory\n// catalogs, or the MCP descriptor cache, so a minimal synthetic invocation\n// context is safe for command-time surface listing.\n\nimport type { ExtensionContext } from \"@earendil-works/pi-coding-agent\";\nimport type { FabricInvocationContext } from \"../protocol.js\";\nimport { stableJsonHash } from \"../core/stable-hash.js\";\nimport { compareCodeUnits, roundMetric, staticFreedomFromSchema } from \"./fingerprint.js\";\nimport type { EntropySurfaceSnapshot } from \"./types.js\";\n\nconst SURFACE_LIST_LIMIT = 1_000;\n\nexport interface EntropySurfaceListAction {\n ref: string;\n inputSchema: unknown;\n}\n\nexport interface EntropySurfaceRegistry {\n list(\n request: { limit?: number; declared?: boolean },\n context: FabricInvocationContext,\n ): Promise<readonly EntropySurfaceListAction[]>;\n}\n\nconst surfaceInvocationContext = (input: {\n extensionContext: ExtensionContext;\n cwd: string;\n}): FabricInvocationContext => ({\n cwd: input.cwd,\n signal: undefined,\n parentToolCallId: \"fabric-entropy-surface\",\n nestedToolCallId: \"fabric-entropy-surface\",\n extensionContext: input.extensionContext,\n update: () => {},\n});\n\n// Snapshot the live action surface (ref + input schema per action) through\n// the registry's discovery path. Sorted by ref so the snapshot hashes and\n// diffs deterministically.\nexport const liveSurfaceSnapshot = async (input: {\n registry: EntropySurfaceRegistry;\n extensionContext: ExtensionContext;\n cwd: string;\n}): Promise<EntropySurfaceSnapshot> => {\n // Declared truth, never the enforced view: the compile's base surface\n // keeps quarantined refs visible so base-digest proofs and artifact\n // carry-forward read the declared schema. The model-facing catalog keeps\n // hiding them.\n const actions = await input.registry.list(\n { limit: SURFACE_LIST_LIMIT, declared: true },\n surfaceInvocationContext(input),\n );\n return {\n version: 1,\n actions: actions\n .map((action) => ({ ref: action.ref, inputSchema: action.inputSchema }))\n .sort((left, right) => compareCodeUnits(left.ref, right.ref)),\n };\n};\n\nexport const entropySurfaceHash = (surface: EntropySurfaceSnapshot): string =>\n stableJsonHash(surface);\n\nexport interface EntropySurfaceFreedomEntry {\n ref: string;\n freedom: number;\n}\n\nexport interface EntropySurfaceFreedomReport {\n actions: EntropySurfaceFreedomEntry[];\n total: number;\n mean: number;\n}\n\n// Static freedom of a whole surface: per-action scores sorted worst-first,\n// with the total and mean the ratchet tracks. Computable with no corpus at\n// all, which is what lets a candidate surface be scored before any session\n// runs against it.\nexport const surfaceFreedomReport = (\n surface: EntropySurfaceSnapshot,\n): EntropySurfaceFreedomReport => {\n const actions = surface.actions\n .map((action) => ({ ref: action.ref, freedom: staticFreedomFromSchema(action.inputSchema) }))\n .sort((left, right) => right.freedom - left.freedom || compareCodeUnits(left.ref, right.ref));\n const total = roundMetric(actions.reduce((sum, entry) => sum + entry.freedom, 0));\n return {\n actions,\n total,\n mean: actions.length > 0 ? roundMetric(total / actions.length) : 0,\n };\n};\n", "// The autonomous compile step: measure \u2192 propose \u2192 apply the mechanical\n// subset \u2192 re-measure \u2192 gate. The gate proves two things on the retained\n// corpus: the score never increases, and every successful call to a ref\n// the compile touched still parses against the candidate surface.\n// Overload-split and sequence-fuse author new composite definitions, and a\n// pure modal rename drops the declared key that every successful call\n// recorded, so all three stay surfaced for review and never auto-apply.\n\nimport { stableJsonHash } from \"../core/stable-hash.js\";\nimport { measureEntropy } from \"./meter.js\";\nimport { applyProposalsToSurface, evaluateGate, proposeEntropyReductions } from \"./passes.js\";\nimport {\n COMPILED_SURFACE_VERSION,\n MAX_COMPILED_SURFACE_PROPOSALS,\n applyCompiledSurface,\n replaySuccessfulCalls,\n schemaDigest,\n type CompiledSurfaceAppliedProposal,\n type CompiledSurfaceFile,\n} from \"./compiled-surface.js\";\nimport { entropySurfaceHash } from \"./surface.js\";\nimport { ENTROPY_METRIC_VERSION } from \"./types.js\";\nimport type {\n EntropyGateResult,\n EntropyProposal,\n EntropyRepairRowInput,\n EntropyReport,\n EntropySurfaceSnapshot,\n EntropyTraceInput,\n EntropyValueObservation,\n} from \"./types.js\";\n\n// The kinds the autonomous loop may apply. Every other proposal carries its\n// evidence to the surfaced review queue instead.\nexport const AUTO_APPLY_PROPOSAL_KINDS: readonly string[] = [\"enum-tighten\", \"noise-quarantine\"];\n\nexport interface CompileEntropyInput {\n traces: readonly EntropyTraceInput[];\n surface: EntropySurfaceSnapshot;\n repairs?: readonly EntropyRepairRowInput[];\n valueObservations?: readonly EntropyValueObservation[];\n artifact?: CompiledSurfaceFile;\n catalogDigest?: string;\n}\n\nexport type CompileEntropyStatus = \"compiled\" | \"converged\" | \"rejected\";\n\nexport interface CompileEntropyOutcome {\n status: CompileEntropyStatus;\n /** The maintained artifact: new when compiled, the input artifact otherwise. */\n artifact?: CompiledSurfaceFile;\n report: EntropyReport;\n after?: EntropyReport;\n proposals: EntropyProposal[];\n gate?: EntropyGateResult;\n}\n\nconst proposalDetail = (proposal: EntropyProposal): { ref: string; detail: string } => {\n if (proposal.kind === \"enum-tighten\") {\n return { ref: proposal.ref, detail: `${proposal.key}: ${proposal.values.length} observed values` };\n }\n if (proposal.kind === \"noise-quarantine\") {\n return { ref: proposal.ref, detail: `${proposal.failed} failed vs ${proposal.succeeded} succeeded` };\n }\n return { ref: \"n/a\", detail: \"review-only\" };\n};\n\n// Refs the compile touched: tightened schemas and quarantined actions. The\n// replay gate scopes to this set; untouched refs keep their schema by\n// identity, so projection artifacts elsewhere cannot poison a compile.\nconst touchedRefs = (before: EntropySurfaceSnapshot, after: EntropySurfaceSnapshot): Set<string> => {\n const beforeByRef = new Map(before.actions.map((action) => [action.ref, action.inputSchema]));\n const touched = new Set<string>();\n for (const action of after.actions) {\n if (stableJsonHash(beforeByRef.get(action.ref)) !== stableJsonHash(action.inputSchema)) {\n touched.add(action.ref);\n }\n }\n for (const ref of beforeByRef.keys()) {\n if (!after.actions.some((action) => action.ref === ref)) touched.add(ref);\n }\n return touched;\n};\n\n// Build the maintained artifact from the candidate surface against the live\n// surface: overlay entries carry the live base digest, quarantined actions\n// carry theirs, and the applied ledger accumulates across compiles.\nconst artifactFromCandidate = (\n live: EntropySurfaceSnapshot,\n candidate: EntropySurfaceSnapshot,\n proposals: readonly EntropyProposal[],\n gate: { passed: boolean; beforeScore: number; afterScore: number; reasons: string[] },\n evidenceDigest: string,\n previous?: CompiledSurfaceFile,\n): CompiledSurfaceFile => {\n const liveByRef = new Map(live.actions.map((action) => [action.ref, action.inputSchema]));\n const actions = candidate.actions\n .filter(\n (action) => stableJsonHash(action.inputSchema) !== stableJsonHash(liveByRef.get(action.ref)),\n )\n .map((action) => ({\n ref: action.ref,\n inputSchema: action.inputSchema as Record<string, unknown>,\n baseSchemaDigest: schemaDigest(liveByRef.get(action.ref)),\n }));\n const candidateRefs = new Set(candidate.actions.map((action) => action.ref));\n const quarantined = live.actions\n .filter((action) => !candidateRefs.has(action.ref))\n .map((action) => ({ ref: action.ref, baseSchemaDigest: schemaDigest(action.inputSchema) }));\n const applied: CompiledSurfaceAppliedProposal[] = [...(previous?.applied ?? [])];\n const seen = new Set(applied.map((entry) => `${entry.kind}:${entry.ref}:${entry.detail}`));\n for (const proposal of proposals) {\n const { ref, detail } = proposalDetail(proposal);\n const identity = `${proposal.kind}:${ref}:${detail}`;\n if (seen.has(identity)) continue;\n seen.add(identity);\n applied.push({ kind: proposal.kind, ref, detail });\n }\n return {\n version: COMPILED_SURFACE_VERSION,\n metricVersion: ENTROPY_METRIC_VERSION,\n actions,\n quarantined,\n applied: applied.slice(0, MAX_COMPILED_SURFACE_PROPOSALS),\n gate,\n evidenceDigest,\n };\n};\n\nexport const compileEntropySurface = (input: CompileEntropyInput): CompileEntropyOutcome => {\n const effective = applyCompiledSurface(input.surface, input.artifact);\n const report = measureEntropy({\n traces: input.traces,\n surface: effective,\n ...(input.repairs ? { repairs: input.repairs } : {}),\n catalogDigest: input.catalogDigest ?? entropySurfaceHash(effective),\n });\n const proposals = proposeEntropyReductions({\n report,\n traces: input.traces,\n surface: effective,\n ...(input.repairs ? { repairs: input.repairs } : {}),\n ...(input.valueObservations ? { valueObservations: input.valueObservations } : {}),\n });\n const auto = proposals.filter((proposal) =>\n (AUTO_APPLY_PROPOSAL_KINDS as readonly string[]).includes(proposal.kind),\n );\n if (auto.length === 0) {\n return {\n status: \"converged\",\n ...(input.artifact ? { artifact: input.artifact } : {}),\n report,\n proposals,\n };\n }\n const candidate = applyProposalsToSurface(effective, auto);\n const after = measureEntropy({\n traces: input.traces,\n surface: candidate,\n ...(input.repairs ? { repairs: input.repairs } : {}),\n catalogDigest: entropySurfaceHash(candidate),\n });\n const scoreGate = evaluateGate(report, after);\n const violations = replaySuccessfulCalls(\n candidate,\n input.traces,\n touchedRefs(effective, candidate),\n );\n const reasons = [\n ...scoreGate.reasons,\n ...violations.map((violation) => `${violation.ref}: ${violation.reason}`),\n ];\n const gate: EntropyGateResult = {\n passed: scoreGate.passed && violations.length === 0,\n beforeScore: report.score,\n afterScore: after.score,\n delta: scoreGate.delta,\n reasons: scoreGate.passed && violations.length === 0 ? [] : reasons,\n };\n if (gate.passed) {\n const evidenceDigest = stableJsonHash({\n traces: input.traces.length,\n operations: report.totals.operations,\n succeeded: report.totals.succeeded,\n failed: report.totals.failed,\n surface: entropySurfaceHash(effective),\n repairs: input.repairs?.length ?? 0,\n });\n return {\n status: \"compiled\",\n artifact: artifactFromCandidate(\n input.surface,\n candidate,\n auto,\n { passed: true, beforeScore: report.score, afterScore: after.score, reasons: [] },\n evidenceDigest,\n input.artifact,\n ),\n report,\n after,\n proposals,\n gate,\n };\n }\n return {\n status: \"rejected\",\n ...(input.artifact ? { artifact: input.artifact } : {}),\n report,\n after,\n proposals,\n gate,\n };\n};", "// Corpus shaping for the entropy meter: turn persisted Fabric execution\n// traces and session JSONL into meter traces, and normalize catalog repair\n// rows. Only guarded, typed records are consumed \u2014 never rendered prose.\n\nimport {\n FABRIC_EXECUTION_TRACE_KIND,\n readFabricExecutionTraceV1,\n type FabricExecutionTraceV1,\n} from \"../audit/trace.js\";\nimport { stableJsonHash } from \"../core/stable-hash.js\";\nimport type { CatalogRepair } from \"../repairs/types.js\";\nimport type {\n EntropyReport,\n EntropyRepairRowInput,\n EntropyTraceInput,\n EntropyValueObservation,\n} from \"./types.js\";\n\nconst DEFAULT_TASK_KEY = \"(none)\";\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n// One Fabric execution trace becomes one meter trace. The first persisted\n// workflow phase is the deterministic task key for flow entropy.\nexport const entropyTraceFromFabricTrace = (\n trace: FabricExecutionTraceV1,\n model?: string,\n): EntropyTraceInput => ({\n operations: trace.operations.map((operation) => ({\n ref: operation.ref,\n args: operation.args,\n outcome: operation.outcome,\n ...(operation.failureStage !== undefined ? { failureStage: operation.failureStage } : {}),\n })),\n taskKey: trace.phases[0] ?? DEFAULT_TASK_KEY,\n ...(model ? { model } : {}),\n});\n\nconst MODEL_CHANGE_FILTER = '\"type\":\"model_change\"';\nconst ASSISTANT_FILTER = '\"role\":\"assistant\"';\n\n// Model identity for one parsed session record: `model_change` entries name\n// the provider/model from that point on, and assistant messages carry the\n// provider/model that produced the turn. A toolResult's producing model is\n// the one active at its line, so the scan tracks it in order.\nconst modelFromRecord = (parsed: Record<string, unknown>): string | undefined => {\n if (parsed.type === \"model_change\") {\n const provider = typeof parsed.provider === \"string\" ? parsed.provider : \"\";\n const modelId = typeof parsed.modelId === \"string\" ? parsed.modelId : \"\";\n return provider && modelId ? `${provider}/${modelId}` : undefined;\n }\n const message = isRecord(parsed.message) ? parsed.message : undefined;\n if (!message || message.role !== \"assistant\") return undefined;\n const provider = typeof message.provider === \"string\" ? message.provider : \"\";\n const modelId = typeof message.model === \"string\" ? message.model : \"\";\n return provider && modelId ? `${provider}/${modelId}` : undefined;\n};\n\ninterface ScannedSessionRecord {\n details: Record<string, unknown>;\n model?: string;\n}\n\n// Cheap pre-filters keep on-demand multi-session scans fast on large logs:\n// only lines that can carry a trace envelope or a model identity get parsed.\n// The substring gates are lossy by design; the guarded parse decides.\nconst sessionRecords = (lines: readonly string[]): ScannedSessionRecord[] => {\n const records: ScannedSessionRecord[] = [];\n let currentModel: string | undefined;\n for (const line of lines) {\n const trimmed = line.trim();\n if (trimmed === \"\") continue;\n const traceLine = trimmed.includes(FABRIC_EXECUTION_TRACE_KIND);\n const modelLine =\n !traceLine &&\n (trimmed.includes(MODEL_CHANGE_FILTER) || trimmed.includes(ASSISTANT_FILTER));\n if (!traceLine && !modelLine) continue;\n let parsed: unknown;\n try {\n parsed = JSON.parse(trimmed);\n } catch {\n continue;\n }\n if (!isRecord(parsed)) continue;\n if (modelLine) {\n const model = modelFromRecord(parsed);\n if (model) currentModel = model;\n continue;\n }\n const details = isRecord(parsed.details)\n ? parsed.details\n : isRecord(parsed.message) && isRecord(parsed.message.details)\n ? parsed.message.details\n : undefined;\n if (isRecord(details)) {\n records.push({ details, ...(currentModel ? { model: currentModel } : {}) });\n }\n }\n return records;\n};\n\n// Extract meter traces from Pi session JSONL lines. Malformed lines, non-trace\n// entries, and envelopes that fail the trace guard are skipped without\n// throwing; only typed, guarded trace V1 envelopes count.\nexport const entropyTracesFromSessionJsonl = (lines: readonly string[]): EntropyTraceInput[] => {\n const traces: EntropyTraceInput[] = [];\n for (const record of sessionRecords(lines)) {\n const trace = readFabricExecutionTraceV1(record.details.trace);\n if (trace) traces.push(entropyTraceFromFabricTrace(trace, record.model));\n }\n return traces;\n};\n\n// Verbatim audit arguments are the authoritative value corpus for\n// enum-tighten: trace V1 projects values away per ref (external and MCP calls\n// keep none), while persisted audits carry every argument the call used. The\n// observations stay local to the session record, exactly like the audits.\nexport const entropyValueObservationsFromSessionJsonl = (\n lines: readonly string[],\n): EntropyValueObservation[] => {\n const observations: EntropyValueObservation[] = [];\n for (const record of sessionRecords(lines)) {\n const details = record.details;\n if (!Array.isArray(details.audits)) continue;\n for (const audit of details.audits) {\n if (!isRecord(audit)) continue;\n const ref = typeof audit.ref === \"string\" ? audit.ref : undefined;\n const args = isRecord(audit.args) ? audit.args : undefined;\n if (!ref || !args) continue;\n for (const [key, value] of Object.entries(args)) {\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n observations.push({ ref, key, value });\n }\n }\n }\n }\n return observations;\n};\n\n// Normalize catalog repair rows for the meter. `ref` is the target the row\n// repairs toward: the declared key's action for key aliases, or\n// provider.declared-action for action aliases.\nexport const entropyRepairRows = (repairs: readonly CatalogRepair[]): EntropyRepairRowInput[] =>\n repairs.map((repair) =>\n repair.kind === \"keyAlias\"\n ? { kind: \"keyAlias\", ref: repair.ref, from: repair.from, to: repair.to }\n : {\n kind: \"actionAlias\",\n ref: `${repair.provider}.${repair.to}`,\n from: repair.from,\n to: repair.to,\n },\n );\n\n// Stable hash of a report \u2014 the determinism check compares these.\nexport const entropyReportHash = (report: EntropyReport): string => stableJsonHash(report);\n", "// On-demand session measurement. Session JSONL is the source of truth, so\n// entropy is never recorded: the newest project sessions are read live,\n// measured against the current surface, and the trend is the per-session\n// slope. The repair table and the compiled entropy surface are the only\n// durable derived artifacts, because they are the only ones that change\n// runtime behavior.\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { sessionDirForCwd } from \"../memory/discovery.js\";\nimport {\n entropyTracesFromSessionJsonl,\n entropyValueObservationsFromSessionJsonl,\n} from \"./corpus.js\";\nimport { measureEntropy } from \"./meter.js\";\nimport { compareCodeUnits, trendFromScores } from \"./fingerprint.js\";\nimport type {\n EntropyModelReport,\n EntropyReport,\n EntropySurfaceSnapshot,\n EntropyTraceInput,\n EntropyTrend,\n EntropyValueObservation,\n} from \"./types.js\";\n\nconst DEFAULT_SESSION_WINDOW = 8;\n\nexport interface SessionCorpusEntry {\n file: string;\n operations: number;\n report: EntropyReport;\n}\n\n// Per-model trend across the session window: the attribution that names\n// which model's behavior moved, with the surface share staying global.\nexport interface SessionModelTrend {\n model: string;\n sessions: number;\n latestBehavioralScore: number;\n slopePerSession: number;\n latestRejectionsPer1k: number;\n}\n\nexport interface SessionCorpusResult {\n files: readonly string[];\n sessions: SessionCorpusEntry[];\n latest?: EntropyReport;\n trend: EntropyTrend;\n models: SessionModelTrend[];\n}\n\n// Newest-first session JSONL files for one project cwd, bounded by `limit`.\n// Mtime ties break by path so the ordering is stable.\nexport const projectSessionFiles = (\n agentDir: string,\n cwd: string,\n limit = DEFAULT_SESSION_WINDOW,\n): string[] => {\n const dir = sessionDirForCwd(cwd, agentDir);\n let entries: fs.Dirent[] = [];\n try {\n entries = fs.readdirSync(dir, { withFileTypes: true });\n } catch {\n return [];\n }\n const stamped = entries\n .filter((entry) => entry.isFile() && entry.name.endsWith(\".jsonl\"))\n .map((entry) => {\n const file = path.join(dir, entry.name);\n let mtime = 0;\n try {\n mtime = fs.statSync(file).mtimeMs;\n } catch {\n mtime = 0;\n }\n return { file, mtime };\n });\n stamped.sort(\n (left, right) =>\n right.mtime - left.mtime || (left.file < right.file ? -1 : left.file > right.file ? 1 : 0),\n );\n return stamped.slice(0, Math.max(1, limit)).map((entry) => entry.file);\n};\n\n// Measure each session file independently against the same surface; sessions\n// without fabric_exec traces contribute nothing. `files` must be newest\n// first; the trend runs oldest to newest.\nexport const measureSessionCorpus = (input: {\n files: readonly string[];\n surface?: EntropySurfaceSnapshot;\n catalogDigest?: string;\n}): SessionCorpusResult => {\n const sessions: SessionCorpusEntry[] = [];\n for (const file of input.files) {\n let text: string;\n try {\n text = fs.readFileSync(file, \"utf8\");\n } catch {\n continue;\n }\n const traces = entropyTracesFromSessionJsonl(text.split(\"\\n\"));\n if (traces.length === 0) continue;\n const report = measureEntropy({\n traces,\n ...(input.surface ? { surface: input.surface } : {}),\n ...(input.catalogDigest !== undefined ? { catalogDigest: input.catalogDigest } : {}),\n });\n if (report.totals.operations === 0) continue;\n sessions.push({ file, operations: report.totals.operations, report });\n }\n const chronological = [...sessions].reverse();\n const modelScores = new Map<string, { behavioral: number[]; latest: EntropyModelReport }>();\n for (const session of chronological) {\n for (const model of session.report.byModel) {\n const entry = modelScores.get(model.model) ?? { behavioral: [], latest: model };\n entry.behavioral.push(model.behavioralScore);\n entry.latest = model;\n modelScores.set(model.model, entry);\n }\n }\n const models: SessionModelTrend[] = [...modelScores.entries()]\n .sort(([left], [right]) => compareCodeUnits(left, right))\n .map(([model, entry]) => ({\n model,\n sessions: entry.behavioral.length,\n latestBehavioralScore: entry.latest.behavioralScore,\n slopePerSession: trendFromScores(entry.behavioral).slopePerStep,\n latestRejectionsPer1k: entry.latest.invocationRejectionsPer1k,\n }));\n return {\n files: input.files,\n sessions,\n ...(sessions.length > 0 ? { latest: sessions[0]!.report } : {}),\n trend: trendFromScores(chronological.map((session) => session.report.score)),\n models,\n };\n};\n\n// One read per file yields both meter traces and the verbatim audit value\n// corpus, so the autonomous compile and the command share a single window\n// scan.\nexport interface SessionWindowEvidence {\n traces: EntropyTraceInput[];\n valueObservations: EntropyValueObservation[];\n}\n\nexport const sessionWindowEvidence = (\n files: readonly string[],\n): SessionWindowEvidence => {\n const traces: EntropyTraceInput[] = [];\n const valueObservations: EntropyValueObservation[] = [];\n for (const file of files) {\n let text: string;\n try {\n text = fs.readFileSync(file, \"utf8\");\n } catch {\n continue;\n }\n const lines = text.split(\"\\n\");\n traces.push(...entropyTracesFromSessionJsonl(lines));\n valueObservations.push(...entropyValueObservationsFromSessionJsonl(lines));\n }\n return { traces, valueObservations };\n};\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;AAQO,IAAM,yBAAyB;AAI/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;;;ACjB7F,IAAM,qBAAqB;AAC3B,IAAM,sBAAsB;AAE5B,IAAM,uBAAuB;AAE7B,IAAM,gBAAgB,CAAC,UACrB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAK9D,IAAM,cAAc,CAAC,UAA0B;AACpD,QAAM,UAAU,KAAK,MAAM,QAAQ,GAAG,IAAI;AAC1C,SAAO,YAAY,IAAI,IAAI;AAC7B;AAIO,IAAM,mBAAmB,CAAC,MAAc,UAC7C,OAAO,QAAQ,KAAK,OAAO,QAAQ,IAAI;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ecord", "DEFAULT_TASK_KEY", "provider", "modelId"]
|
|
7
7
|
}
|
|
@@ -6,7 +6,7 @@ import {
|
|
|
6
6
|
} from "./chunk-SOBEXOWK.js";
|
|
7
7
|
import {
|
|
8
8
|
NESTED_TOOL_CALL_ID_PREFIX
|
|
9
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-R6KHFESZ.js";
|
|
10
10
|
import {
|
|
11
11
|
THINKING_DIGEST_CUSTOM_TYPE,
|
|
12
12
|
buildThinkingDigest,
|
|
@@ -2447,4 +2447,4 @@ export {
|
|
|
2447
2447
|
resolveFabricIdentity,
|
|
2448
2448
|
MainAgentController
|
|
2449
2449
|
};
|
|
2450
|
-
//# sourceMappingURL=chunk-
|
|
2450
|
+
//# sourceMappingURL=chunk-NQIGNZBM.js.map
|
|
@@ -735,9 +735,13 @@ var ActionRegistry = class {
|
|
|
735
735
|
}
|
|
736
736
|
return sources;
|
|
737
737
|
}
|
|
738
|
+
// The model-facing discovery view: quarantined refs hide here. Pass
|
|
739
|
+
// `declared: true` for the compile's base-surface truth, which keeps
|
|
740
|
+
// quarantined refs visible so base-digest proofs and artifact
|
|
741
|
+
// carry-forward can read the declared schema.
|
|
738
742
|
async list(request, context) {
|
|
739
743
|
if (context.capabilityView) {
|
|
740
|
-
const refs = Object.keys(context.capabilityView.bindings).filter((ref) => !request.provider || ref.startsWith(`${request.provider}.`)).filter((ref) => !activeQuarantinedRefNames().has(ref)).sort();
|
|
744
|
+
const refs = Object.keys(context.capabilityView.bindings).filter((ref) => !request.provider || ref.startsWith(`${request.provider}.`)).filter((ref) => request.declared || !activeQuarantinedRefNames().has(ref)).sort();
|
|
741
745
|
const actions = await Promise.all(refs.map((ref) => this.describe(ref, context)));
|
|
742
746
|
const query = request.query?.normalize("NFKC").trim().toLowerCase();
|
|
743
747
|
return actions.filter((action) => !request.namespace || action.namespace === request.namespace).filter(
|
|
@@ -749,7 +753,7 @@ var ActionRegistry = class {
|
|
|
749
753
|
providers.map(async (provider) => {
|
|
750
754
|
const descriptors = await provider.list(request, context);
|
|
751
755
|
return descriptors.filter(
|
|
752
|
-
(descriptor) => !activeQuarantinedRefNames().has(`${provider.name}.${descriptor.name}`)
|
|
756
|
+
(descriptor) => request.declared || !activeQuarantinedRefNames().has(`${provider.name}.${descriptor.name}`)
|
|
753
757
|
).map((descriptor) => resolveDescriptor(provider, descriptor));
|
|
754
758
|
})
|
|
755
759
|
);
|
|
@@ -1248,7 +1252,10 @@ var ActionRegistry = class {
|
|
|
1248
1252
|
* Prepare + pre-launch a speculative call discovered in a partially
|
|
1249
1253
|
* streamed program (see src/speculation). Pure pipeline only: descriptor
|
|
1250
1254
|
* resolution, the eligibility gate on the resolved action, argument
|
|
1251
|
-
* preparation, and schema validation.
|
|
1255
|
+
* preparation, and schema validation. The compiled entropy surface gates
|
|
1256
|
+
* launches too: quarantined refs never pre-launch and overlays validate
|
|
1257
|
+
* prepared arguments, so the store never warms a call the serve path
|
|
1258
|
+
* would reject. authorize/approve/audits are skipped
|
|
1252
1259
|
* because the eligibility gate restricts this path to actions that never
|
|
1253
1260
|
* prompt, and the real call re-runs the full pipeline on a serve miss.
|
|
1254
1261
|
* Side-channel outputs are captured into `replay` so the serve path can
|
|
@@ -1267,8 +1274,15 @@ var ActionRegistry = class {
|
|
|
1267
1274
|
if (expectedDescriptorHash && actionDescriptorHash(action) !== expectedDescriptorHash) {
|
|
1268
1275
|
return void 0;
|
|
1269
1276
|
}
|
|
1277
|
+
if (isActiveQuarantine(provider.name, actionName, descriptor.inputSchema)) {
|
|
1278
|
+
return void 0;
|
|
1279
|
+
}
|
|
1270
1280
|
if (!this.#speculationEligibility(action)) return void 0;
|
|
1271
|
-
const
|
|
1281
|
+
const effectiveSchema = effectiveInputSchema(
|
|
1282
|
+
action.ref,
|
|
1283
|
+
action.inputSchema
|
|
1284
|
+
);
|
|
1285
|
+
const catalogInput = applyActiveArgRepairs(action.ref, args, effectiveSchema);
|
|
1272
1286
|
const preparedArgs = provider.prepareArguments ? await runAbortable(context.signal, () => provider.prepareArguments(actionName, catalogInput, context)) : catalogInput;
|
|
1273
1287
|
if (typeof preparedArgs !== "object" || preparedArgs === null || Array.isArray(preparedArgs)) {
|
|
1274
1288
|
return void 0;
|
|
@@ -1276,9 +1290,9 @@ var ActionRegistry = class {
|
|
|
1276
1290
|
const repairedArgs = applyActiveArgRepairs(
|
|
1277
1291
|
action.ref,
|
|
1278
1292
|
preparedArgs,
|
|
1279
|
-
|
|
1293
|
+
effectiveSchema
|
|
1280
1294
|
);
|
|
1281
|
-
if (validationMessage(
|
|
1295
|
+
if (validationMessage(effectiveSchema, repairedArgs)) return void 0;
|
|
1282
1296
|
const nestedToolCallId = `${NESTED_TOOL_CALL_ID_PREFIX}spec-${randomUUID2()}`;
|
|
1283
1297
|
return {
|
|
1284
1298
|
preparedArgs: repairedArgs,
|
|
@@ -1525,4 +1539,4 @@ export {
|
|
|
1525
1539
|
NESTED_TOOL_CALL_ID_PREFIX,
|
|
1526
1540
|
ActionRegistry
|
|
1527
1541
|
};
|
|
1528
|
-
//# sourceMappingURL=chunk-
|
|
1542
|
+
//# sourceMappingURL=chunk-R6KHFESZ.js.map
|