automated-qa 0.11.0
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/LICENSE +22 -0
- package/NOTICE +9 -0
- package/README.md +100 -0
- package/SKILL.md +65 -0
- package/agent/prebuilt/darwin-universal/qa-agent +0 -0
- package/agent/prebuilt/linux-arm64/qa-agent +0 -0
- package/agent/prebuilt/linux-x64/qa-agent +0 -0
- package/agent/release-manifest.json +31 -0
- package/bin/autonomous-cache.mjs +2 -0
- package/bin/bench-generate.mjs +232 -0
- package/bin/bench-graph-query.mjs +2 -0
- package/bin/bench-score.mjs +10 -0
- package/bin/classify.mjs +15 -0
- package/bin/coherence-playwright.mjs +1 -0
- package/bin/coherence-runner.mjs +6 -0
- package/bin/crud-runner.mjs +12 -0
- package/bin/experiment-executor.mjs +10 -0
- package/bin/experiment-runner.mjs +3 -0
- package/bin/inventory.mjs +17 -0
- package/bin/probe.js +879 -0
- package/bin/qa.mjs +16 -0
- package/bin/rules.mjs +5 -0
- package/bin/run-benchmarks.mjs +2 -0
- package/bin/runtime-packs.mjs +3 -0
- package/bin/semantic-explorer.mjs +3 -0
- package/bin/shadow-collector.mjs +3 -0
- package/bin/shadow-replay.mjs +6 -0
- package/bin/soak-marathon.mjs +15 -0
- package/bin/sweep.mjs +43 -0
- package/bin/validate-priors.mjs +3 -0
- package/bin/verify-artifacts.mjs +3 -0
- package/bin/verify-manifest.mjs +2 -0
- package/install-skill.sh +45 -0
- package/lib/qa/agent-availability.mjs +1 -0
- package/lib/qa/agent-result.mjs +1 -0
- package/lib/qa/analysis.mjs +5 -0
- package/lib/qa/atlas-coverage.mjs +11 -0
- package/lib/qa/atlas-v1.mjs +1 -0
- package/lib/qa/atlas.mjs +2 -0
- package/lib/qa/auth/coordinator.mjs +1 -0
- package/lib/qa/auth/launcher.mjs +3 -0
- package/lib/qa/auth/lease.mjs +1 -0
- package/lib/qa/auth/oracle.mjs +1 -0
- package/lib/qa/auth/personas.mjs +3 -0
- package/lib/qa/autonomous-cache.mjs +3 -0
- package/lib/qa/block-ledger.mjs +1 -0
- package/lib/qa/capture-report.mjs +63 -0
- package/lib/qa/ci.mjs +11 -0
- package/lib/qa/cli.mjs +538 -0
- package/lib/qa/coherence/analyze.mjs +1 -0
- package/lib/qa/coherence/cache-key.mjs +6 -0
- package/lib/qa/coherence/causes.mjs +1 -0
- package/lib/qa/coherence/concurrency.mjs +1 -0
- package/lib/qa/coherence/contracts.mjs +1 -0
- package/lib/qa/coherence/entity-aliases.mjs +1 -0
- package/lib/qa/coherence/enums.mjs +1 -0
- package/lib/qa/coherence/family-report.mjs +1 -0
- package/lib/qa/coherence/flow-pool.mjs +1 -0
- package/lib/qa/coherence/graph.mjs +1 -0
- package/lib/qa/coherence/identity.mjs +1 -0
- package/lib/qa/coherence/ir.mjs +4 -0
- package/lib/qa/coherence/navigation.mjs +1 -0
- package/lib/qa/coherence/observe.mjs +2 -0
- package/lib/qa/coherence/offline.mjs +1 -0
- package/lib/qa/coherence/plan-join.mjs +1 -0
- package/lib/qa/coherence/provenance.mjs +2 -0
- package/lib/qa/coherence/report.mjs +1 -0
- package/lib/qa/coherence/representations.mjs +1 -0
- package/lib/qa/coherence/risk.mjs +2 -0
- package/lib/qa/coherence/structural-js.mjs +11 -0
- package/lib/qa/coherence/symbols.mjs +6 -0
- package/lib/qa/coherence/tanstack.mjs +4 -0
- package/lib/qa/coherence/views.mjs +1 -0
- package/lib/qa/coherence-planner.mjs +1 -0
- package/lib/qa/command-catalog.mjs +2 -0
- package/lib/qa/commands/dev.mjs +1 -0
- package/lib/qa/commands/fix.mjs +1 -0
- package/lib/qa/commands/impl/analysis.mjs +1 -0
- package/lib/qa/commands/impl/atlas.mjs +1 -0
- package/lib/qa/commands/impl/coherence.mjs +1 -0
- package/lib/qa/commands/impl/crud.mjs +2 -0
- package/lib/qa/commands/impl/doctor.mjs +1 -0
- package/lib/qa/commands/impl/experiments.mjs +1 -0
- package/lib/qa/commands/impl/fp.mjs +1 -0
- package/lib/qa/commands/impl/graph.mjs +1 -0
- package/lib/qa/commands/impl/invariants.mjs +1 -0
- package/lib/qa/commands/impl/lanes.mjs +7 -0
- package/lib/qa/commands/impl/ledger.mjs +11 -0
- package/lib/qa/commands/impl/loop.mjs +1 -0
- package/lib/qa/commands/impl/marathon.mjs +1 -0
- package/lib/qa/commands/impl/next.mjs +38 -0
- package/lib/qa/commands/impl/report.mjs +4 -0
- package/lib/qa/commands/impl/research.mjs +4 -0
- package/lib/qa/commands/impl/selftest.mjs +1 -0
- package/lib/qa/commands/impl/serve.mjs +1 -0
- package/lib/qa/commands/impl/shadow.mjs +1 -0
- package/lib/qa/commands/impl/stability.mjs +1 -0
- package/lib/qa/commands/impl/triage.mjs +1 -0
- package/lib/qa/commands/impl/validate.mjs +4 -0
- package/lib/qa/commands/impl/version.mjs +1 -0
- package/lib/qa/commands/impl/watch.mjs +1 -0
- package/lib/qa/commands/init.mjs +6 -0
- package/lib/qa/commands/measure.mjs +1 -0
- package/lib/qa/commands/run.mjs +1 -0
- package/lib/qa/commands/show.mjs +1 -0
- package/lib/qa/commands/verify.mjs +6 -0
- package/lib/qa/deepening.mjs +1 -0
- package/lib/qa/denominators.mjs +1 -0
- package/lib/qa/depth.mjs +4 -0
- package/lib/qa/doctor.mjs +2 -0
- package/lib/qa/experiments-default.mjs +1 -0
- package/lib/qa/fix-lanes.mjs +3 -0
- package/lib/qa/forced-states.mjs +1 -0
- package/lib/qa/fp.mjs +2 -0
- package/lib/qa/fs.mjs +6 -0
- package/lib/qa/graph-schema.mjs +2 -0
- package/lib/qa/graph.mjs +3 -0
- package/lib/qa/harness-plan.mjs +3 -0
- package/lib/qa/init.mjs +5 -0
- package/lib/qa/integrity.mjs +1 -0
- package/lib/qa/invariants.mjs +84 -0
- package/lib/qa/jcs.mjs +1 -0
- package/lib/qa/lanes.mjs +1 -0
- package/lib/qa/loop.mjs +7 -0
- package/lib/qa/marathon-coherence.mjs +1 -0
- package/lib/qa/marathon-phases.mjs +1 -0
- package/lib/qa/marathon-wait.mjs +3 -0
- package/lib/qa/marathon.mjs +5 -0
- package/lib/qa/mode-coverage.mjs +1 -0
- package/lib/qa/mutation-policy.mjs +1 -0
- package/lib/qa/pattern-ledger.mjs +3 -0
- package/lib/qa/pending.mjs +1 -0
- package/lib/qa/proc.mjs +4 -0
- package/lib/qa/recommend.mjs +1 -0
- package/lib/qa/release-manifest.mjs +1 -0
- package/lib/qa/report-html.mjs +178 -0
- package/lib/qa/reports.mjs +2 -0
- package/lib/qa/request-evidence.mjs +1 -0
- package/lib/qa/research.mjs +20 -0
- package/lib/qa/routing.mjs +1 -0
- package/lib/qa/runs.mjs +1 -0
- package/lib/qa/schema.mjs +1 -0
- package/lib/qa/serve.mjs +4 -0
- package/lib/qa/server.mjs +1 -0
- package/lib/qa/source-snapshot.mjs +3 -0
- package/lib/qa/stability.mjs +3 -0
- package/lib/qa/state-evidence.mjs +1 -0
- package/lib/qa/sweep-incremental.mjs +1 -0
- package/lib/qa/triage.mjs +2 -0
- package/lib/qa/verdict.mjs +1 -0
- package/lib/qa/watch.mjs +2 -0
- package/package.json +62 -0
- package/references/ATLAS-COVERAGE.md +231 -0
- package/references/atlas-v1.md +318 -0
- package/references/atlas.md +338 -0
- package/references/verify.crud.example.json +1 -0
- package/references/verify.impact.example.json +1 -0
- package/references/verify.shadow.example.json +1 -0
- package/schemas/agent-result.schema.json +135 -0
- package/schemas/analysis.schema.json +15 -0
- package/schemas/classify.schema.json +61 -0
- package/schemas/coherence-ir.schema.json +1585 -0
- package/schemas/coherence-observed.schema.json +1171 -0
- package/schemas/coherence-plan.schema.json +77 -0
- package/schemas/coherence-risk.schema.json +46 -0
- package/schemas/crud-observed.schema.json +118 -0
- package/schemas/experiment-execution.schema.json +82 -0
- package/schemas/graph-edge.schema.json +22 -0
- package/schemas/graph-node.schema.json +81 -0
- package/schemas/graph.schema.json +2493 -0
- package/schemas/identity-oracle.schema.json +19 -0
- package/schemas/inventory.schema.json +2167 -0
- package/schemas/lanes-plan.schema.json +52 -0
- package/schemas/next.schema.json +54 -0
- package/schemas/personas.schema.json +52 -0
- package/schemas/research.schema.json +192 -0
- package/schemas/run.schema.json +160 -0
- package/schemas/shadow-replay.schema.json +68 -0
- package/schemas/stability.schema.json +92 -0
- package/schemas/sweep.schema.json +239 -0
- package/schemas/v1/agent-result.schema.json +106 -0
- package/schemas/v1/run.schema.json +96 -0
- package/schemas/verify-crud.schema.json +37 -0
- package/schemas/verify-read-only.schema.json +37 -0
- package/templates/github-workflow.yml +80 -0
- package/templates/pre-commit.sample +22 -0
- package/verify.sh +385 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{canonicalize as u}from"../jcs.mjs";const k=Object.freeze(["measured","partial","unmeasured"]),O=Object.freeze(["exact","resolved","coarse","unresolved","uncertain"]),x=Object.freeze(["value","empty","absent","failed","withheld","redacted","loading"]),R=Object.freeze(["visible","absent","redacted","withheld","forbidden"]),E=Object.freeze(["same-surface","client-navigation","reload","fresh-context","history-back","history-forward","direct-url","offline-replay"]),b=Object.freeze(["route","component","modal","drawer","tab","wizard-step","embedded-widget"]),w=Object.freeze(["dynamic-import","namespace-spread","export-star","computed-member","ambiguous-alias","unresolved-module","unsupported-syntax"]),p=Object.freeze({invalidateQueries:e=>[{kind:"invalidate",scope:"matched"},{kind:"refetch",scope:e.refetchType==null?"active":typeof e.refetchType=="string"?e.refetchType:"unknown"}],refetchQueries:()=>[{kind:"refetch",scope:"matched"}],resetQueries:()=>[{kind:"reset",scope:"matched"},{kind:"refetch",scope:"active"}],removeQueries:()=>[{kind:"remove",scope:"matched"}],setQueryData:()=>[{kind:"update",scope:"matched"}],setQueriesData:()=>[{kind:"update",scope:"matched"}]});function C(e){return e?.receiver?.resolution!=="resolved"?[]:e.operation==="clear"?e.receiver.kind==="query-client"?[{kind:"clear-query-cache",scope:"all"},{kind:"clear-mutation-cache",scope:"all"}]:e.receiver.kind==="query-cache"?[{kind:"clear-query-cache",scope:"all"}]:[]:e.receiver.kind==="query-client"?p[e.operation]?.(e.filters??{})??[]:[]}function v(e,t){return!e||!t?"unresolved":e.kind==="wildcard"||t.kind==="wildcard"?"covered":e.kind!=="literal"||t.kind!=="literal"?"unresolved":u(e.value)===u(t.value)?"covered":"not-covered"}function f(e,t){const r=e?.material??e??{},s=r.keyMatch??r.match;if(s==="unknown"||s==="predicate")return"unresolved";const n=r.predicate||Object.keys(r.filters??{}).some(c=>c!=="refetchType");if(s==="all")return n?"unresolved":"covered";const o=r.key?.segments??r.pattern?.segments??e?.key?.segments??[],a=t?.segments??[];if(!o.length||!a.length)return"unresolved";let d=!1;for(let c=0;c<Math.min(o.length,a.length);c++){const l=v(o[c],a[c]);if(l==="not-covered")return"not-covered";l==="unresolved"&&(d=!0)}const i=s==="exact"?o.length!==a.length:o.length>a.length;return i&&!d?"not-covered":i||d||n?"unresolved":"covered"}function I(e){return e.includes("covered")?"covered":e.includes("unresolved")?"unresolved":"not-covered"}function m(e,t){if(t!=="covered")return t;const r=e?.material??e??{};return r.receiver?.resolution==="unresolved"||r.operation!=="invalidateQueries"||Object.keys(r.filters??{}).some(s=>s!=="refetchType")||r.keyMatch==="all"?"unresolved":"covered"}function S(e,t,r=new Map){const s=[];for(const n of e.values()){const o={...n.material,key:r.get(n.material?.keyId)?.material??n.material?.key??null};for(const a of t.values()){const d=f({...n,material:o},a.pattern),i=m({...n,material:o},d);s.push({id:`${n.id}:${a.id}`,operationId:n.id,readId:a.id,keyCoverage:d,effectCoverage:i,mandatory:d==="unresolved"||i==="unresolved"||o.keyMatch==="all"})}}return s.sort((n,o)=>n.operationId.localeCompare(o.operationId)||n.readId.localeCompare(o.readId))}const h=()=>({writeCandidates:0,writesResolved:0,writesNonWrite:0,writesUnresolved:0,writersWithNoReaderSurface:0,ambiguousMutationOccurrences:0,readCandidates:0,readsResolved:0,readsUnresolved:0,keysDiscovered:0,keysResolved:0,keysUnresolved:0,operationsDiscovered:0,operationsResolved:0,operationsUnresolved:0,invalidationsDiscovered:0,invalidationsResolved:0,invalidationsUnresolved:0,operationReadPairsDiscovered:0,operationReadPairsCovered:0,operationReadPairsNotCovered:0,operationReadPairsUnresolved:0,surfacesSuggested:0,surfacesResolved:0,surfacesDeclared:0,ownershipEdgesDiscovered:0,ownershipEdgesResolved:0,ownershipEdgesUnresolved:0});function y(){return{artifact:"frontend-verify.semantic-graph",schemaVersion:2,coverage:{status:"unmeasured",factsDiscovered:0,factsResolved:0,factsUnresolved:0,unresolvedIds:[]},nodes:[],edges:[]}}function T(){return{schemaVersion:4,graph:y(),coverage:{status:"unmeasured",reason:"not-analyzed",counts:h(),unresolved:[],unjoinedWriterFamilies:[]},resourceFamilies:[],cacheKeys:[],cacheOperations:[],reads:[],mutations:[],invalidations:[],operationReadPairs:[],surfaces:[],ownershipEdges:[],candidates:[]}}function N({runId:e,base:t,lane:r}){return{schemaVersion:1,status:"unmeasured",runId:e,base:t,lane:r,provenance:[],cases:[],findings:[],reason:"not-observed",counts:{cases:{planned:0,completed:0,unmeasured:0},targets:{planned:0,reached:0,compared:0,agreed:0,unmeasured:0},personas:{planned:0,completed:0,unmeasured:0},contexts:{planned:0,completed:0,unmeasured:0},cleanups:{planned:0,completed:0,unmeasured:0},obligations:{discovered:0,resolved:0,unresolved:0,planned:0,reached:0,compared:0,agreed:0},mutations:{declared:0,executed:0}}}}export{O as CONFIDENCES,k as COVERAGE_STATUSES,w as OWNERSHIP_REASONS,x as REPRESENTATION_STATES,b as SURFACE_KINDS,E as TRANSITION_MODES,R as VISIBILITY_EXPECTATIONS,S as deriveOperationReadPairs,m as effectCoverage,T as emptyCoherence,N as emptyCoherenceObserved,y as emptySemanticGraph,C as expectedCacheOperationEffects,f as keyCoverage,I as reduceCoverage};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const h=128,y=32,l=/^[a-z][a-z0-9_-]{0,63}$/,u=/^(?:\{[A-Za-z_$][\w$]*\}|:[A-Za-z_$][\w$]*|\$[A-Za-z_$][\w$]*)$/,p=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function m(e){const n=String(e??"").split("?")[0].split("#")[0].split("/");return n.map((s,r)=>r===0||!s||!(u.test(s)||/^\d+$/.test(s)||p.test(s))?s:r===n.length-1?"":":param").filter((s,r)=>r===0||s!=="").join("/")||"/"}function d(e){if(typeof e!="string"||e.length<2||e.length>512||!e.startsWith("/"))return"must be an absolute path of 2..512 characters";if(/[*?#]/.test(e))return"must not contain wildcards, query strings, or fragments";const i=e.slice(1).split("/");return i.some(n=>!n)?"must not contain empty path segments":i.some(n=>/[:${}]/.test(n)&&!u.test(n))?"contains a malformed dynamic segment":null}function $(e){if(e?.entities===void 0)return{ok:!0};if(e.schema_version!==2)return{ok:!1,reason:'"entities" is supported only with schema_version 2'};if(!Array.isArray(e.entities)||e.entities.length>128)return{ok:!1,reason:'"entities" must be an array with at most 128 entries'};const i=new Set,n=new Map;for(let a=0;a<e.entities.length;a++){const t=e.entities[a];if(!t||typeof t!="object"||Array.isArray(t))return{ok:!1,reason:`entities[${a}] is not an object`};const s=Object.keys(t).filter(r=>r!=="name"&&r!=="endpoints");if(s.length)return{ok:!1,reason:`entities[${a}] has unknown field "${s[0]}"`};if(typeof t.name!="string"||!l.test(t.name))return{ok:!1,reason:`entities[${a}].name must match ${l}`};if(i.has(t.name))return{ok:!1,reason:`entity name "${t.name}" is declared more than once`};if(i.add(t.name),!Array.isArray(t.endpoints)||t.endpoints.length<2||t.endpoints.length>32)return{ok:!1,reason:`entity "${t.name}" must declare 2..32 endpoints`};for(const r of t.endpoints){const o=d(r);if(o)return{ok:!1,reason:`entity "${t.name}" endpoint ${JSON.stringify(r)} ${o}`};const f=m(r),c=n.get(f);if(c)return{ok:!1,reason:`endpoint family "${f}" is assigned to both "${c}" and "${t.name}"`};n.set(f,t.name)}}return{ok:!0}}function A(e=[]){const n=$({schema_version:2,entities:e});if(!n.ok)throw new TypeError(n.reason);return new Map(e.flatMap(a=>a.endpoints.map(t=>[m(t),a.name])))}export{m as endpointFamily,A as entityAliasMap,$ as validateEntityAliases};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function c(n,t){if(typeof t!="string"||!t.startsWith("#/"))return null;let r=n;for(const s of t.slice(2).split("/"))if(r=r?.[s.replace(/~1/g,"/").replace(/~0/g,"~")],r==null)return null;return r}function i(n,{schema:t,property:r}){let e=n?.components?.schemas?.[t]?.properties?.[r];return e?.$ref&&(e=c(n,e.$ref)),!e||!Array.isArray(e.enum)?{status:"unmeasured",cases:[],reason:"missing-or-non-enum-schema"}:{status:"measured",cases:[...new Set(e.enum.filter(o=>["string","number","boolean"].includes(typeof o)))]}}function p({cases:n,renderers:t,maxCases:r}){const e=(n??[]).slice(0,Math.max(0,r??n?.length??0)).flatMap(l=>(t??[]).map(u=>({value:l,renderer:u}))),o=(n?.length??0)*(t?.length??0),a=e.length<o;return{planned:e,total:o,truncated:a,...a?{reason:`${e.length} of ${o} renderer cases planned`}:{}}}export{i as enumCasesFromOpenApi,p as planEnumFanout,c as resolveLocalSchemaRef};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{parseObligationId as I}from"./plan-join.mjs";const x=()=>({possible:null,discovered:null,resolved:null,unresolved:null,planned:null,reached:0,compared:0,agreed:0,disagreed:0,unmeasuredObligations:0});function k({coherence:r,dimension:m=null,observed:a=null,causes:o=null}){const t=new Map;if(m?.status==="measured")for(const e of m.value?.families??[])t.set(e.family,e);const i=new Map((r?.surfaces??[]).map(e=>[e.id,e])),g=new Map((r?.mutations??[]).map(e=>[e.id,e])),h=new Map;let v=0;const y=e=>(h.has(e)||h.set(e,{reached:0,compared:0,agreed:0,disagreed:0,unmeasuredObligations:0}),h.get(e));for(const e of a?.plan?.journeys??[])for(const n of e.targets??[])for(const d of n.obligations??[]){const u=[3,4].includes(a?.schemaVersion)?d.mutationId:I(d.id)?.mutationId,f=u?g.get(u)?.family??null:null;if(!f){v++;continue}const s=y(f);d.status==="unmeasured"?s.unmeasuredObligations++:(s.reached++,d.status==="agreed"?(s.compared++,s.agreed++):d.status==="disagreed"&&(s.compared++,s.disagreed++))}const $=new Map;for(const e of o?.causes??[])e.family&&($.has(e.family)||$.set(e.family,[]),$.get(e.family).push(e));const p=(r?.resourceFamilies??[]).map(e=>{const n=t.get(e.family)??null,d=h.get(e.family)??null,u={...x(),...d??{}};n&&(u.possible=n.possible??null,u.discovered=n.discovered??null,u.resolved=n.resolved??null,u.unresolved=n.unresolved??null,u.planned=n.planned??null);const f=n?.principals??null;return{family:e.family,mutations:(e.mutationIds??[]).map(s=>g.get(s)?.hook??s).sort(),surfaces:(e.surfaceIds??[]).map(s=>{const l=i.get(s);return l?.component?`${l.route}:${l.component}`:l?.route??s}).sort(),keyTerms:e.keyTerms??[],principals:f,contexts:n?.contexts??null,invariants:n?.invariants??null,excluded:n?.excluded??null,funnel:u,rootCauses:($.get(e.family)??[]).filter(s=>s.label==="confirmed").map(s=>({rootCauseId:s.rootCauseId,mutation:s.mutation??s.mutationId,source:s.source??null,affectedSurfaces:s.affectedSurfaces.filter(l=>l.runtime==="disagreed").map(l=>l.component?`${l.route}:${l.component}`:l.route??l.surfaceId)})),unmeasuredReason:n?null:"no-kernel-accounting"}});for(const e of p){const n=e.funnel,d=[n.agreed,n.compared,n.reached,n.planned,n.resolved,n.discovered,n.possible].filter(u=>u!=null);d.every((u,f)=>f===0||d[f-1]<=u)||(e.funnel={...n,monotone:!1},e.unmeasuredReason="funnel-not-monotone: the plan and the runtime evidence disagree, most likely a stale agent-result.json")}const b=p.some(e=>e.funnel.monotone===!1);return{status:p.length===0?"unmeasured":b?"invalid":t.size?"measured":"partial",reason:p.length===0?"no-resource-families":b?"funnel-not-monotone":t.size?null:"no-kernel-accounting",families:p,unattributed:v}}const c=r=>r==null?"unmeasured":String(r);function C(r,{max:m=10}={}){const a=[];for(const o of(r?.families??[]).slice(0,m)){a.push(`${o.family} coherence`),a.push(` mutations ${o.mutations.length} \xB7 surfaces ${o.surfaces.length} \xB7 principals ${c(o.principals)} \xB7 contexts ${c(o.contexts)} \xB7 invariants ${c(o.invariants)}`);const t=o.funnel;a.push(` possible ${c(t.possible)} \xB7 discovered ${c(t.discovered)} (resolved ${c(t.resolved)}, unresolved ${c(t.unresolved)}) \xB7 planned ${c(t.planned)}`),a.push(` reached ${t.reached} \xB7 compared ${t.compared} \xB7 agreed ${t.agreed} \xB7 disagreed ${t.disagreed}${t.unmeasuredObligations?` \xB7 unmeasured ${t.unmeasuredObligations}`:""}`),o.unmeasuredReason&&a.push(` funnel unmeasured: ${o.unmeasuredReason}`),o.excluded&&Object.keys(o.excluded).length&&a.push(` excluded from the Cartesian bound: ${Object.entries(o.excluded).map(([i,g])=>`${g} ${i}`).join(", ")}`);for(const i of o.rootCauses)a.push(` root cause: ${i.mutation}${i.source?.file?` (${i.source.file}:${i.source.line})`:""}`),i.affectedSurfaces.length&&a.push(` affected surfaces: ${i.affectedSurfaces.join(", ")}`)}return r?.unattributed&&a.push(`${r.unattributed} planned obligation(s) unattributed: no mutation in this inventory (stale plan)`),(r?.families??[]).length>m&&a.push(`... ${r.families.length-m} more families`),a}export{k as familyBlocks,C as renderFamilies};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
async function m(e,t){const n=new Array(e.length);if(e.length===0)return n;let r=0,i=0;return new Promise((u,h)=>{let c=!1;function s(){if(c)return;if(r>=e.length){i===0&&(c=!0,u(n));return}const o=r++;i++,Promise.resolve().then(()=>e[o]()).then(l=>{n[o]=l,i--,s()},l=>{c||(c=!0,h(l))})}const a=Math.max(1,Math.min(t,e.length));for(let o=0;o<a;o++)s()})}function f(e,t){return!(e.crosscheck?.entity&&e.crosscheck.entity===t.crosscheck?.entity)||e.crosscheck?.isolation==="per-flow"&&t.crosscheck?.isolation==="per-flow"?null:`flows "${e.name}" and "${t.name}" share crosscheck.entity "${e.crosscheck.entity}" without isolation: "per-flow" declared on both`}function y(e){for(let t=0;t<e.length;t++)for(let n=t+1;n<e.length;n++){const r=f(e[t],e[n]);if(r)return{ok:!1,reason:r}}return{ok:!0,reason:null}}function p(e,t){return`coherence-${e}-${t}`}export{y as checkFlowIsolation,p as fixtureNamespaceFor,m as runBounded};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{canonicalize as v,jcsDigest as A}from"../jcs.mjs";import{CONFIDENCES as le,OWNERSHIP_REASONS as L}from"./contracts.mjs";import{deriveOperationReadPairs as fe}from"./contracts.mjs";import{keyResolution as J}from"./cache-key.mjs";const j=(e,n)=>e<n?-1:e>n?1:0,W=Object.freeze(["finding","feature","route","surface","component","symbol","query","api-resource","mutation","cache-key","family","truth-subject","principal","context","invariant","flow","observation","workflow-transition","provenance"]),X=Object.freeze({"renders-through":{from:["route"],to:["component"]},"contains-surface":{from:["route"],to:["surface"]},realizes:{from:["component"],to:["surface"]},uses:{from:["component","symbol"],to:["symbol"]},declares:{from:["symbol"],to:["query","mutation"]},requests:{from:["query"],to:["api-resource"]},"uses-key":{from:["query"],to:["cache-key"]},reads:{from:["query"],to:["family"]},writes:{from:["mutation"],to:["family","truth-subject"]},calls:{from:["mutation"],to:["api-resource"]},invalidates:{from:["mutation"],to:["cache-key"]},"direct-updates":{from:["mutation"],to:["cache-key"]},"reads-via":{from:["surface"],to:["query"]},renders:{from:["surface"],to:["family","truth-subject"]},"may-observe":{from:["principal"],to:["surface"]},implements:{from:["flow"],to:["mutation"]},targets:{from:["flow"],to:["surface"]},"observed-at":{from:["observation"],to:["surface"]},represents:{from:["observation"],to:["truth-subject"]},"starts-at":{from:["workflow-transition"],to:["route"]},"ends-at":{from:["workflow-transition"],to:["route"]},"evidenced-by":{from:W.filter(e=>e!=="provenance"),to:["provenance"]}}),Z=Object.freeze([...L,"absent-producer","ambiguous-mutation-occurrence","contract-conflict","dynamic-key","no-resolvable-endpoint","non-json-value","unattributed-mutation-owner","unknown-helper","unsafe-number","unsupported-client","unsupported-expression"]),ue=L,q=64,Q="resolved",me=Object.freeze(["classify","declaration","inventory","rust","sweep"]),pe=Object.freeze(["cache-key","cache-operation","mutation","provenance-cap","query","route","surface","symbol","symbol-traversal","symbol-use"]),Ve=Object.freeze(["builder-edge-conflict","builder-node-conflict","conflicting-edge","conflicting-node","coverage","dangling-edge","duplicate-edge","duplicate-node","edge-endpoint-kind","edge-id","edge-order","edge-shape","legacy-artifact-version","node-domain-id","node-id","node-identity","node-order","node-read-id","node-shape","operation-conflict","provenance","provenance-order","resolved-edge-unresolved-endpoint","root","unresolved-ledger","unresolved-reason","unsafe-value"]),z=new Set(le),T=/^graph:v2:node:[a-f0-9]{64}$/,ye=/^graph:v2:edge:[a-f0-9]{64}$/,ve=/^[a-f0-9]{64}$/,Ie=Object.freeze(["cacheKeyId","contextId","familyId","flowId","invariantId","mutationId","observationId","principalId","provenanceId","surfaceId","transitionId","truthSubjectId"]),ge=/^sha256:[a-f0-9]{64}$/,he=["artifactVersion","recordId","kind","identity","certainty","provenance","attrs"],be=["artifactVersion","edgeId","from","to","relation","semanticKey","certainty","provenance","attrs"],ee=Object.freeze({finding:["findingId"],feature:["name"],route:["path"],surface:["surfaceId"],component:["symbolKey","route"],symbol:["symbolKey"],query:["readId"],"api-resource":["endpoint"],mutation:["mutationId"],"cache-key":["cacheKeyId"],family:["familyId"],"truth-subject":["truthSubjectId"],principal:["principalId"],context:["contextId"],invariant:["invariantId"],flow:["flowId"],observation:["observationId"],"workflow-transition":["transitionId"],provenance:["provenanceId"]}),te=Object.freeze({finding:["severity","findingKind","status"],feature:[],route:["file"],surface:["material","route","file","component","confidence","surfaceKind"],component:["name","file"],symbol:["name","file","exported","presentation"],query:["keyId","file","line","span","pattern","endpoint","family","familySource","confidence"],"api-resource":[],mutation:["material","file","line","hook","endpoint","family","familySource","confidence"],"cache-key":["material","sourceProvenance"],family:["material","family"],"truth-subject":["material","name"],principal:["material","name"],context:["material","kind","transition"],invariant:["material","name"],flow:["material","route"],observation:["material","status"],"workflow-transition":["fromRoute","toRoute"],provenance:["source","path","span","method","reason"]}),ke=Object.freeze({uses:["source"],invalidates:["operationId"],"direct-updates":["operationId"],"reads-via":["path"],"evidenced-by":["reason"]}),we=Object.freeze({uses:["reason"],invalidates:["operation"],"direct-updates":["operation"],"reads-via":["ownership"],"evidenced-by":["ownership"]}),G=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),S=(e,n)=>G(e)&&Object.keys(e).length===n.length&&n.every(s=>Object.hasOwn(e,s)),l=e=>{throw new TypeError(`semantic-graph-${e}`)},ne=e=>e.every((n,s)=>s===0||e[s-1]<=n),Ee=(e,n=s=>s)=>e.every((s,m)=>m===0||n(e[m-1])<n(s)),B=e=>e===null||typeof e=="string"&&e.length>=1&&e.length<=512&&!/[\n\r\u2028\u2029]/.test(e)&&!e.startsWith("/")&&!e.startsWith("\\")&&!/^[A-Za-z]:/.test(e)&&!e.split(/[\\/]/).includes(".."),Se=e=>e===null||S(e,["file","start","end","line","column"])&&B(e.file)&&typeof e.file=="string"&&Number.isSafeInteger(e.start)&&Number.isSafeInteger(e.end)&&e.start>=0&&e.end>e.start&&Number.isSafeInteger(e.line)&&e.line>=1&&Number.isSafeInteger(e.column)&&e.column>=1;function D(e,n=0){return n>24?!1:e===null||typeof e=="boolean"?!0:typeof e=="string"?e.length<=4096:typeof e=="number"?Number.isFinite(e)&&Math.abs(e)<=Number.MAX_SAFE_INTEGER:Array.isArray(e)?e.length<=256&&e.every(s=>D(s,n+1)):!G(e)||Object.keys(e).some(s=>/authorization|cookie|password|secret|payload|headers?/i.test(s)||s==="__proto__"||s==="constructor"||s==="prototype")?!1:Object.keys(e).length<=128&&Object.values(e).every(s=>D(s,n+1))}function re(e){Array.isArray(e)||l("provenance-order"),e.length>q&&l("unsafe-value"),Ee(e,v)||l("provenance-order");for(const n of e)(!S(n,["source","path","span","method","reason"])||!me.includes(n.source)||!B(n.path)||!Se(n.span)||!pe.includes(n.method)||n.reason!==null&&!Z.includes(n.reason))&&l("provenance")}function Oe(e){e?.artifactVersion===1&&l("legacy-artifact-version"),(!S(e,he)||e.artifactVersion!==2||!W.includes(e.kind)||!T.test(e.recordId)||!z.has(e.certainty)||!S(e.identity,ee[e.kind])||!S(e.attrs,te[e.kind]))&&l("node-shape"),(!D(e.identity)||!D(e.attrs))&&l("unsafe-value"),te[e.kind].includes("file")&&!B(e.attrs.file)&&l("unsafe-value"),re(e.provenance),e.recordId!==`graph:v2:node:${A({artifactVersion:2,kind:e.kind,identity:e.identity})}`&&l("node-id");for(const n of ee[e.kind]){const s=e.identity[n];(typeof s!="string"||!s)&&l("node-identity"),Ie.includes(n)&&!ve.test(s)&&l("node-domain-id"),n==="readId"&&!ge.test(s)&&l("node-read-id")}e.certainty==="unresolved"&&!e.provenance.some(({reason:n})=>n!==null)&&!Z.includes(e.attrs.reason)&&l("unresolved-reason")}function Ne(e){e?.artifactVersion===1&&l("legacy-artifact-version");const n=ke[e.relation]??[],s=we[e.relation]??[];(!S(e,be)||e.artifactVersion!==2||!Object.hasOwn(X,e.relation)||!ye.test(e.edgeId)||!T.test(e.from)||!T.test(e.to)||!z.has(e.certainty)||!S(e.semanticKey,n)||!S(e.attrs,s))&&l("edge-shape"),(!D(e.semanticKey)||!D(e.attrs))&&l("unsafe-value"),re(e.provenance),e.edgeId!==`graph:v2:edge:${A({artifactVersion:2,from:e.from,to:e.to,relation:e.relation,semanticKey:e.semanticKey})}`&&l("edge-id"),e.certainty==="unresolved"&&!e.provenance.some(({reason:m})=>m!==null)&&l("unresolved-reason"),e.relation==="evidenced-by"&&!ue.includes(e.semanticKey.reason)&&l("unresolved-reason")}const Ke=Object.freeze({source:"inventory",path:null,span:null,method:"provenance-cap",reason:null}),oe=e=>[...new Map(e.map(n=>[v(n),n])).values()],P=e=>{const n=ae(oe(e));return n.length<=q?n:ae(oe([...n.slice(0,q-1),{...Ke}]))},F=(e,n)=>P([...e,...n]),ae=e=>[...e].sort((n,s)=>j(v(n),v(s)));function _e({kind:e,identity:n,certainty:s,provenance:m,attrs:I}){return{artifactVersion:2,recordId:`graph:v2:node:${A({artifactVersion:2,kind:e,identity:n})}`,kind:e,identity:n,certainty:s,provenance:P(m),attrs:I}}function xe({from:e,to:n,relation:s,semanticKey:m,certainty:I,provenance:h,attrs:k}){return{artifactVersion:2,edgeId:`graph:v2:edge:${A({artifactVersion:2,from:e,to:n,relation:s,semanticKey:m})}`,from:e,to:n,relation:s,semanticKey:m,certainty:I,provenance:P(h),attrs:k}}function Re({nodes:e=[],edges:n=[]}={}){const s=e.map(i=>({...i,provenance:P(i.provenance)})).sort((i,E)=>j(i.recordId,E.recordId)),m=n.map(i=>({...i,provenance:P(i.provenance)})).sort((i,E)=>j(i.edgeId,E.edgeId)),I=[...s.filter(({certainty:i})=>i==="unresolved").map(({recordId:i})=>i),...m.filter(({certainty:i})=>i==="unresolved").map(({edgeId:i})=>i)].sort(j),h=s.length+m.length,k=I.length,x=h-k,O={artifact:"frontend-verify.semantic-graph",schemaVersion:2,coverage:{status:h===0?"unmeasured":k===0?"measured":x===0?"unmeasured":"partial",factsDiscovered:h,factsResolved:x,factsUnresolved:k,unresolvedIds:I},nodes:s,edges:m};return ie(O),O}function ie(e){(!S(e,["artifact","schemaVersion","coverage","nodes","edges"])||e.artifact!=="frontend-verify.semantic-graph"||e.schemaVersion!==2||!Array.isArray(e.nodes)||!Array.isArray(e.edges))&&l("root");const n=new Map;for(const i of e.nodes)Oe(i),n.has(i.recordId)&&l(v(n.get(i.recordId))===v(i)?"duplicate-node":"conflicting-node"),n.set(i.recordId,i);const s=new Map;for(const i of e.edges){Ne(i),s.has(i.edgeId)&&l(v(s.get(i.edgeId))===v(i)?"duplicate-edge":"conflicting-edge");const E=n.get(i.from),N=n.get(i.to),R=X[i.relation];(!E||!N)&&l("dangling-edge"),(!R.from.includes(E.kind)||!R.to.includes(N.kind))&&l("edge-endpoint-kind"),i.certainty!=="unresolved"&&(E.certainty==="unresolved"||N.certainty==="unresolved")&&l("resolved-edge-unresolved-endpoint"),s.set(i.edgeId,i)}ne(e.nodes.map(({recordId:i})=>i))||l("node-order"),ne(e.edges.map(({edgeId:i})=>i))||l("edge-order");const m=[...e.nodes.filter(({certainty:i})=>i==="unresolved").map(({recordId:i})=>i),...e.edges.filter(({certainty:i})=>i==="unresolved").map(({edgeId:i})=>i)].sort(j),I=e.nodes.length+e.edges.length,h=m.length,k={status:I===0?"unmeasured":h===0?"measured":h===I?"unmeasured":"partial",factsDiscovered:I,factsResolved:I-h,factsUnresolved:h};S(e.coverage,["status","factsDiscovered","factsResolved","factsUnresolved","unresolvedIds"])||l("coverage"),v(e.coverage.unresolvedIds)!==v(m)&&l("unresolved-ledger");const{unresolvedIds:x,...O}=e.coverage;return v(O)!==v(k)&&l("coverage"),e}const b=(e,n,s,m=null)=>e?[{source:"inventory",path:e,span:n?.column?n:null,method:s,reason:m}]:[],U=e=>z.has(e)?e:"unresolved",Ae=(e,n="no-resolvable-endpoint")=>e.confidence==="unresolved"?n:null,Me=e=>(e?.segments??[]).map(n=>n.kind==="literal"?JSON.stringify(n.value):`<${n.kind}${n.expression||n.name?":"+(n.expression??n.name):""}>`).join(","),se=(e,n)=>e.material.receiver?.resolution==="unresolved"||e.material.keyMatch==="unknown"||e.material.keyId&&J(n.get(e.material.keyId)?.material)==="unresolved"||e.material.predicate&&e.material.predicate.resolution!=="resolved"||Object.values(e.material.filters??{}).some(s=>G(s)&&s.resolution!=="resolved");function $e({routes:e=[],symbolIndex:n,cacheKeys:s=[],cacheOperations:m=[],reads:I=[],mutations:h=[],surfaces:k=[],ownershipEdges:x=[],unresolved:O=[],readOwnerById:i=new Map,mutationOwnerById:E=new Map}){const N=[],R=[],r=new Map,d=new Map,y=t=>{const a=_e(t),o=r.get(a.recordId);return o?((o.certainty!==a.certainty||v(o.attrs)!==v(a.attrs))&&l("builder-node-conflict"),o.provenance=F(o.provenance,a.provenance),o):(r.set(a.recordId,a),N.push(a),a)},f=t=>{const a=[r.get(t.from),r.get(t.to)].find(u=>u?.certainty==="unresolved"),o=xe(a&&t.certainty!=="unresolved"?{...t,certainty:"unresolved",provenance:F(t.provenance,a.provenance)}:t),c=d.get(o.edgeId);return c?((c.certainty!==o.certainty||v(c.attrs)!==v(o.attrs))&&l("builder-edge-conflict"),c.provenance=F(c.provenance,o.provenance),c):(d.set(o.edgeId,o),R.push(o),o)},V=new Map;for(const t of[...e].sort((a,o)=>String(a.path).localeCompare(String(o.path)))){const a=y({kind:"route",identity:{path:t.path},certainty:"exact",provenance:b(t.file??null,null,"route"),attrs:{file:t.file??null}});V.set(t.path,a)}const K=new Map;for(const t of n?.declarations??[]){const a=y({kind:"symbol",identity:{symbolKey:t.key},certainty:"exact",provenance:b(t.file,t.span??null,"symbol"),attrs:{name:t.name,file:t.file,exported:!!t.exported,presentation:!!t.presentation}});K.set(t.key,a)}for(const t of n?.uses??[]){const a=K.get(t.from),o=K.get(t.to);if(!a||!o)continue;const c=`${t.source.file}:${t.source.start}:${t.source.end}`;f({from:a.recordId,to:o.recordId,relation:"uses",semanticKey:{source:c},certainty:"resolved",provenance:b(t.source.file,t.source,"symbol-use"),attrs:{reason:null}})}for(const t of n?.unknownEdges??[]){const a=K.get(t.from);if(!a)continue;const o=`unknown:${A({from:t.from,source:t.source,reason:t.reason})}`,c=b(t.source.file,t.source,"symbol-use",t.reason),u=y({kind:"symbol",identity:{symbolKey:o},certainty:"unresolved",provenance:c,attrs:{name:"<unknown>",file:t.source.file,exported:!1,presentation:!1}});f({from:a.recordId,to:u.recordId,relation:"uses",semanticKey:{source:`${t.source.file}:${t.source.start}:${t.source.end}`},certainty:"unresolved",provenance:c,attrs:{reason:t.reason}})}const p=new Map;for(const t of s){const a=t.material.segments.find(u=>u.resolution==="unresolved")?.reason??null,o=t.material.segments.find(u=>u.origin)?.origin??t.provenance[0]?.origin??null,c=y({kind:"cache-key",identity:{cacheKeyId:t.id},certainty:a?"unresolved":"exact",provenance:b(o?.file,o,"cache-key",a),attrs:{material:t.material,sourceProvenance:t.provenance}});p.set(t.id,c)}const M=new Map;for(const t of[...new Set([...I.map(a=>a.family),...h.map(a=>a.family)].filter(Boolean))].sort()){const a={namespace:"coherence/family",version:1,endpointFamily:t},o=A(a),c=[...I.filter(g=>g.family===t).flatMap(g=>b(g.file,g.span,"query")),...h.filter(g=>g.family===t).flatMap(g=>b(g.file,null,"mutation"))],u=y({kind:"family",identity:{familyId:o},certainty:"exact",attrs:{material:a,family:t},provenance:P(c)});M.set(t,u)}const Y=new Map;for(const t of I){const a=Ae(t),o=y({kind:"query",identity:{readId:t.id},certainty:U(t.confidence),provenance:b(t.file,t.span,"query",a),attrs:{keyId:t.keyId,file:t.file,line:t.line,span:t.span,pattern:t.pattern,endpoint:t.endpoint,family:t.family,familySource:t.familySource,confidence:t.confidence}});Y.set(t.id,o);const c=K.get(i.get(t.id));c&&f({from:c.recordId,to:o.recordId,relation:"declares",semanticKey:{},certainty:o.certainty,provenance:o.provenance,attrs:{}});const u=p.get(t.keyId);if(u&&f({from:o.recordId,to:u.recordId,relation:"uses-key",semanticKey:{},certainty:o.certainty==="unresolved"||u.certainty==="unresolved"?"unresolved":"resolved",provenance:o.certainty==="unresolved"||u.certainty==="unresolved"?[...o.provenance,...u.provenance].sort((w,C)=>j(v(w),v(C))):o.provenance,attrs:{}}),t.endpoint){const w=y({kind:"api-resource",identity:{endpoint:t.endpoint},certainty:Q,provenance:o.provenance,attrs:{}});f({from:o.recordId,to:w.recordId,relation:"requests",semanticKey:{},certainty:o.certainty,provenance:o.provenance,attrs:{}})}const g=M.get(t.family);g&&f({from:o.recordId,to:g.recordId,relation:"reads",semanticKey:{},certainty:o.certainty,provenance:o.provenance,attrs:{}})}const H=new Map,ce=new Map(O.map(t=>[t.id,t]));for(const t of h){const a=t.confidence==="unresolved"?ce.get(t.id)?.reason??"no-resolvable-endpoint":null,o=b(t.file,null,"mutation",a),c=y({kind:"mutation",identity:{mutationId:t.id},certainty:U(t.confidence),provenance:o,attrs:{material:t.material,file:t.file,line:t.line,hook:t.hook??null,endpoint:t.endpoint,family:t.family,familySource:t.familySource,confidence:t.confidence}});H.set(t.id,c);const u=K.get(E.get(t.id));if(u)f({from:u.recordId,to:c.recordId,relation:"declares",semanticKey:{},certainty:c.certainty,provenance:o,attrs:{}});else{const w=t.file?b(t.file,null,"mutation","unattributed-mutation-owner"):[{source:"inventory",path:null,span:null,method:"mutation",reason:"unattributed-mutation-owner"}],C=y({kind:"symbol",identity:{symbolKey:`unattributed:${t.id}`},certainty:"unresolved",provenance:w,attrs:{name:"<unknown>",file:t.file||null,exported:!1,presentation:!1}});f({from:C.recordId,to:c.recordId,relation:"declares",semanticKey:{},certainty:"unresolved",provenance:w,attrs:{}})}if(t.endpoint){const w=y({kind:"api-resource",identity:{endpoint:t.endpoint},certainty:Q,provenance:o,attrs:{}});f({from:c.recordId,to:w.recordId,relation:"calls",semanticKey:{},certainty:c.certainty,provenance:o,attrs:{}})}const g=M.get(t.family);g&&f({from:c.recordId,to:g.recordId,relation:"writes",semanticKey:{},certainty:c.certainty,provenance:o,attrs:{}})}const $=new Map;for(const t of k){const a=y({kind:"surface",identity:{surfaceId:t.id},certainty:U(t.confidence),provenance:b(t.file,null,"surface"),attrs:{material:t.material,route:t.route,file:t.file,component:t.component,confidence:t.confidence,surfaceKind:t.kind}});$.set(t.id,a);const o=V.get(t.route);if(o&&f({from:o.recordId,to:a.recordId,relation:"contains-surface",semanticKey:{},certainty:a.certainty,provenance:a.provenance,attrs:{}}),t.component&&t.file){const c=`${t.file}#${t.component}`,u=y({kind:"component",identity:{symbolKey:c,route:t.route},certainty:a.certainty,provenance:a.provenance,attrs:{name:t.component,file:t.file}});o&&f({from:o.recordId,to:u.recordId,relation:"renders-through",semanticKey:{},certainty:a.certainty,provenance:a.provenance,attrs:{}}),f({from:u.recordId,to:a.recordId,relation:"realizes",semanticKey:{},certainty:a.certainty,provenance:a.provenance,attrs:{}})}}for(const t of x){const a=$.get(t.surfaceId);if(!a)continue;if(t.resolution==="resolved"){const g=Y.get(t.readId);g&&f({from:a.recordId,to:g.recordId,relation:"reads-via",semanticKey:{path:t.path},certainty:"resolved",provenance:b(t.source.file,t.source,"symbol-traversal"),attrs:{ownership:t}});continue}const o=b(t.source.file,t.source,"symbol-traversal",t.reason),c=A({kind:"ownership",surfaceId:t.surfaceId,source:t.source,reason:t.reason,path:t.path}),u=y({kind:"provenance",identity:{provenanceId:c},certainty:"unresolved",provenance:o,attrs:o[0]});f({from:a.recordId,to:u.recordId,relation:"evidenced-by",semanticKey:{reason:t.reason},certainty:"unresolved",provenance:o,attrs:{ownership:t}})}for(const t of k){const a=$.get(t.id);for(const o of t.families??[]){const c=M.get(o);a&&c&&f({from:a.recordId,to:c.recordId,relation:"renders",semanticKey:{},certainty:a.certainty,provenance:a.provenance,attrs:{}})}}const de=new Map(m.map(t=>[t.id,t]));for(const t of h){const a=H.get(t.id);for(const o of t.operationIds??[]){const c=de.get(o);if(!a||!c)continue;const u=c.material.keyId?[p.get(c.material.keyId)].filter(Boolean):[...p.values()],g=c.material.effects.some(({kind:_})=>_==="update")?"direct-updates":"invalidates",w=se(c,new Map(s.map(_=>[_.id,_])))?c.material.receiver.reason??"dynamic-key":null,C=b(c.material.sourceRef.file,null,"cache-operation",w);for(const _ of u)f({from:a.recordId,to:_.recordId,relation:g,semanticKey:{operationId:o},certainty:w||_.certainty==="unresolved"?"unresolved":"resolved",provenance:!w&&_.certainty==="unresolved"?_.provenance:C,attrs:{operation:c}})}}return Re({nodes:N,edges:R})}function qe(e){ie(e);const n=new Map(e.nodes.map(r=>[r.recordId,r])),s=e.nodes.filter(({kind:r})=>r==="cache-key").map(r=>({id:r.identity.cacheKeyId,material:r.attrs.material,provenance:r.attrs.sourceProvenance})).sort((r,d)=>r.id.localeCompare(d.id)),m=e.nodes.filter(({kind:r})=>r==="query").map(r=>({id:r.identity.readId,...r.attrs})).sort((r,d)=>r.id.localeCompare(d.id)),I=new Map;for(const r of e.edges.filter(({relation:d})=>d==="invalidates"||d==="direct-updates")){const d=r.attrs.operation,y=I.get(d.id);y&&v(y)!==v(d)&&l("operation-conflict"),I.set(d.id,d)}const h=[...I.values()].sort((r,d)=>r.id.localeCompare(d.id)),k=e.nodes.filter(({kind:r})=>r==="mutation").map(r=>({id:r.identity.mutationId,...r.attrs,operationIds:[...new Set(e.edges.filter(d=>d.from===r.recordId&&(d.relation==="invalidates"||d.relation==="direct-updates")).map(d=>d.semanticKey.operationId))].sort(),writes:r.attrs.family?[{pattern:{segments:[{kind:"literal",value:r.attrs.family}]}}]:[]})).sort((r,d)=>r.id.localeCompare(d.id)),x=e.edges.filter(({relation:r})=>r==="reads-via"||r==="evidenced-by").map(r=>r.attrs.ownership).sort((r,d)=>JSON.stringify(r).localeCompare(JSON.stringify(d))),O=e.nodes.filter(({kind:r})=>r==="surface").map(r=>{const d=e.edges.filter(f=>f.from===r.recordId&&f.relation==="reads-via").map(f=>n.get(f.to).identity.readId).sort(),y=e.edges.filter(f=>f.from===r.recordId&&f.relation==="renders").map(f=>n.get(f.to).attrs.family).sort();return{id:r.identity.surfaceId,material:r.attrs.material,route:r.attrs.route,file:r.attrs.file,component:r.attrs.component,readIds:d,families:y,confidence:r.attrs.confidence,kind:r.attrs.surfaceKind}}).sort((r,d)=>r.id.localeCompare(d.id)),i=new Map(s.map(r=>[r.id,r])),E=new Map(m.map(r=>[r.id,r])),N=new Map(h.map(r=>[r.id,r])),R=e.nodes.filter(({kind:r})=>r==="family").map(r=>{const d=r.attrs.family,y=m.filter(p=>p.family===d),f=k.filter(p=>p.family===d),V=O.filter(p=>p.families.includes(d)),K=f.flatMap(p=>p.operationIds.map(M=>N.get(M)).filter(Boolean));return{id:r.identity.familyId,material:r.attrs.material,family:d,mutationIds:f.map(({id:p})=>p).sort(),readIds:y.map(({id:p})=>p).sort(),surfaceIds:V.map(({id:p})=>p).sort(),keyTerms:[...new Set(y.map(p=>Me(p.pattern)))].sort(),invalidations:K.length,invalidationsUnresolved:K.filter(p=>se(p,i)).length,readsUnresolvedKey:y.filter(p=>J(p.pattern)==="unresolved").length}}).sort((r,d)=>r.family.localeCompare(d.family));return{cacheKeys:s,cacheOperations:h,reads:m,mutations:k,surfaces:O,ownershipEdges:x,resourceFamilies:R,operationReadPairs:fe(N,E,i)}}export{te as ATTR_KEYS,z as CERTAINTIES,Ie as DOMAIN_ID_FIELDS,we as EDGE_ATTR_FIELDS,X as EDGE_ENDPOINTS,ue as EVIDENCED_BY_REASONS,Ve as GRAPH_ERROR_CODES,pe as GRAPH_PROVENANCE_METHODS,me as GRAPH_PROVENANCE_SOURCES,Z as GRAPH_UNRESOLVED_REASONS,ee as IDENTITY_KEYS,W as NODE_KINDS,q as PROVENANCE_CAP,ke as SEMANTIC_KEY_FIELDS,be as TOP_EDGE_KEYS,he as TOP_NODE_KEYS,$e as buildSemanticGraph,xe as createGraphEdge,_e as createGraphNode,Re as finalizeSemanticGraph,qe as projectCoherenceGraph,ie as validateSemanticGraph};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createHash as de}from"node:crypto";import{canonicalize as o,jcsDigest as q}from"../jcs.mjs";import{deriveOperationReadPairs as Y,expectedCacheOperationEffects as le,OWNERSHIP_REASONS as fe,reduceCoverage as X,SURFACE_KINDS as pe}from"./contracts.mjs";import{projectCoherenceGraph as ue,validateSemanticGraph as he}from"./graph.mjs";const ye=Object.freeze(["cacheKeys","cacheOperations","reads","mutations","surfaces","ownershipEdges","resourceFamilies","operationReadPairs"]);function we(e){if(!e.graph)throw new TypeError("coherence-graph-required");he(e.graph);const a=ue(e.graph);for(const f of ye)if(o(a[f])!==o(e[f]??[]))throw new TypeError(`coherence-graph-view-conflict-${f}`);const d=e.coverage?.counts??{},l={keysDiscovered:a.cacheKeys.length,operationsDiscovered:a.cacheOperations.length,invalidationsDiscovered:a.cacheOperations.length,readCandidates:a.reads.length,operationReadPairsDiscovered:a.operationReadPairs.length,surfacesSuggested:a.surfaces.length,surfacesDeclared:a.surfaces.length,ownershipEdgesDiscovered:a.ownershipEdges.length};for(const[f,c]of Object.entries(l))if(d[f]!==c)throw new TypeError(`coherence-graph-count-conflict-${f}`);if((e.coverage?.unresolved??[]).some(f=>f?.kind!=="family-join")&&e.graph.coverage.status==="measured")throw new TypeError("coherence-graph-coverage-conflict")}const me=Object.freeze(["mutation","surface","target","family","principal","context","invariant","entity","flow","cache-key","cache-operation","observation-cell"]),L=new Set(me),D=/^[a-f0-9]{64}$/,Z=/^sha256:[a-f0-9]{64}$/,G=e=>Array.isArray(e)?"["+e.map(G).join(",")+"]":e&&typeof e=="object"?"{"+Object.keys(e).sort().map(a=>JSON.stringify(a)+":"+G(e[a])).join(",")+"}":JSON.stringify(e);function ee(e,a,d){return"sha256:"+de("sha256").update(G({kind:e,sourceRef:a,discriminator:d})).digest("hex")}function ge(e){if(!L.has(e))throw new TypeError(`unknown-coherence-identity-kind:${e}`)}function W(e,a=new Set,d=!1){if(!(e===null||typeof e=="string"||typeof e=="boolean")){if(typeof e=="number"){if(!Number.isFinite(e)||Math.abs(e)>Number.MAX_SAFE_INTEGER||!d&&!Number.isSafeInteger(e))throw new TypeError("unsafe-identity-number");return}if(typeof e!="object")throw new TypeError("non-jcs-identity-value");if(a.has(e))throw new TypeError("cyclic-identity-material");if(a.add(e),Array.isArray(e))for(const l of e)W(l,a,d);else{const l=Object.getPrototypeOf(e);if(l!==Object.prototype&&l!==null)throw new TypeError("non-jcs-identity-object");for(const s of Object.values(e))W(s,a,d)}a.delete(e)}}function K(e,a){if(ge(e),!a||typeof a!="object"||Array.isArray(a))throw new TypeError("coherence-identity-semantic-object-required");if(Object.hasOwn(a,"namespace")||Object.hasOwn(a,"version"))throw new TypeError("coherence-identity-brand-is-reserved");W(a,new Set,e==="cache-key"||e==="cache-operation");const d={namespace:`coherence/${e}`,version:1,...a};return{id:q(d),material:d}}function B(e,a){return K("context",{kind:e,transition:a})}const ve=Object.freeze(["field","type","source","attribute","locale","timezone","currency","scale","inputUnit","canonicalUnit","factor","optional_on_summary"]);function Ee(e,a){M(e,"flow");const d=Object.fromEntries(ve.filter(l=>Object.hasOwn(a?.representation??{},l)).map(l=>[l,a.representation[l]]));return K("target",{flow:e,route:a?.route??null,transition:a?.transition??null,role:a?.role??null,representation:d})}function M(e,a=null){if(!e||typeof e!="object"||Array.isArray(e)||!D.test(e.id??""))throw new TypeError("coherence-identity-shape");const d=e.material;if(!d||typeof d!="object"||Array.isArray(d))throw new TypeError("coherence-identity-material");if(d.version!==1)throw new TypeError("coherence-identity-version");const l=typeof d.namespace=="string"&&d.namespace.startsWith("coherence/")?d.namespace.slice(10):null;if(!L.has(l))throw new TypeError("coherence-identity-namespace");if(a!==null&&l!==a)throw new TypeError("coherence-identity-namespace-mismatch");if(W(d,new Set,l==="cache-key"||l==="cache-operation"),q(d)!==e.id)throw new TypeError("coherence-identity-digest-mismatch");return e}function te(e,a=[]){const d=new Map,l=new Map;for(const s of e??[]){if(!s||typeof s!="object")throw new TypeError("coherence-identity-shape");const f=o(s.material),c=d.get(s.id);if(c===f)throw new TypeError("duplicate-coherence-identity");if(c!==void 0)throw new TypeError("coherence-identity-storage-conflict");const w=l.get(f);if(w!==void 0&&w!==s.id)throw new TypeError("coherence-identity-semantic-conflict");M(s),d.set(s.id,f),l.set(f,s.id)}for(const s of a??[]){const f=e.find(w=>w.id===s?.fromId),c=e.find(w=>w.id===s?.toId);if(!f||!c)throw new TypeError("dangling-coherence-identity-relation");try{M(f,s.fromKind),M(c,s.toKind)}catch(w){throw String(w?.message).includes("namespace")?new TypeError("coherence-identity-relation-namespace"):w}}return!0}function $(e,a){const d=new Map;for(const l of e){M(l,a);const s=o(l.material);if(d.has(l.id))throw new TypeError(d.get(l.id)===s?"duplicate-coherence-identity":"coherence-identity-storage-conflict");d.set(l.id,s)}return new Map(e.map(l=>[l.id,l]))}const U=(e,a)=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===a.length&&a.every(d=>Object.hasOwn(e,d)),re=e=>U(e,["file","start","end","line","column"])&&typeof e.file=="string"&&Number.isSafeInteger(e.start)&&Number.isSafeInteger(e.end)&&e.start>=0&&e.end>e.start&&Number.isSafeInteger(e.line)&&e.line>=1&&Number.isSafeInteger(e.column)&&e.column>=1,H=e=>U(e,["kind","expression","ownerSymbol","targetSymbol","origin","resolutionPath","resolution","reason"])&&["parameter","wildcard","call","unknown"].includes(e.kind)&&typeof e.expression=="string"&&[null,"string"].includes(e.ownerSymbol===null?null:typeof e.ownerSymbol)&&[null,"string"].includes(e.targetSymbol===null?null:typeof e.targetSymbol)&&re(e.origin)&&e.resolution==="unresolved"&&typeof e.reason=="string"&&Array.isArray(e.resolutionPath)&&e.resolutionPath.length<=26&&e.resolutionPath.every(a=>typeof a=="string"),Ie=e=>H(e)||e?.kind==="literal"&&(U(e,["kind","value"])||U(e,["kind","value","origin"])&&re(e.origin))&&Object.hasOwn(e,"value");function ne(e){for(const a of e.values()){if(!Array.isArray(a.material.segments))throw new TypeError("coherence-cache-key-segments");for(const d of a.material.segments)if(d?.kind==="literal"){if(!Object.hasOwn(d,"value")||Object.keys(d).some(l=>!["kind","value"].includes(l)))throw new TypeError("coherence-cache-key-literal")}else if(!H(d))throw new TypeError("coherence-cache-key-symbolic")}return e}function oe(e,a){const d=new Set,l=new Set(["invalidateQueries","refetchQueries","resetQueries","removeQueries","setQueryData","setQueriesData","clear"]),s=new Set(["invalidate","refetch","reset","remove","update","clear-query-cache","clear-mutation-cache"]);for(const f of e.values()){const c=f.material,w=c.sourceRef;if(!U(c,["namespace","version","sourceRef","receiver","operation","keyId","keyMatch","exact","predicate","filters","effects"]))throw new TypeError("coherence-cache-operation-kind");if(!U(w,["file","start","end"])||typeof w.file!="string"||!Number.isSafeInteger(w.start)||!Number.isSafeInteger(w.end)||w.start<0||w.end<=w.start)throw new TypeError("coherence-cache-operation-source-span");const r=`${w.file}:${w.start}:${w.end}`;if(d.has(r))throw new TypeError("duplicate-coherence-cache-operation-occurrence");if(d.add(r),!l.has(c.operation)||!["all","prefix","exact","unknown"].includes(c.keyMatch)||![!0,!1,null].includes(c.exact))throw new TypeError("coherence-cache-operation-kind");if(!U(c.receiver,["expression","ownerSymbol","targetSymbol","kind","resolution","reason"])||typeof c.receiver.expression!="string"||![null,"string"].includes(c.receiver.ownerSymbol===null?null:typeof c.receiver.ownerSymbol)||![null,"string"].includes(c.receiver.targetSymbol===null?null:typeof c.receiver.targetSymbol)||!["query-client","query-cache","unknown"].includes(c.receiver.kind)||!["resolved","unresolved"].includes(c.receiver.resolution)||(c.receiver.resolution==="resolved"?c.receiver.kind==="unknown"||c.receiver.reason!==null:c.receiver.kind!=="unknown"||c.receiver.reason!=="unsupported-client"))throw new TypeError("coherence-cache-operation-receiver");if(c.keyId===null?c.keyMatch!=="all":!a.has(c.keyId))throw new TypeError("dangling-coherence-cache-operation-key");if(c.keyId===null&&c.exact!==!1||c.keyId!==null&&(c.keyMatch==="all"||c.keyMatch==="exact"!=(c.exact===!0)||c.keyMatch==="unknown"!=(c.exact===null))||c.operation==="setQueryData"&&(c.keyMatch!=="exact"||c.exact!==!0)||c.operation==="clear"&&(c.keyId!==null||c.keyMatch!=="all"))throw new TypeError("coherence-cache-operation-kind");if(c.predicate!==null&&!Ie(c.predicate))throw new TypeError("coherence-cache-operation-predicate");const m={type:new Set(["active","inactive","all"]),stale:new Set([!0,!1]),fetchStatus:new Set(["fetching","paused","idle"]),refetchType:new Set(["active","inactive","all","none"])};if(!c.filters||typeof c.filters!="object"||Array.isArray(c.filters)||Object.entries(c.filters).some(([y,I])=>!m[y]||!m[y].has(I)&&!H(I)))throw new TypeError("coherence-cache-operation-filter");if(c.operation!=="invalidateQueries"&&Object.hasOwn(c.filters,"refetchType")||["clear","setQueryData"].includes(c.operation)&&(c.predicate!==null||Object.keys(c.filters).length))throw new TypeError("coherence-cache-operation-filter");if(!Array.isArray(c.effects)||c.effects.some(y=>!U(y,["kind","scope"])||!s.has(y.kind)||typeof y.scope!="string"))throw new TypeError("coherence-cache-operation-effect");if(c.operation!=="clear"&&c.receiver.resolution==="resolved"&&c.receiver.kind!=="query-client")throw new TypeError("coherence-cache-operation-receiver");if(o(c.effects)!==o(le(c)))throw new TypeError("coherence-cache-operation-effect")}return e}function Se(e){if([1,2,3].includes(e?.schemaVersion))return{current:!1};if(e?.schemaVersion!==4)throw new TypeError("unsupported-coherence-ir-version");for(const t of["mutations","surfaces","resourceFamilies","cacheKeys","cacheOperations","reads","invalidations","operationReadPairs"])if(!Array.isArray(e[t]))throw new TypeError(`coherence-ir-${t}-required`);const a=$(e.mutations,"mutation"),d=$(e.surfaces,"surface"),l=$(e.resourceFamilies,"family"),s=$(e.cacheKeys,"cache-key"),f=$(e.cacheOperations,"cache-operation");ne(s),oe(f,s);const c=new Set;for(const t of a.values()){const h=t.operationIds??[];if(new Set(h).size!==h.length||o(h)!==o([...h].sort())||h.some(O=>!f.has(O)))throw new TypeError("dangling-coherence-cache-operation-owner");for(const O of h)c.add(O)}if(c.size!==f.size)throw new TypeError("unowned-coherence-cache-operation");if((e.invalidations??[]).length)throw new TypeError("coherence-top-level-invalidation-authority");const w=new Map;for(const t of e.reads??[]){if(!Z.test(t?.id??""))throw new TypeError("coherence-read-identity-shape");if(w.has(t.id))throw new TypeError("duplicate-coherence-read-identity");const h=t.span??null;if(h!==null&&(h.file!==t.file||h.line!==t.line||!Number.isSafeInteger(h.start)||!Number.isSafeInteger(h.end)||h.start<0||h.end<=h.start||!Number.isSafeInteger(h.column)||h.column<1))throw new TypeError("coherence-read-source-span");const O=h??{file:t.file,line:t.line};if(t.id!==ee("read",O,t.pattern))throw new TypeError("coherence-read-identity-conflict");const V=(t.pattern?.segments??[]).map(F=>F.kind==="literal"?{kind:"literal",value:F.value}:F);if(!s.has(t.keyId)||o(s.get(t.keyId).material.segments)!==o(V))throw new TypeError("dangling-coherence-read-cache-key");w.set(t.id,t)}const r=e.operationReadPairs??[],m=new Set;for(const t of r){if(!f.has(t.operationId)||!w.has(t.readId)||t.id!==`${t.operationId}:${t.readId}`)throw new TypeError("dangling-coherence-operation-read-pair");if(m.has(t.id))throw new TypeError("duplicate-coherence-operation-read-pair");m.add(t.id)}const y=Y(f,w,s);if(o(r)!==o(y))throw new TypeError("coherence-operation-read-pair-derived-conflict");for(const t of a.values()){const h={namespace:"coherence/mutation",version:1,sourceRef:{file:t.file,line:t.line},endpoint:t.endpoint??null};if(o(t.material)!==o(h))throw new TypeError("coherence-mutation-material-conflict")}for(const t of d.values()){const h={namespace:"coherence/surface",version:1,route:t.route,component:t.component??null,sourceRef:{file:t.file??null,line:0}};if(o(t.material)!==o(h))throw new TypeError("coherence-surface-material-conflict");if(!pe.includes(t.kind))throw new TypeError("unknown-coherence-surface-kind");if(t.kind==="route"&&(t.component!==null||t.confidence!=="coarse"||(t.readIds??[]).length||(t.families??[]).length))throw new TypeError("coherence-surface-kind-evidence");if(t.kind!=="route"&&(typeof t.component!="string"||!t.component||typeof t.file!="string"||!t.file))throw new TypeError("coherence-surface-kind-evidence")}for(const t of l.values())if(t.material.endpointFamily!==t.family)throw new TypeError("coherence-family-material-conflict");for(const t of e.candidates??[]){if(t.mutationId&&!a.has(t.mutationId))throw new TypeError("dangling-coherence-candidate-mutation");for(const h of t.surfaceIds??[])if(!d.has(h))throw new TypeError("dangling-coherence-candidate-surface")}const I=new Map,E=new Set;let C=0,j=0;for(const t of e.ownershipEdges??[]){const h=d.get(t?.surfaceId);if(!h)throw new TypeError("dangling-coherence-ownership-surface");if(h.kind==="route")throw new TypeError("coherence-surface-kind-evidence");if(!t.source||typeof t.source.file!="string"||!Number.isSafeInteger(t.source.start)||!Number.isSafeInteger(t.source.end)||t.source.start<0||t.source.end<=t.source.start||!Number.isSafeInteger(t.source.line)||t.source.line<1||!Number.isSafeInteger(t.source.column)||t.source.column<1)throw new TypeError("coherence-ownership-source-span");if(t.provenance?.adapter!=="structural-js"||t.provenance?.method!=="symbol-traversal")throw new TypeError("coherence-ownership-provenance");if(!Array.isArray(t.path)||t.path.length<2||t.path.length>26||t.path.some(O=>typeof O!="string"||!O))throw new TypeError("coherence-ownership-symbol-path");if(t.path[0]!==`${h.file}#${h.component}`)throw new TypeError("coherence-ownership-path-start");if(t.resolution==="resolved"){if(t.confidence!=="resolved"||t.reason!==null||!w.has(t.readId))throw new TypeError("coherence-ownership-resolved-conflict");if(o(t.source)!==o(w.get(t.readId).span))throw new TypeError("coherence-ownership-read-span-conflict");if(t.path.at(-1)!==`read:${t.readId}`)throw new TypeError("coherence-ownership-path-end");const O=`${t.surfaceId}:${t.readId}`;if(E.has(O))throw new TypeError("duplicate-coherence-ownership-edge");E.add(O),C++,I.set(t.surfaceId,[...I.get(t.surfaceId)??[],t.readId])}else if(t.resolution==="unresolved"){if(t.confidence!=="unresolved"||t.readId!==null||!fe.includes(t.reason))throw new TypeError("coherence-ownership-unresolved-conflict");if(t.path.at(-1)!=="unknown-export")throw new TypeError("coherence-ownership-path-end");j++}else throw new TypeError("coherence-ownership-resolution")}for(const t of d.values()){const h=[...new Set(I.get(t.id)??[])].sort();if(o(t.readIds??[])!==o(h))throw new TypeError("coherence-surface-read-projection-conflict")}const u=e.coverage?.counts??{};if(u.ownershipEdgesDiscovered!==C+j||u.ownershipEdgesResolved!==C||u.ownershipEdgesUnresolved!==j)throw new TypeError("coherence-ownership-count-conflict");const R=t=>[...t].sort((h,O)=>o(h).localeCompare(o(O))),n=R((e.ownershipEdges??[]).filter(t=>t.resolution==="unresolved").map(t=>({id:t.surfaceId,file:t.source.file,line:t.source.line,kind:"ownership",reason:t.reason}))),p=R((e.coverage?.unresolved??[]).filter(t=>t.kind==="ownership"));if(o(p)!==o(n))throw new TypeError("coherence-ownership-unresolved-ledger");if(j&&e.coverage?.status==="measured")throw new TypeError("coherence-ownership-status-conflict");const b=(e.coverage?.unresolved??[]).filter(t=>t.kind==="write"),g=b.filter(t=>t.reason==="ambiguous-mutation-occurrence"),N=new Map;for(const t of g)N.set(t.id,[...N.get(t.id)??[],t]);for(const[t,h]of N){const O=a.get(t);if(!O||O.endpoint==null||O.confidence!=="unresolved"||O.family!==null||(O.writes??[]).length)throw new TypeError("coherence-ambiguous-mutation-join");if((e.resourceFamilies??[]).some(S=>(S.mutationIds??[]).includes(t)))throw new TypeError("coherence-ambiguous-mutation-join");if((e.candidates??[]).some(S=>S.mutationId===t))throw new TypeError("coherence-ambiguous-mutation-candidate");if(h.length<2)throw new TypeError("coherence-ambiguous-mutation-ledger");const V=h.map(S=>S.span);if(h.some(S=>S.file!==O.file||S.line!==O.line||!S.span||S.span.file!==O.file||S.span.line!==O.line||!Number.isSafeInteger(S.span.start)||!Number.isSafeInteger(S.span.end)||S.span.start<0||S.span.end<=S.span.start||!Number.isSafeInteger(S.span.column)||S.span.column<1))throw new TypeError("coherence-ambiguous-mutation-ledger");const F=V.map(S=>`${S.file}:${S.start}:${S.end}`);if(new Set(F).size!==h.length)throw new TypeError("coherence-ambiguous-mutation-ledger");const ce=[...V].sort((S,Q)=>S.file.localeCompare(Q.file)||S.line-Q.line||S.start-Q.start||S.end-Q.end);if(o(V)!==o(ce))throw new TypeError("coherence-ambiguous-mutation-ledger")}for(const t of a.values())if(t.confidence==="unresolved"&&t.endpoint!=null&&!N.has(t.id))throw new TypeError("coherence-ambiguous-mutation-ledger");const z=R(b.filter(t=>t.reason!=="ambiguous-mutation-occurrence")),i=R([...a.values()].filter(t=>t.confidence==="unresolved"&&t.endpoint==null).map(t=>({id:t.id,file:t.file,line:t.line,kind:"write",reason:"no-resolvable-endpoint"})));if(o(z)!==o(i))throw new TypeError("coherence-mutation-unresolved-ledger");const k=[...a.values()].filter(t=>t.confidence!=="unresolved").length,x=i.length+g.length;if(u.ambiguousMutationOccurrences!==g.length||u.writesResolved!==k||u.writesUnresolved!==x||u.writeCandidates!==k+x+u.writesNonWrite)throw new TypeError("coherence-mutation-count-conflict");const A=[...s.values()].filter(t=>t.material.segments.some(h=>h.kind!=="literal"&&h.resolution!=="resolved")).length,T=[...f.values()].filter(t=>t.material.receiver.resolution==="unresolved"||t.material.keyMatch==="unknown"||t.material.keyId&&s.get(t.material.keyId).material.segments.some(h=>h.kind!=="literal"&&h.resolution!=="resolved")||t.material.predicate&&t.material.predicate.resolution!=="resolved"||Object.values(t.material.filters).some(h=>h&&typeof h=="object"&&h.resolution!=="resolved")).length,v=r.filter(t=>t.keyCoverage==="covered"&&t.effectCoverage==="covered").length,P=r.filter(t=>t.keyCoverage==="unresolved"||t.effectCoverage==="unresolved").length;if(u.keysDiscovered!==s.size||u.keysResolved!==s.size-A||u.keysUnresolved!==A)throw new TypeError("coherence-cache-key-count-conflict");if(u.operationsDiscovered!==f.size||u.operationsResolved!==f.size-T||u.operationsUnresolved!==T||u.invalidationsDiscovered!==f.size||u.invalidationsResolved!==f.size-T||u.invalidationsUnresolved!==T)throw new TypeError("coherence-cache-operation-count-conflict");if(u.operationReadPairsDiscovered!==r.length||u.operationReadPairsCovered!==v||u.operationReadPairsUnresolved!==P||u.operationReadPairsNotCovered!==r.length-v-P)throw new TypeError("coherence-operation-read-pair-count-conflict");const _=u.writeCandidates===0||u.writesResolved===0?"unmeasured":u.writesUnresolved||u.readsUnresolved||u.keysUnresolved||u.operationsUnresolved||u.operationReadPairsUnresolved||u.invalidationsUnresolved||u.ownershipEdgesUnresolved||u.writersWithNoReaderSurface?"partial":"measured",se=_!=="unmeasured"?null:u.writeCandidates===0?"no-write-candidates":"no-writes-resolved";if(e.coverage?.status!==_||e.coverage?.reason!==se)throw new TypeError("coherence-coverage-status-conflict");return we(e),{current:!0}}function ie(e){if([1,2].includes(e?.schema_version))return{current:!1};if(e?.schema_version!==3)throw new TypeError("unsupported-verify-crud-version");const a=new Set,d=new Set;for(const l of e.flows??[]){if(M(l.identity,"flow"),a.has(l.identity.id))throw new TypeError("duplicate-coherence-flow-identity");if(a.add(l.identity.id),(l.identity.material.route??null)!==(l.route??null)||(l.identity.material.declaredEndpoint??null)!==(l.declared_endpoint??null))throw new TypeError("typed-flow-label-conflict");const s=l.crosscheck;if(M(s?.mutationIdentity,"mutation"),M(s?.entityIdentity,"entity"),M(s?.writerIdentity,"principal"),s.entityIdentity.material.name!==s.entity)throw new TypeError("typed-entity-label-conflict");if(s.writerIdentity.material.name!==s.writer)throw new TypeError("typed-writer-label-conflict");if(s.causal){if(typeof s.causal!="object"||Array.isArray(s.causal)||Object.keys(s.causal).sort().join("\0")!==["entity","effect","convergence"].sort().join("\0"))throw new TypeError("typed-causal-contract-closed");if(s.causal.entity!==s.entity)throw new TypeError("typed-causal-entity-conflict");if(!s.causal.effect||typeof s.causal.effect!="object"||Array.isArray(s.causal.effect)||Object.keys(s.causal.effect).sort().join("\0")!==["kind","field"].sort().join("\0"))throw new TypeError("typed-causal-effect-closed");const r=s.causal.convergence?.deadlineMs;if(!s.causal.convergence||typeof s.causal.convergence!="object"||Array.isArray(s.causal.convergence)||Object.keys(s.causal.convergence).sort().join("\0")!==["deadlineMs"].sort().join("\0"))throw new TypeError("typed-causal-convergence-closed");if(!Number.isInteger(r)||r<1||r>12e4)throw new TypeError("typed-causal-deadline-invalid");if(!["field-change","version-advance"].includes(s.causal.effect?.kind)||typeof s.causal.effect?.field!="string"||!s.causal.effect.field)throw new TypeError("typed-causal-effect-invalid")}const f=new Map,c=new Set;for(const r of s.observers??[]){if(M(r.identity,"principal"),r.identity.material.name!==r.persona)throw new TypeError("typed-observer-label-conflict");if(f.has(r.persona))throw f.get(r.persona)!==r.expect?new TypeError("conflicting-typed-observer-expectation"):new TypeError("duplicate-typed-observer-persona");if(c.has(r.identity.id))throw new TypeError("duplicate-typed-observer-principal");f.set(r.persona,r.expect),c.add(r.identity.id)}const w=new Set;for(const r of s.targets??[]){if(M(r.identity,"target"),M(r.surfaceMatch?.surface,"surface"),d.has(r.identity.id))throw new TypeError("duplicate-coherence-target-identity");if(d.add(r.identity.id),w.has(r.surfaceMatch.surface.id))throw new TypeError("ambiguous-coherence-target-surface-relation");if(w.add(r.surfaceMatch.surface.id),!r.surfaceMatch?.evidence?.source||r.surfaceMatch.evidence.kind!=="declared")throw new TypeError("typed-target-surface-evidence-required");const m=Ee(l.identity,r);if(o(r.identity)!==o(m))throw new TypeError("typed-target-material-conflict");if(r.surfaceMatch.surface.material.route!==r.route)throw new TypeError("typed-target-surface-route-conflict")}}return{current:!0}}function Ce(e){if(e?.schemaVersion===1)return{current:!1};if(e?.schemaVersion!==2)throw new TypeError("unsupported-coherence-plan-version");for(const n of["cacheKeys","reads","mutations","surfaces","operations","sideChannels","sideChannelIds","operationIds","obligations","obligationIds"])if(!Array.isArray(e[n]))throw new TypeError(`coherence-plan-${n}-required`);const a=n=>Number.isSafeInteger(n)&&n>=0;for(const n of["discovered","resolved","unresolved","planned","reached","compared","agreed"])if(!a(e.coverage?.[n]))throw new TypeError("typed-plan-count-shape");for(const n of["obligations","discovered","unresolved","mutations","surfaces","principals","contexts","invariants","operations","sideChannels","unresolvedSideChannels"])if(!a(e.universe?.[n]))throw new TypeError("typed-plan-count-shape");if(!a(e.plan?.rejected)||!a(e.plan?.unselected)||typeof e.plan?.budget!="number"||!Number.isFinite(e.plan.budget)||e.plan.budget<0)throw new TypeError("typed-plan-count-shape");const d=ne($(e.cacheKeys,"cache-key")),l=oe($(e.operations,"cache-operation"),d),s=new Map;for(const n of e.reads??[]){if(!Z.test(n?.id??"")||s.has(n.id))throw new TypeError(s.has(n?.id)?"duplicate-coherence-read-identity":"coherence-read-identity-shape");const p=n.span;if(!p||p.file!==n.file||p.line!==n.line||!Number.isSafeInteger(p.start)||!Number.isSafeInteger(p.end)||p.start<0||p.end<=p.start||!Number.isSafeInteger(p.column)||p.column<1)throw new TypeError("coherence-read-source-span");if(n.id!==ee("read",p,n.pattern))throw new TypeError("coherence-read-identity-conflict");const b=(n.pattern?.segments??[]).map(g=>g.kind==="literal"?{kind:"literal",value:g.value}:g);if(!d.has(n.keyId)||o(d.get(n.keyId).material.segments)!==o(b))throw new TypeError("dangling-coherence-read-cache-key");s.set(n.id,n)}const f=$(e.mutations??[],"mutation"),c=new Set;for(const n of f.values()){const p={namespace:"coherence/mutation",version:1,sourceRef:{file:n.file,line:n.line},endpoint:n.endpoint??null};if(o(n.material)!==o(p))throw new TypeError("coherence-mutation-material-conflict");const b=n.operationIds??[];if(new Set(b).size!==b.length||o(b)!==o([...b].sort())||b.some(g=>!l.has(g)))throw new TypeError("dangling-coherence-cache-operation-owner");for(const g of b)c.add(g)}if(c.size!==l.size)throw new TypeError("unowned-coherence-cache-operation");const w=$(e.surfaces??[],"surface");for(const n of w.values()){const p={namespace:"coherence/surface",version:1,route:n.route,component:n.component??null,sourceRef:{file:n.file??null,line:0}};if(o(n.material)!==o(p))throw new TypeError("coherence-surface-material-conflict");const b=n.readIds??[];if(new Set(b).size!==b.length||o(b)!==o([...b].sort())||b.some(g=>!s.has(g)))throw new TypeError("dangling-coherence-surface-read")}const r=[...l.keys()].sort();if(o(e.operationIds??[])!==o(r))throw new TypeError("typed-plan-operation-id-set-conflict");const m=Y(l,s,d);if(o(e.sideChannels??[])!==o(m))throw new TypeError("typed-plan-side-channel-derived-conflict");const y=new Map(m.map(n=>[n.id,n])),I=m.filter(n=>n.mandatory).map(n=>n.id);if(o(e.sideChannelIds??[])!==o(I))throw new TypeError("typed-plan-side-channel-id-set-conflict");const E=m.filter(n=>n.keyCoverage==="unresolved"||n.effectCoverage==="unresolved").length;if(e.universe?.mutations!==f.size||e.universe?.surfaces!==w.size||e.universe?.operations!==l.size||e.universe?.sideChannels!==m.length||e.universe?.unresolvedSideChannels!==E)throw new TypeError("typed-plan-side-channel-count-conflict");const C=(n,p)=>{const b=f.get(n),g=w.get(p);if(!b||!g)throw new TypeError("typed-obligation-endpoint-conflict");const N=new Set(b.operationIds),z=new Set(g.readIds),i=m.filter(k=>N.has(k.operationId)&&z.has(k.readId));return{operationIds:[...new Set(i.map(k=>k.operationId))].sort(),sideChannelIds:i.filter(k=>k.mandatory).map(k=>k.id),sideChannels:i,sideChannelStatus:X(i.map(k=>k.effectCoverage))}},j=new Set;for(const n of e.obligationIds??[]){if(!D.test(n))throw new TypeError("typed-root-obligation-id-shape");if(j.has(n))throw new TypeError("duplicate-root-obligation-id");j.add(n)}if(j.size!==e.coverage?.resolved||j.size!==e.universe?.obligations)throw new TypeError("typed-root-obligation-count-conflict");if(e.coverage?.discovered!==e.coverage?.resolved+e.coverage?.unresolved)throw new TypeError("typed-plan-coverage-partition-conflict");if(e.coverage?.reached!==0||e.coverage?.compared!==0||e.coverage?.agreed!==0)throw new TypeError("typed-static-plan-runtime-count-conflict");if(e.universe?.discovered!==e.coverage?.discovered||e.universe?.unresolved!==e.coverage?.unresolved)throw new TypeError("typed-plan-universe-count-conflict");if(e.plan?.rejected!==e.plan?.unselected)throw new TypeError("typed-plan-unselected-count-conflict");const u=new Map;for(const n of e.obligations??[]){if(M(n,"observation-cell"),u.has(n.id))throw new TypeError("duplicate-root-obligation-record");const p=n.coordinates;if(o(n.material)!==o({namespace:"coherence/observation-cell",version:1,...p}))throw new TypeError("typed-obligation-coordinate-conflict");for(const[z,i]of[["mutation","mutation"],["surface","surface"],["principal","principal"],["context","context"],["invariant","invariant"]])M(p?.[z],i);if(p?.target?.id){if(M(p.target,"target"),M(p.target.material?.flow,"flow"),!n.flowIdentity||o(p.target.material.flow)!==o(n.flowIdentity))throw new TypeError("typed-obligation-target-flow-conflict")}else if(o(p?.target)!==o({status:"unresolved",reason:"declaration-target-not-joined"}))throw new TypeError("typed-obligation-target-invalid");if(n.flowIdentity&&M(n.flowIdentity,"flow"),n.mutationId!==p.mutation.id||n.surfaceId!==p.surface.id||n.principalId!==p.principal.id||n.principal!==p.principal.material.name||n.context!==p.context.material.kind||n.invariant!==p.invariant.material.name||n.expectation!==p.expectation||n.route!==p.surface.material.route)throw new TypeError("typed-obligation-scalar-coordinate-conflict");if(p.context.material.kind==="fresh-context"&&p.expectation!=="visible")throw new TypeError("typed-fresh-expectation-conflict");const b=f.get(n.mutationId),g=w.get(n.surfaceId);if(!b||!g||o(p.mutation)!==o({id:b.id,material:b.material})||o(p.surface)!==o({id:g.id,material:g.material}))throw new TypeError("typed-obligation-endpoint-conflict");const N=C(n.mutationId,n.surfaceId);for(const z of n.sideChannels??[])if(!y.has(z.id))throw new TypeError("typed-obligation-side-channel-conflict");if(o({operationIds:n.operationIds,sideChannelIds:n.sideChannelIds,sideChannels:n.sideChannels,sideChannelStatus:n.sideChannelStatus})!==o(N)||n.mandatory!==(!!p.target?.id||N.sideChannelIds.length>0))throw new TypeError("typed-obligation-side-channel-conflict");u.set(n.id,n)}if(u.size!==j.size||o([...u.keys()].sort())!==o([...j].sort()))throw new TypeError("typed-root-obligation-id-set-conflict");const R=new Set;for(const n of e.plan?.selected??[]){M(n.mutationIdentity,"mutation");const p=f.get(n.mutationId);if(!p||o(n.mutationIdentity)!==o({id:p.id,material:p.material}))throw new TypeError("typed-journey-mutation-conflict");n.flowIdentity&&M(n.flowIdentity,"flow");const b=new Set;for(const g of n.targets??[]){M(g.surfaceIdentity,"surface");const N=w.get(g.surfaceId);if(!N||o(g.surfaceIdentity)!==o({id:N.id,material:N.material}))throw new TypeError("typed-plan-surface-conflict");const z=new Set;for(const v of g.obligationIds??[]){if(!D.test(v)||z.has(v))throw new TypeError("typed-target-obligation-id-set-conflict");z.add(v)}const i=new Set((g.obligations??[]).map(v=>v.id));if(i.size!==(g.obligations??[]).length||o([...z].sort())!==o([...i].sort()))throw new TypeError("typed-target-obligation-id-set-conflict");for(const v of g.obligations??[]){if(R.has(v.id))throw new TypeError("duplicate-coherence-observation-cell");R.add(v.id),b.add(v.id);const P=u.get(v.id);if(!P)throw new TypeError("dangling-selected-obligation-id");if(o(P)!==o(v))throw new TypeError("typed-selected-obligation-copy-conflict");const _=v.coordinates;if(_?.target?.id&&(!n.flowIdentity||o(_.target.material.flow)!==o(n.flowIdentity)))throw new TypeError("typed-obligation-target-flow-conflict");if(_.mutation.id!==n.mutationIdentity.id||_.surface.id!==g.surfaceIdentity.id)throw new TypeError("typed-obligation-endpoint-conflict");if(v.flowIdentity&&o(v.flowIdentity)!==o(n.flowIdentity))throw new TypeError("typed-obligation-flow-conflict")}const k=[...new Set((g.obligations??[]).flatMap(v=>v.operationIds))].sort(),x=[...new Set((g.obligations??[]).flatMap(v=>v.sideChannelIds))].sort(),A=[...new Map((g.obligations??[]).flatMap(v=>v.sideChannels).map(v=>[v.id,v])).values()].sort((v,P)=>v.id.localeCompare(P.id)),T=X(A.map(v=>v.effectCoverage));if(o(g.operationIds)!==o(k)||o(g.sideChannelIds)!==o(x)||o(g.sideChannels)!==o(A)||g.sideChannelStatus!==T)throw new TypeError("typed-target-side-channel-conflict")}if(n.covers!==b.size)throw new TypeError("typed-journey-covers-conflict")}if(R.size!==e.coverage?.planned)throw new TypeError("typed-plan-planned-count-conflict");return{current:!0}}function ae(e){const a=[];for(const d of e.crosscheck.targets){for(const l of e.crosscheck.observers){const s=l.expect==="visible"?"field-parity":"visibility-policy";a.push(J({mutation:e.crosscheck.mutationIdentity,target:d.identity,surface:d.surfaceMatch.surface,principal:l.identity,context:B("warm-cache",d.transition??null),invariant:K("invariant",{name:s}),expectation:l.expect}))}for(const l of["field-parity","durability"])a.push(J({mutation:e.crosscheck.mutationIdentity,target:d.identity,surface:d.surfaceMatch.surface,principal:e.crosscheck.writerIdentity,context:B("fresh-context","fresh-context"),invariant:K("invariant",{name:l}),expectation:"visible"}))}return te(a.map(({cellId:d,material:l})=>({id:d,material:l}))),a.sort((d,l)=>d.cellId.localeCompare(l.cellId))}function je(e){if(e?.schemaVersion===1)return{current:!1};if(![2,3,4].includes(e?.schemaVersion))throw new TypeError("unsupported-coherence-observed-version");const a=e.schemaVersion===2;if(e.status==="measured"&&(e.cases??[]).length===0)throw new TypeError("typed-observed-vacuous-measurement");const d=[],l=new Set;for(const r of e.cases??[]){const m=new Set,y=r.flowExecutionMaterial?.declaration;if(!y)throw new TypeError("typed-flow-execution-declaration-required");if(r.flow!==y.name)throw new TypeError("typed-observed-flow-conflict");if(o(r.observers??[])!==o(y.crosscheck?.observers??[]))throw new TypeError("typed-observed-observers-conflict");M(y.identity,"flow");const I={name:y.name,route:y.route??void 0,declared_endpoint:y.declaredEndpoint??void 0,cleanup_required:y.cleanupRequired,production:!1,identity:y.identity,crosscheck:y.crosscheck};if(ie({schema_version:3,flows:[I]}),q(r.flowExecutionMaterial)!==r.flowExecutionId)throw new TypeError("typed-flow-execution-digest-mismatch");const E=new Map((y.crosscheck.targets??[]).map(i=>[i.identity.id,i])),C=new Map(ae(I).map(i=>[i.cellId,i.material])),j=new Map;for(const i of r.cells??[]){const k={id:i.cellId,material:i.material};M(k,"observation-cell");const x=i.material;for(const[T,v]of[["mutation","mutation"],["target","target"],["surface","surface"],["principal","principal"],["context","context"],["invariant","invariant"]])M(x[T],v);const A=E.get(x.target.id);if(!A||A.surfaceMatch.surface.id!==x.surface.id)throw new TypeError("typed-cell-target-surface-conflict");if(j.has(i.cellId))throw new TypeError("duplicate-emitted-observation-cell");if(!C.has(i.cellId)||o(C.get(i.cellId))!==o(i.material))throw new TypeError("typed-cell-not-declared");j.set(i.cellId,i.material),m.add([x.target.id,x.surface.id,x.principal.id,x.context.id,x.invariant.id,x.expectation].join(":")),d.push(k)}const u=new Map((r.flowExecutionMaterial.cells??[]).map(i=>[i.cellId,i.materialDigest]));if(u.size!==(r.flowExecutionMaterial.cells??[]).length||j.size!==C.size||u.size!==j.size)throw new TypeError("typed-flow-cell-set-conflict");for(const[i,k]of j)if(u.get(i)!==q(k)||!C.has(i))throw new TypeError("typed-flow-cell-conflict");const R=new Set;for(const i of r.cases??[]){if(!E.has(i.targetId))throw new TypeError("typed-observation-target-dangling");const k=E.get(i.targetId);if(k.surfaceMatch.surface.id!==i.surfaceId)throw new TypeError("typed-observation-surface-conflict");if((i.route??null)!==(k.route??null))throw new TypeError("typed-observation-route-conflict");if(R.has(i.targetId))throw new TypeError("duplicate-typed-observation-target");R.add(i.targetId),l.add(`${i.targetId}:${i.surfaceId}`);const x=new Set,A=new Map(y.crosscheck.observers.map(T=>[T.identity.id,T]));for(const T of i.observations??[]){for(const v of[T.principalId,T.contextId,T.invariantId])if(!D.test(v??""))throw new TypeError("typed-observation-coordinate-shape");if(B("warm-cache",T.transition??null).id!==T.contextId||K("invariant",{name:T.invariant}).id!==T.invariantId||!m.has([i.targetId,i.surfaceId,T.principalId,T.contextId,T.invariantId,T.expectation].join(":")))throw new TypeError("typed-observation-cell-not-declared");if(A.get(T.principalId)?.persona!==T.persona)throw new TypeError("typed-observation-principal-label-conflict");if(x.has(T.principalId))throw new TypeError("duplicate-typed-warm-observation");x.add(T.principalId)}for(const T of[i.fresh?.principalId,i.fresh?.contextId,...i.fresh?.invariantIds??[]])if(!D.test(T??""))throw new TypeError("typed-observation-coordinate-shape");if(B("fresh-context","fresh-context").id!==i.fresh.contextId)throw new TypeError("typed-fresh-context-conflict");for(const[T,v]of(i.fresh?.invariants??[]).entries()){const P=i.fresh.invariantIds?.[T];if(K("invariant",{name:v}).id!==P||!m.has([i.targetId,i.surfaceId,i.fresh.principalId,i.fresh.contextId,P,i.fresh.expectation].join(":")))throw new TypeError("typed-fresh-cell-not-declared")}if(r.status==="measured"){const T=new Set(y.crosscheck.observers.map(v=>v.identity.id));if(x.size!==T.size||[...T].some(v=>!x.has(v)))throw new TypeError("typed-warm-observation-set-conflict");if(i.fresh.principalId!==y.crosscheck.writerIdentity.id||i.fresh.persona!==y.crosscheck.writer||o([...i.fresh.invariants??[]].sort())!==o(["durability","field-parity"]))throw new TypeError("typed-fresh-observation-set-conflict")}}if(r.status==="measured"&&(R.size!==E.size||[...E.keys()].some(i=>!R.has(i))))throw new TypeError("typed-observation-target-set-conflict");const n=r.cases??[],p={planned:E.size,reached:n.length,compared:n.filter(i=>i.status==="measured").length,agreed:n.filter(i=>i.status==="measured"&&i.comparison?.agreed===!0).length,unmeasured:E.size-n.filter(i=>i.status==="measured").length};if(o(r.counts?.targets??{})!==o(p))throw new TypeError("typed-observed-entry-counts-conflict");const b=(y.crosscheck.observers??[]).filter(i=>i.persona!==y.crosscheck.writer).length,g=1+b+E.size*(1+b),N=1+(y.crosscheck.observers??[]).length+E.size,z={personas:1+(y.crosscheck.observers??[]).length,contexts:g,cleanups:1};for(const[i,k]of Object.entries(z)){const x=r.counts?.[i];if(!x||!(i==="contexts"&&a?new Set([N,g]):new Set([k])).has(x.planned)||!Number.isSafeInteger(x.completed)||!Number.isSafeInteger(x.unmeasured)||x.completed<0||x.unmeasured<0||x.completed+x.unmeasured!==x.planned)throw new TypeError("typed-observed-entry-counts-conflict")}if(e.status==="measured"&&(r.status!=="measured"||r.mutationAccepted!==!0||p.planned===0||p.reached!==p.planned||p.compared!==p.planned||p.unmeasured!==0||n.some(i=>i.status!=="measured"||!i.comparison||i.comparison.authoritative?.status!=="measured"||i.comparison.fresh?.status!=="measured"||i.observations.some(k=>k.status!=="measured"||typeof k.agreed!="boolean"||k.authoritative?.status!=="measured"||k.observed?.status!=="measured")||i.fresh?.status!=="measured"||typeof i.fresh?.agreed!="boolean"||i.fresh?.authoritative?.status!=="measured"||i.fresh?.observed?.status!=="measured")||a&&!new Set([N,g]).has(r.counts.contexts.completed)||Object.keys(z).filter(i=>!a||i!=="contexts").some(i=>r.counts[i].completed!==r.counts[i].planned||r.counts[i].unmeasured!==0)))throw new TypeError("typed-observed-measured-funnel-incomplete")}te(d);const s=(r,m)=>(e.cases??[]).reduce((y,I)=>{for(const E of Object.keys(y))y[E]+=I.counts?.[r]?.[E]??0;return y},m),f={cases:{planned:(e.cases??[]).length,completed:(e.cases??[]).filter(r=>r.status==="measured").length,unmeasured:(e.cases??[]).filter(r=>r.status!=="measured").length},targets:s("targets",{planned:0,reached:0,compared:0,agreed:0,unmeasured:0}),cleanups:s("cleanups",{planned:0,completed:0,unmeasured:0}),personas:s("personas",{planned:0,completed:0,unmeasured:0}),contexts:s("contexts",{planned:0,completed:0,unmeasured:0})};for(const r of Object.keys(f))if(o(e.counts?.[r]??{})!==o(f[r]))throw new TypeError("typed-observed-counts-conflict");if(e.status==="measured"&&(f.cases.completed!==f.cases.planned||f.cases.unmeasured!==0||f.targets.planned===0||f.targets.reached!==f.targets.planned||f.targets.compared!==f.targets.planned||f.targets.unmeasured!==0||["personas","contexts","cleanups"].filter(r=>!a||r!=="contexts").some(r=>f[r].completed!==f[r].planned||f[r].unmeasured!==0)||e.counts?.obligations?.planned<=0||e.counts.obligations.reached!==e.counts.obligations.planned||e.counts.obligations.compared!==e.counts.obligations.planned))throw new TypeError("typed-observed-measured-funnel-incomplete");if(e.counts?.obligations?.reached!==f.targets.reached||e.counts?.obligations?.compared!==f.targets.compared||e.counts?.obligations?.agreed!==f.targets.agreed||!Number.isSafeInteger(e.counts?.mutations?.declared)||e.counts.mutations.declared<(e.cases??[]).length||e.status==="measured"&&e.counts.mutations.declared!==(e.cases??[]).length||e.counts?.mutations?.executed!==(e.cases??[]).filter(r=>r.mutationAccepted===!0).length)throw new TypeError("typed-observed-counts-conflict");const c=r=>r.map(m=>o(m)).sort();if(o(c(e.findings??[]))!==o(c((e.cases??[]).flatMap(r=>r.findings??[]))))throw new TypeError("typed-observed-findings-conflict");for(const r of e.findings??[]){if(!D.test(r.targetId??"")||!D.test(r.surfaceId??""))throw new TypeError("typed-finding-coordinate-shape");if(!l.has(`${r.targetId}:${r.surfaceId}`))throw new TypeError("typed-finding-coordinate-dangling")}const w=new Map(d.map(r=>[r.id,r.material]));for(const r of e.plan?.obligations??[]){if(!D.test(r.id??""))throw new TypeError("typed-plan-obligation-id-shape");for(const y of["mutationId","surfaceId","principalId","contextId","invariantId"])if(!D.test(r[y]??""))throw new TypeError(`typed-plan-obligation-${y}-shape`);if(r.targetId!==null&&!D.test(r.targetId??""))throw new TypeError("typed-plan-obligation-targetId-shape");const m=w.get(r.id);if(r.status!=="unmeasured"&&!m)throw new TypeError("typed-plan-obligation-cell-dangling");if(m&&(r.mutationId!==m.mutation.id||r.targetId!==m.target.id||r.surfaceId!==m.surface.id||r.principalId!==m.principal.id||r.contextId!==m.context.id||r.invariantId!==m.invariant.id||r.expectation!==m.expectation))throw new TypeError("typed-observed-plan-coordinate-conflict")}if(e.plan?.status==="measured"){const r=(e.plan.journeys??[]).flatMap(I=>{let E=null;if(I.status==="matched"){const C=(e.cases??[]).filter(j=>j.flow===I.flow);if(C.length!==1||I.flowId!==C[0].flowExecutionMaterial?.declaration?.identity?.id)throw new TypeError("typed-observed-plan-flow-conflict");E=C[0]}return(I.targets??[]).flatMap(C=>{if(E&&!(E.flowExecutionMaterial.declaration.crosscheck.targets??[]).some(p=>p.identity.id===C.targetId&&p.surfaceMatch.surface.id===C.surfaceId&&p.route===C.route))throw new TypeError("typed-observed-plan-target-conflict");const j=C.obligations??[],u={planned:j.length,reached:0,compared:0,agreed:0,disagreed:0,unmeasured:0};for(const n of j)n.status==="unmeasured"?u.unmeasured++:(u.reached++,n.status!=="reached"&&(u.compared++,u[n.status]++));const R=u.reached===0?"unmeasured":u.disagreed?"disagreed":u.compared<u.planned?"partial":"agreed";if(o(C.counts)!==o(u)||C.status!==R)throw new TypeError("typed-observed-plan-target-summary-conflict");return j})});if(o(c(e.plan.obligations??[]))!==o(c(r)))throw new TypeError("typed-observed-plan-obligation-set-conflict");const m={reached:0,compared:0,agreed:0,disagreed:0};for(const I of r)I.status!=="unmeasured"&&(m.reached++,I.status!=="reached"&&(m.compared++,m[I.status]++));const y=e.plan.coverage??{};if(y.planned!==r.length||y.discovered!==y.resolved+y.unresolved||r.length>y.resolved||Object.entries(m).some(([I,E])=>y[I]!==E))throw new TypeError("typed-observed-plan-coverage-conflict")}return{current:!a}}function J(e){const{id:a,material:d}=K("observation-cell",e);return{cellId:a,material:d}}function Oe({flow:e,planMutation:a=null,planJourney:d=null,mutationPermitMaterial:l}){const s=e.crosscheck,f=!!e.identity;f&&ie({schema_version:3,flows:[e]});const c={flow:e.name,matchedPlanMutation:a===null?{status:"absent"}:{status:"resolved",id:a},entity:s.entity,writer:s.writer,authoritativeReadback:s.authoritative_readback},w={status:"unresolved",reason:"logical-surface-not-resolved"};let r=f?ae(e):[];const m=(I,E,C,j)=>{r.push(J({mutation:c,target:I,surface:w,principal:E,context:C,invariant:j}))};for(const I of s.targets){for(const E of s.observers??[]){const C=E.expect==="visible"?"field-parity":"visibility-policy";f||m(I,{persona:E.persona,expect:E.expect},{kind:"warm-cache",transition:I.transition??null},C)}for(const E of["field-parity","durability"])f||m(I,{persona:s.writer,expect:"visible"},{kind:"fresh-context",transition:"fresh-context"},E)}r.sort((I,E)=>I.cellId.localeCompare(E.cellId));const y={namespace:"coherence/flow-execution",version:1,declaration:{name:e.name,route:e.route??null,declaredEndpoint:e.declared_endpoint??null,cleanupRequired:e.cleanup_required===!0,...f?{identity:e.identity}:{},crosscheck:s},mutationPolicy:{namespace:"coherence/flow-mutation-policy",version:1,permit:l,selectedFlow:e.name},planJourney:d===null?{status:"absent"}:{status:"matched",journey:d},cells:r.map(({cellId:I,material:E})=>({cellId:I,materialDigest:q(E)}))};return{flowExecutionId:q(y),flowExecutionMaterial:y,cells:r}}export{me as COHERENCE_IDENTITY_KINDS,M as assertCoherenceIdentity,Oe as buildFlowExecutionIdentity,J as buildObservationCellIdentity,K as createCoherenceIdentity,B as createContextIdentity,Ee as createTargetIdentity,ee as stableEvidenceId,te as validateCoherenceIdentityGraph,Se as validateCoherenceIrIdentities,je as validateCoherenceObservedIdentities,Ce as validateCoherencePlanIdentities,ie as validateTypedCrudDeclaration};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{emptyCoherence as Fe}from"./contracts.mjs";import{extractTanstackUnit as je}from"./tanstack.mjs";import{analyzeCoherence as Ae,operationReadPairs as Te}from"./analyze.mjs";import{balancedSlice as $e,callParen as fe,maskNonCode as Le,parseKeyExpression as qe,splitTopLevel as Ue}from"./structural-js.mjs";import{createCoherenceIdentity as Z,stableEvidenceId as ue,validateCoherenceIrIdentities as De}from"./identity.mjs";import{buildSymbolIndex as ze,declarationForOffset as Y,traceSymbolUses as _}from"./symbols.mjs";import{cacheKeyIdentity as Qe,evaluateCacheKeyExpression as Ge,keyResolution as ee}from"./cache-key.mjs";import{buildSemanticGraph as He}from"./graph.mjs";import{endpointFamily as Ze,entityAliasMap as _e}from"./entity-aliases.mjs";import{endpointFamily as mn}from"./entity-aliases.mjs";const P=f=>f.span?`${f.file}:${f.span.start}:${f.span.end}`:`${f.file}:${f.line}`,ne=(f,p)=>{const v=[...f].filter(k=>k.file===p.file&&k.line===p.line);return v.length===1?v[0]:null},Ve=(f,p)=>f.file.localeCompare(p.file)||f.line-p.line||(f.span?.start??-1)-(p.span?.start??-1)||(f.span?.end??-1)-(p.span?.end??-1);function dn({sourceByFile:f,importsByFile:p,moduleRefsByFile:v}){return Object.keys(f??{}).sort().map(k=>({file:k,source:f[k],imports:[...p?.[k]??[]].sort(),moduleRefs:[...v?.[k]??[]].sort((l,x)=>JSON.stringify(l).localeCompare(JSON.stringify(x)))}))}function pe(f,p=new Map){const v=f.material??f;return v.receiver?.resolution==="unresolved"||v.keyMatch==="unknown"||v.predicate&&v.predicate.resolution!=="resolved"||Object.values(v.filters??{}).some(l=>l&&typeof l=="object"&&l.resolution!=="resolved")||v.keyId&&ee(p.get(v.keyId)?.material)==="unresolved"||f.match==="predicate"?!0:(f.pattern?.segments??[]).some(l=>l.kind==="call"||l.kind==="unknown"||l.kind==="parameter")}const Xe=f=>(f?.segments??[]).map(p=>p.kind==="literal"?JSON.stringify(p.value):`<${p.kind}${p.expression||p.name?":"+(p.expression??p.name):""}>`).join(",");function Ye({reads:f=[],mutations:p=[],surfaces:v=[],cacheKeys:k=[],cacheOperations:l=[]}){const x=new Map,J=a=>(x.has(a)||x.set(a,{family:a,mutationIds:[],readIds:[],surfaceIds:[],keyTerms:new Set,invalidations:0,invalidationsUnresolved:0,readsUnresolvedKey:0}),x.get(a)),M=new Map(f.map(a=>[a.id,a])),K=new Map(k.map(a=>[a.id,a])),m=new Map(l.map(a=>[a.id,a]));for(const a of f){if(!a.family)continue;const g=J(a.family);g.readIds.push(a.id),g.keyTerms.add(Xe(a.pattern)),ee(a.pattern)==="unresolved"&&g.readsUnresolvedKey++}for(const a of p){if(!a.family)continue;const g=J(a.family);g.mutationIds.push(a.id);for(const C of a.operationIds??[]){const E=m.get(C);E&&(g.invalidations++,pe(E,K)&&g.invalidationsUnresolved++)}}for(const a of v){const g=new Set((a.readIds??[]).map(C=>M.get(C)?.family).filter(Boolean));for(const C of g)J(C).surfaceIds.push(a.id)}return[...x.values()].sort((a,g)=>a.family.localeCompare(g.family)).map(a=>({...Z("family",{endpointFamily:a.family}),family:a.family,mutationIds:[...a.mutationIds].sort(),readIds:[...a.readIds].sort(),surfaceIds:[...new Set(a.surfaceIds)].sort(),keyTerms:[...a.keyTerms].sort(),invalidations:a.invalidations,invalidationsUnresolved:a.invalidationsUnresolved,readsUnresolvedKey:a.readsUnresolvedKey}))}function fn({units:f,routes:p,contracts:v={},entities:k=[]}){const l=Fe(),x=_e(k),J=e=>{const n=Ze(e);return{family:x.get(n)??n,familySource:x.has(n)?"declaration":"endpoint"}},M=[...f??[]].sort((e,n)=>e.file.localeCompare(n.file)),K=p??[],m=ze(M),a=M.map(e=>je(e,{symbolIndex:m,units:M,contracts:v})),g=a.flatMap(e=>e.unresolved),C=new Map;for(const e of a.flatMap(n=>n.operationCandidates??[])){const n=e.receiver.ownerSymbol;n&&C.set(n,[...C.get(n)??[],e])}const E=new Map,me=(e,n)=>{const o=(Array.isArray(n)?n:[n]).filter(Boolean),i=Qe(e),s=E.get(i.id);if(s)return s.provenance=[...new Map([...s.provenance,...o].map(t=>[JSON.stringify(t),t])).values()].sort((t,d)=>JSON.stringify(t).localeCompare(JSON.stringify(d))),s;const c={...i,provenance:o};return E.set(c.id,c),c},oe=new Map,ye=e=>{const n=e.key?me(e.key,[{origin:e.sourceRef,method:"tanstack-operation-key",confidence:e.resolution},...e.keyProvenance??[]]):null,o={sourceRef:e.sourceRef,receiver:e.receiver,operation:e.operation,keyId:n?.id??null,keyMatch:e.keyMatch,exact:e.exact,predicate:e.predicate,filters:e.filters,effects:e.effects},i=Z("cache-operation",o),s=`${o.sourceRef.file}:${o.sourceRef.start}:${o.sourceRef.end}`,c=oe.get(s);if(c&&c.id!==i.id)throw new TypeError("conflicting-cache-operation-occurrence");if(c)return c.provenance=[...new Map([...c.provenance,...e.provenance??[]].map(d=>[JSON.stringify(d),d])).values()].sort((d,y)=>JSON.stringify(d).localeCompare(JSON.stringify(y))),c;const t={...i,provenance:[...e.provenance??[]].sort((d,y)=>JSON.stringify(d).localeCompare(JSON.stringify(y)))};return oe.set(s,t),t},O=new Map;for(const e of a)for(const n of e.readCandidates)O.set(P(n),{file:n.file,line:n.line,span:n.span,owner:n.owner,pattern:n.pattern,endpoint:n.endpoint??null,exact:!0,keyProvenance:n.keyProvenance??[]});for(const e of K)for(let n of e.queries??[]){if(n?.file==null||n?.line==null)continue;const o=M.find(S=>S.file===n.file)?.source??"";if(!n.span&&o&&Number.isInteger(n.line)&&n.line>0){const S=o.split(`
|
|
2
|
+
`),r=S[n.line-1]??"",w=n.via?[n.via]:["useQuery","useInfiniteQuery","useSuspenseQuery","useSWR"],B=[...Le(r).matchAll(/\b(use[A-Za-z_$][\w$]*)\b/g)].filter(I=>w.includes(I[1])&&fe(r,I.index+I[0].length)>=0&&!/\bfunction\s+$/.test(r.slice(0,I.index)));if(B.length===1){const I=B[0],H=S.slice(0,n.line-1).join(`
|
|
3
|
+
`).length+(n.line>1?1:0)+I.index;n={...n,span:{file:n.file,start:H,end:H+I[0].length,line:n.line,column:I.index+1}}}}const i=P(n),s=n.span?O.get(i):ne(O.values(),n);if(s){!s.endpoint&&n.endpoint&&(s.endpoint=n.endpoint);continue}if(!n.span&&[...O.values()].some(S=>S.file===n.file&&S.line===n.line))continue;const c=n.span?Y(m,n.file,n.span.start)?.key??null:null,t=n.span?fe(o,n.span.end):-1,d=t<0?null:$e(o,t),y=d?Ue(d.text.slice(1,-1))[0]??"":"",h=!n.via&&y.startsWith("{")?Ue(y.slice(1,-1)).find(S=>/^queryKey\s*:/.test(S)):null,u=n.via?y:h?h.slice(h.indexOf(":")+1).trim():n.key??"",L=d&&u?o.indexOf(u,t+1):-1,G=n.span?{file:n.file,source:o,start:L>=0?L:n.span.start,ownerSymbol:c,symbolIndex:m,units:M,contracts:v}:{},W=Ge(u,G);O.set(i,{file:n.file,line:n.line,span:n.span??null,owner:c,pattern:W.patterns.length===1?W.patterns[0]:qe(u,G),endpoint:n.endpoint??null,exact:W.resolution==="resolved",keyProvenance:W.provenance})}const b=[],F=new Map;for(const e of O.values()){const n=!!e.endpoint&&!!e.span,o=ue("read",e.span??{file:e.file,line:e.line},e.pattern),i=e.endpoint?J(e.endpoint):{family:null,familySource:"unresolved"};b.push({id:o,file:e.file,line:e.line,span:e.span??null,pattern:e.pattern,endpoint:e.endpoint,...i,confidence:n?e.exact?"exact":"coarse":"unresolved"}),e.owner&&F.set(o,e.owner)}for(const e of g.filter(n=>n.reason.includes("query"))){if(e.span?O.has(P(e)):ne(O.values(),e))continue;const n=ue("read",e.span??{file:e.file,line:e.line},e.reason);b.push({id:n,file:e.file,line:e.line,span:e.span??null,pattern:{segments:[{kind:"unknown"}]},endpoint:null,family:null,familySource:"unresolved",confidence:"unresolved"}),e.owner&&F.set(n,e.owner)}for(const e of b){const n=[...O.values()].find(i=>P(i)===P(e)),o=me(e.pattern,[...e.span?[{origin:e.span,method:"tanstack-query-key",confidence:e.confidence}]:[],...n?.keyProvenance??[]]);e.keyId=o.id}const $=new Map;for(const e of a)for(const n of e.mutationCandidates){const o=n.owner?_(m,n.owner):[],i=o.filter(t=>t!==n.owner).flatMap(t=>C.get(t)??[]),s=o.flatMap(t=>{const d=v.helpers?.[t];if(!d)return[];if(!Array.isArray(d))throw new TypeError("invalid-cache-helper-contract");const y=m.uses.find(h=>o.includes(h.from)&&h.to===t)?.source;return d.map(h=>({...h,sourceRef:h.sourceRef??(y?{file:y.file,start:y.start,end:y.end}:null),receiver:h.receiver??{expression:t,ownerSymbol:n.owner,targetSymbol:t,kind:"unknown",resolution:"unresolved",reason:"unsupported-client"},provenance:[{adapter:"structural-js",method:"helper-call",confidence:"exact",resolutionPath:[n.owner,t]},...h.provenance??[],{adapter:"tanstack",method:"explicit-contract",confidence:"resolved",resolutionPath:[n.owner,t]}]}))}),c=[...new Map([...n.operations??[],...i,...s].filter(t=>t.sourceRef).map(t=>[`${t.sourceRef.file}:${t.sourceRef.start}:${t.sourceRef.end}`,t])).values()];$.set(P(n),{file:n.file,line:n.line,span:n.span,endpoint:n.endpoint??null,operations:c,nonWrite:!1})}for(const e of K)for(let n of e.mutations??[]){if(n?.file==null||n?.line==null)continue;if(n.via&&n.span){const s=M.find(d=>d.file===n.file)?.source??"",c=fe(s,n.span.end),t=c<0?null:$e(s,c);if(t){const d=u=>u.file===n.file&&u.start>c&&u.end<=t.end,y=Y(m,n.file,n.span.start)?.key,h=new Set(m.uses.filter(u=>u.resolution==="resolved"&&u.from===y&&d(u.source)&&Y(m,n.file,u.source.start)?.key===y).flatMap(u=>_(m,u.to)));n={...n,operations:[...a.flatMap(u=>u.operationCandidates??[]).filter(u=>d(u.sourceRef)),...[...h].flatMap(u=>C.get(u)??[])]}}}const o=P(n),i=n.span?$.get(o):ne($.values(),n);i?(!i.endpoint&&n.endpoint&&(i.endpoint=n.endpoint),i.nonWrite=i.nonWrite||!!n.nonWrite,i.hook=i.hook??n.hook??n.fnName??null,i.operations.push(...n.operations??[])):(n.span||![...$.values()].some(s=>s.file===n.file&&s.line===n.line))&&$.set(o,{file:n.file,line:n.line,span:n.span,endpoint:n.endpoint??null,operations:n.operations??[],nonWrite:!!n.nonWrite,hook:n.hook??n.fnName??null})}const ve=[...$.values()];for(const e of g.filter(n=>n.reason.includes("mutation")))(e.span?$.has(P(e)):ne($.values(),e))||ve.push({file:e.file,line:e.line,span:e.span,endpoint:null,operations:[],nonWrite:!1});const te=new Map;for(const e of ve){const n=Z("mutation",{sourceRef:{file:e.file,line:e.line},endpoint:e.endpoint??null}),o=te.get(n.id)??{identity:n,occurrences:[]};o.occurrences.push(e),te.set(n.id,o)}const j=[],V=[],se=new Map;let ie=0;for(const{identity:e,occurrences:n}of[...te.values()].sort((o,i)=>o.identity.id.localeCompare(i.identity.id))){const o=[...n].sort(Ve);if(o.every(t=>t.nonWrite)){ie+=o.length;continue}const i=o[0];if(o.length===1){const t=!!i.endpoint,d=t?J(i.endpoint):{family:null,familySource:"unresolved"},y=d.family;se.set(e.id,i.span??null),j.push({...e,file:i.file,line:i.line,hook:i.hook??null,endpoint:i.endpoint,...d,writes:t?[{pattern:{segments:[{kind:"literal",value:y}]}}]:[],operationIds:[...new Set((i.operations??[]).map(ye).map(h=>h.id))].sort(),confidence:t?"exact":"unresolved"});continue}const s=new Set(o.map(t=>t.hook??null)),c=o.flatMap(t=>t.operations??[]).map(ye);se.set(e.id,i.span??null),j.push({...e,file:i.file,line:i.line,hook:s.size===1?i.hook??null:null,endpoint:i.endpoint,family:null,familySource:"unresolved",writes:[],operationIds:[...new Set(c.map(t=>t.id))].sort(),confidence:"unresolved"}),V.push(...o.map(t=>({id:e.id,file:t.file,line:t.line,kind:"write",reason:"ambiguous-mutation-occurrence",span:t.span})))}const Be=new Map(b.map(e=>[e.id,e])),A=new Map(m.declarations.map(e=>[e.key,e])),X=new Map;for(const e of m.uses)X.set(e.from,[...X.get(e.from)??[],e]);const re=new Map;for(const e of m.unknownEdges)re.set(e.from,[...re.get(e.from)??[],e]);const Pe=e=>{if(!e.file)return[];if(e.component){const o=m.declarations.find(s=>s.file===e.file&&s.name===e.component)?.key,i=m.imports.find(s=>s.file===e.file&&s.local===e.component&&s.resolution==="resolved")?.target;return[o??i].filter(Boolean)}const n=m.declarations.filter(o=>o.file===e.file&&o.default).map(o=>o.key);return n.length?n:m.declarations.filter(o=>o.file===e.file&&o.exported&&o.presentation).map(o=>o.key)},he=(e,n)=>{const o=[[e]],i=new Set;for(;o.length;){const s=o.shift(),c=s.at(-1);if(c===n)return s;if(!(i.has(c)||s.length>24)){i.add(c);for(const t of(X.get(c)??[]).sort((d,y)=>d.to.localeCompare(y.to)))t.to!==e&&t.to!==n&&A.get(t.to)?.exported&&A.get(t.to)?.presentation||o.push([...s,t.to])}}return null},N=[],q=[];let ge=0,we=0;for(const e of[...K].sort((n,o)=>String(n.path).localeCompare(String(o.path)))){const o=[...new Set(Pe(e).flatMap(s=>_(m,s)))].map(s=>A.get(s)).filter(s=>s?.exported&&s.presentation).sort((s,c)=>s.key.localeCompare(c.key));let i=!1;for(const s of o){const c=new Set(_(m,s.key,{stopAtPresentation:!0})),t=b.filter(r=>c.has(F.get(r.id))&&r.span).sort((r,w)=>r.id.localeCompare(w.id)),d=[...c].flatMap(r=>re.get(r)??[]).sort((r,w)=>JSON.stringify(r).localeCompare(JSON.stringify(w)));if(!t.length&&!d.length)continue;i=!0;const y=[...new Set((X.get(s.key)??[]).filter(r=>r.resolution==="resolved"&&r.to!==s.key).filter(r=>!(A.get(r.to)?.presentation&&A.get(r.to)?.exported)).map(r=>r.to))],h=new Map(y.map(r=>[r,new Set(_(m,r,{stopAtPresentation:!0}))])),u=r=>{if(r===s.key)return null;const w=y.filter(B=>h.get(B).has(r));return w.length===1?w[0]:null},L=new Map,G=r=>L.get(r)??L.set(r,{reads:[],unknowns:[]}).get(r);for(const r of t)G(u(F.get(r.id))).reads.push(r);for(const r of d)G(u(r.from)).unknowns.push(r);const W=[...L.entries()].filter(([,r])=>r.reads.length||r.unknowns.length),S=(r,w,B)=>{const I=Z("surface",{route:e.path,component:r,sourceRef:{file:s.file,line:0}}),H=`${s.file}#${r}`,be=w.map(R=>{const de=he(s.key,F.get(R.id));return{surfaceId:I.id,readId:R.id,confidence:"resolved",resolution:"resolved",reason:null,source:R.span,provenance:{adapter:"structural-js",method:"symbol-traversal"},path:[H,...de.slice(1),`read:${R.id}`]}}),Ke=B.map(R=>{const de=he(s.key,R.from)??[s.key];return{surfaceId:I.id,readId:null,confidence:"unresolved",resolution:"unresolved",reason:R.reason,source:R.source,provenance:{adapter:"structural-js",method:"symbol-traversal"},path:[H,...de.slice(1),"unknown-export"]}});q.push(...be,...Ke);const Ne=be.map(R=>R.readId).sort(),Ee=[...new Set(Ne.map(R=>Be.get(R)?.family).filter(Boolean))].sort();N.push({...I,route:e.path,file:s.file,component:r,readIds:Ne,families:Ee,confidence:"resolved",kind:"component"})};if(W.length<=1)S(s.name,t,d);else for(const[r,w]of W){const B=r===null?s.name:`${s.name}::${A.get(r)?.name??r}`;S(B,w.reads,w.unknowns)}}if(i){ge++;continue}we++,N.push({...Z("surface",{route:e.path,component:null,sourceRef:{file:e.file??null,line:0}}),route:e.path,file:e.file??null,component:null,readIds:[],families:[],confidence:"coarse",kind:"route"})}const U=[...E.values()].sort((e,n)=>e.id.localeCompare(n.id)),ae=new Map(U.map(e=>[e.id,e])),T=[...oe.values()].sort((e,n)=>e.id.localeCompare(n.id)),D=Te(T.map(e=>({...e,material:{...e.material,key:ae.get(e.material.keyId)?.material??null}})),b),ke=j.filter(e=>e.confidence!=="unresolved").length,Se=j.filter(e=>e.confidence==="unresolved"&&e.endpoint==null).length+V.length,Ie=b.filter(e=>e.confidence!=="unresolved").length,Re=b.filter(e=>e.confidence==="unresolved").length;let z=0,Q=0;for(const e of T)z++,pe(e,ae)&&Q++;const We=new Set(N.flatMap(e=>e.families??[])),le=j.filter(e=>e.family&&!We.has(e.family)),Je=[...new Set(le.map(e=>e.family))].sort();l.cacheKeys=U,l.cacheOperations=T,l.reads=b.sort((e,n)=>e.id.localeCompare(n.id)),l.mutations=j.sort((e,n)=>e.id.localeCompare(n.id)),l.operationReadPairs=D,l.surfaces=N.sort((e,n)=>e.id.localeCompare(n.id)),l.ownershipEdges=q.sort((e,n)=>JSON.stringify(e).localeCompare(JSON.stringify(n))),l.resourceFamilies=Ye({reads:l.reads,mutations:l.mutations,surfaces:N,cacheKeys:U,cacheOperations:T});const Me=U.filter(e=>ee(e.material)==="unresolved").length,Ce=D.filter(e=>e.keyCoverage==="covered"&&e.effectCoverage==="covered").length,xe=D.filter(e=>e.keyCoverage==="unresolved"||e.effectCoverage==="unresolved").length;l.coverage.counts={writeCandidates:ke+Se+ie,writesResolved:ke,writesNonWrite:ie,writesUnresolved:Se,ambiguousMutationOccurrences:V.length,readCandidates:Ie+Re,readsResolved:Ie,readsUnresolved:Re,keysDiscovered:U.length,keysResolved:U.length-Me,keysUnresolved:Me,operationsDiscovered:z,operationsResolved:z-Q,operationsUnresolved:Q,invalidationsDiscovered:z,invalidationsResolved:z-Q,invalidationsUnresolved:Q,operationReadPairsDiscovered:D.length,operationReadPairsCovered:Ce,operationReadPairsNotCovered:D.length-Ce-xe,operationReadPairsUnresolved:xe,surfacesSuggested:N.length,surfacesResolved:N.filter(e=>e.kind==="component").length,surfacesDeclared:N.length,routesWithSurfaces:ge,routesWithoutReads:we,ownershipEdgesDiscovered:q.length,ownershipEdgesResolved:q.filter(e=>e.resolution==="resolved").length,ownershipEdgesUnresolved:q.filter(e=>e.resolution==="unresolved").length,writersWithNoReaderSurface:le.length},l.coverage.unjoinedWriterFamilies=Je,l.coverage.unresolved=[...l.reads.filter(e=>e.confidence==="unresolved").map(e=>({id:e.id,file:e.file,line:e.line,kind:"read",reason:e.span?"no-resolvable-endpoint":"missing-source-span"})),...l.mutations.filter(e=>e.confidence==="unresolved"&&e.endpoint==null).map(e=>({id:e.id,file:e.file,line:e.line,kind:"write",reason:"no-resolvable-endpoint"})),...V,...le.map(e=>({id:e.id,file:e.file,line:e.line,kind:"family-join",family:e.family,reason:"no-reader-surface"})),...U.filter(e=>ee(e.material)==="unresolved").map(e=>{const n=e.material.segments.find(o=>o.resolution==="unresolved")?.origin;return{id:e.id,file:n?.file??"<unknown>",line:n?.line??0,kind:"cache-key",reason:e.material.segments.find(o=>o.resolution==="unresolved")?.reason??"dynamic-key"}}),...T.filter(e=>pe(e,ae)).map(e=>({id:e.id,file:e.material.sourceRef.file,line:M.find(n=>n.file===e.material.sourceRef.file)?.source.slice(0,e.material.sourceRef.start).split(`
|
|
4
|
+
`).length??0,kind:"cache-operation",reason:e.material.receiver.reason??(e.material.keyMatch==="unknown","dynamic-key")})),...l.ownershipEdges.filter(e=>e.resolution==="unresolved").map(e=>({id:e.surfaceId,file:e.source.file,line:e.source.line,kind:"ownership",reason:e.reason}))],l.units=M.map(e=>({file:e.file,imports:e.imports??[],moduleRefs:e.moduleRefs??[]}));const Oe=new Map;for(const e of l.mutations){const n=se.get(e.id),o=n?Y(m,e.file,n.start)?.key:null;o&&Oe.set(e.id,o)}l.graph=He({routes:K,symbolIndex:m,cacheKeys:U,cacheOperations:T,reads:l.reads,mutations:l.mutations,surfaces:N,ownershipEdges:l.ownershipEdges,unresolved:l.coverage.unresolved,readOwnerById:F,mutationOwnerById:Oe});const ce=Ae(l);return l.coverage.status=ce.coverage.status,l.coverage.reason=ce.coverage.reason,l.candidates=ce.candidates,De(l),l}export{fn as buildCoherenceIr,mn as endpointFamily,Ye as resourceFamilies,dn as sourceUnits,ue as stableEvidenceId};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function y(n,e){const i=Array.isArray(n)?n:[];if(!e||typeof e.path!="string"||!e.path.startsWith("/"))throw new Error("navigation event needs an absolute path");return[...i,{sequence:i.length,path:e.path,mode:e.mode??"unknown",at:e.at??null,mainFrameDocument:e.mainFrameDocument??null,sameDocument:e.sameDocument??null,surfaceId:e.surfaceId??null}]}function g(n){return Array.isArray(n)?[...n]:[...n?.paths??[]]}function x(n,e){const i=g(n),s=g(e),o=Math.max(i.length,s.length);for(let r=0;r<o;r++)if(i[r]!==s[r])return{agreed:!1,index:r,expected:i[r]??null,observed:s[r]??null,reason:i[r]==null?"unexpected-transition":s[r]==null?"missing-transition":"substituted-transition"};return{agreed:!0,index:null,reason:"exact-sequence"}}const m=n=>{try{return new URL(n,"http://qa.invalid").origin==="http://qa.invalid"?new URL(n,"http://qa.invalid").pathname:null}catch{return null}};function w(n,e){const i=new Set((n??[]).map(t=>t?.path).filter(t=>typeof t=="string")),s=[],o=[],r=new Set;for(const t of n??[]){if(!i.has(t?.path))continue;const u=[...new Set([t.file,...t.files??[]].filter(Boolean))].sort();for(const c of u){const f=e instanceof Map?e.get(c):e?.(c);if(typeof f=="string"){for(const a of f.matchAll(/<Link\b[^>]*\bhref\s*=\s*(["'`])([^"'`]+)\1/g)){const l=m(a[2]),p={file:c,start:a.index,end:a.index+a[0].length};if(!l||!i.has(l)){o.push({fromRoute:t.path,sourceRef:p,reason:l?"undeclared-route-target":"non-local-route-target"});continue}if(l===t.path)continue;const h={fromRoute:t.path,toRoute:l,sourceRef:p,transition:"client-navigation",cost:1},d=JSON.stringify(h);r.has(d)||(r.add(d),s.push(h))}for(const a of f.matchAll(/\b(?:router\.(?:push|replace)|navigate)\(\s*(["'`])([^"'`]+)\1\s*\)/g)){const l=m(a[2]),p={file:c,start:a.index,end:a.index+a[0].length};if(!l||!i.has(l)){o.push({fromRoute:t.path,sourceRef:p,reason:l?"undeclared-route-target":"non-local-route-target"});continue}if(l===t.path)continue;const h={fromRoute:t.path,toRoute:l,sourceRef:p,transition:"client-navigation",cost:1},d=JSON.stringify(h);r.has(d)||(r.add(d),s.push(h))}for(const a of f.matchAll(/<a\b[^>]*\bhref\s*=\s*(["'`])([^"'`]+)\1/g))o.push({fromRoute:t.path,sourceRef:{file:c,start:a.index,end:a.index+a[0].length},reason:"full-document-link"});for(const a of f.matchAll(/<(?:a|Link)\b[^>]*\bhref\s*=\s*\{/g))o.push({fromRoute:t.path,sourceRef:{file:c,start:a.index,end:a.index+a[0].length},reason:"dynamic-route-target"})}}}return{records:s.sort((t,u)=>JSON.stringify(t).localeCompare(JSON.stringify(u))),gaps:o.sort((t,u)=>JSON.stringify(t).localeCompare(JSON.stringify(u)))}}function S({fromRoute:n,toRoute:e,transitions:i}){if(n===e)return{status:"planned",fromRoute:n,toRoute:e,cost:0,steps:[]};const s=new Map;for(const t of i??[]){if(!t||typeof t.fromRoute!="string"||typeof t.toRoute!="string"||t.transition!=="client-navigation"||!Number.isFinite(t.cost)||t.cost<=0)throw new TypeError("navigation-transition-invalid");s.set(t.fromRoute,[...s.get(t.fromRoute)??[],t])}for(const t of s.values())t.sort((u,c)=>JSON.stringify(u).localeCompare(JSON.stringify(c)));const o=[{route:n,cost:0,steps:[]}],r=new Map([[n,0]]);for(;o.length;){o.sort((u,c)=>u.cost-c.cost||JSON.stringify(u.steps).localeCompare(JSON.stringify(c.steps)));const t=o.shift();if(t.route===e)return{status:"planned",fromRoute:n,toRoute:e,cost:t.cost,steps:t.steps};if(t.cost===r.get(t.route))for(const u of s.get(t.route)??[]){const c=t.cost+u.cost;c>=(r.get(u.toRoute)??1/0)||(r.set(u.toRoute,c),o.push({route:u.toRoute,cost:c,steps:[...t.steps,u]}))}}return{status:"unmeasured",fromRoute:n,toRoute:e,reason:"no-navigation-path",cost:null,steps:[]}}async function v({context:n,plan:e,transition:i}){if(e?.status!=="planned")return{status:"unmeasured",reason:e?.reason??"navigation-path-unplanned",completed:0};if(typeof i!="function")return{status:"unmeasured",reason:"navigation-driver-missing",completed:0};for(let s=0;s<e.steps.length;s++){const o=await i({context:n,step:e.steps[s]});if(o?.status!=="measured"||o?.continuity?.status!=="measured"||o.continuity.sameDocument!==!0)return{status:"unmeasured",reason:o?.reason??o?.continuity?.reason??"document-continuity-unmeasured",completed:s}}return{status:"measured",reason:null,completed:e.steps.length,context:n}}export{x as comparePathSequence,w as discoverWorkflowTransitions,v as executeNavigationPath,g as expectedPathSequence,y as recordTransition,S as shortestNavigationPath};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{createHash as se}from"node:crypto";import{canonicalize as oe}from"../jcs.mjs";import{assertCoherenceIdentity as q,createCoherenceIdentity as Q,createContextIdentity as W}from"./identity.mjs";import{compareRepresentations as ue,isUnavailableAuthoritativeState as X,normalizeRepresentation as Y,representationFinding as Z}from"./representations.mjs";const ge=4,M=e=>"sha256:"+se("sha256").update(oe(e)).digest("hex"),ie=/^sha256:[a-f0-9]{64}$/;function ee(e,t=[]){return{status:"unmeasured",reason:e,accepted:!1,fixture:null,effect:null,convergence:null,observers:t}}function ce(e){return e.flatMap(t=>[...(t.observations??[]).map(a=>({targetId:t.targetId??null,surfaceId:t.surfaceId??null,route:t.route??null,persona:a.persona,context:a.context,status:a.status,agreed:a.agreed,projection:a.observed})),t.fresh?{targetId:t.targetId??null,surfaceId:t.surfaceId??null,route:t.route??null,persona:t.fresh.persona,context:t.fresh.context,status:t.fresh.status,agreed:t.fresh.agreed,projection:t.fresh.observed}:null].filter(Boolean))}function N(e){const t=e?.causal?.fixture;return!t||typeof t!="object"||t.namespace==null||t.entity==null||!ie.test(t.entityId??"")?null:{namespace:t.namespace,entity:t.entity,entityId:t.entityId}}function B(e,t){return e?.state!=="value"||!e.value||typeof e.value!="object"||Array.isArray(e.value)||!Object.prototype.hasOwnProperty.call(e.value,t)?null:M(e.value[t])}function j(e,t){if(!(e?.state!=="value"||!e.value||typeof e.value!="object"||Array.isArray(e.value)||!Object.prototype.hasOwnProperty.call(e.value,t)))return e.value[t]}function le(e,t,a,r,o,p,v,u=null){const b=e?.causal,d=ce(p);if(!b)return ee("causal-contract-absent",d);if(u)return{status:"unmeasured",reason:u,accepted:!1,fixture:null,effect:null,convergence:null,observers:d};if(t?.accepted!==!0)return ee("mutation-not-accepted",d);if(!Array.isArray(o)||o.length!==2||!o[0]||!o[1])return{status:"unmeasured",reason:"causal-settled-readback-missing",accepted:!0,fixture:null,effect:null,convergence:null,observers:d};const c=N(t),S=N(a),P=N(r),O=o[0],A=o[1],_=N(O),F=N(A);if(!c||c.namespace!==e.fixtureNamespace||c.entity!==b.entity||JSON.stringify(S)!==JSON.stringify(c)||JSON.stringify(P)!==JSON.stringify(c)||JSON.stringify(_)!==JSON.stringify(c)||JSON.stringify(F)!==JSON.stringify(c))return{status:"invalid",reason:"causal-fixture-identity-mismatch",accepted:!0,fixture:null,effect:null,convergence:null,observers:d};const f=b.effect,R=B(a,f.field),E=B(r,f.field),n=B(O,f.field),l=B(A,f.field);if(!R||!E||!n||!l)return{status:"unmeasured",reason:"mutation-effect-not-verified",accepted:!0,fixture:c,effect:null,convergence:null,observers:d};if(n!==l)return{status:"invalid",reason:"authoritative-readback-race",accepted:!0,fixture:c,effect:null,convergence:null,observers:d};if(E!==n)return{status:"invalid",reason:"expected-post-state-mismatch",accepted:!0,fixture:c,effect:null,convergence:null,observers:d};if(f.kind==="field-change"&&R===n)return{status:"invalid",reason:"mutation-effect-not-verified",accepted:!0,fixture:c,effect:null,convergence:null,observers:d};if(f.kind==="version-advance"&&!(Number.isFinite(j(a,f.field))&&Number.isFinite(j(O,f.field))&&j(O,f.field)>j(a,f.field)))return{status:"invalid",reason:"version-not-advanced",accepted:!0,fixture:c,effect:null,convergence:null,observers:d};const C=f.kind==="version-advance"?j(a,f.field):null,H=f.kind==="version-advance"?j(O,f.field):null,k={kind:f.kind,field:f.field,verified:!0,beforeHash:R,expectedHash:E,afterHash:n,settledHash:l,beforeVersionHash:C==null?null:M(C),afterVersionHash:H==null?null:M(H),versionAdvanced:f.kind==="version-advance"?!0:null},s=d.filter(y=>y.context==="fresh-context"||y.persona===e.writer),g=s.length>0&&s.every(y=>y.status==="measured"&&y.agreed===!0&&y.projection.status==="measured"),w={deadlineMs:b.convergence.deadlineMs,elapsedMs:v,converged:g&&Number.isFinite(v)&&v<=b.convergence.deadlineMs};return g?w.converged?{status:"measured",reason:null,accepted:!0,fixture:c,effect:k,convergence:w,observers:d}:{status:"unmeasured",reason:"convergence-deadline-exceeded",accepted:!0,fixture:c,effect:k,convergence:null,observers:d}:{status:"invalid",reason:"observer-projection-not-converged",accepted:!0,fixture:c,effect:k,convergence:null,observers:d}}function D(e){if(e?.status==="unmeasured")return{status:"unmeasured",state:null,hash:null,reason:e.reason??"unmeasured-representation"};const t=e?.state??"failed";return{status:"measured",state:t,hash:t==="value"?e?.hash??M(e?.value):null,reason:null}}function te(e,t,a,r){const o={authoritative:e,observed:t,typed:!!r?.representation?.type};if(e?.status!=="measured"||t?.status!=="measured")return{agreed:!1,status:"unmeasured",reason:e?.reason??t?.reason??"unmeasured-representation",...o};if(o.typed){const u=ue(e,t,{role:r.role,optionalOnSummary:!!r.representation.optional_on_summary,required:!["absent","redacted","withheld","forbidden"].includes(a?.expect)&&r.representation.optional_on_summary!==!0,expectedState:["absent","redacted","withheld","forbidden"].includes(a?.expect)?a.expect:null});return{...u,status:u.status==="unmeasured"?"unmeasured":"measured",...o}}if(t.state==="loading")return{agreed:!1,status:"unmeasured",reason:"representation-loading",...o};const p=a?.expect;return X(e.state)?p===e.state&&t.state===p?{agreed:!0,status:"measured",reason:"visibility-policy",...o}:{agreed:!1,status:"unmeasured",reason:"authoritative-state-unavailable",...o}:p==="forbidden"?{agreed:t.state==="forbidden"||t.state==="absent",status:"measured",...o}:p==="redacted"||p==="withheld"||p==="absent"?{agreed:t.state===p,status:"measured",...o}:{agreed:e.state===t.state&&e.state!=="value"||e.state==="value"&&t.state==="value"&&e.hash===t.hash,status:"measured",...o}}function he(e,t,a){const r={authoritative:e?.state??"failed",observed:t?.state??"failed"};return r.observed==="loading"?{agreed:!1,status:"unmeasured",reason:"representation-loading",...r}:X(r.authoritative)?a===r.authoritative&&r.observed===a?{agreed:!0,status:"measured",reason:"visibility-policy",...r}:{agreed:!1,status:"unmeasured",reason:"authoritative-state-unavailable",...r}:a==="forbidden"?{agreed:r.observed==="forbidden"||r.observed==="absent",status:"measured",...r}:a==="redacted"||a==="withheld"||a==="absent"?{agreed:r.observed===a,status:"measured",...r}:{agreed:r.authoritative===r.observed&&r.authoritative!=="value"||r.authoritative==="value"&&r.observed==="value"&&M(e.value)===M(t.value),status:"measured",...r}}function ae(e,t){if(!t||!e||e.state!=="value")return e;const a=e.value;return a==null||typeof a!="object"||Array.isArray(a)?e:Object.prototype.hasOwnProperty.call(a,t)?{...e,value:a[t]}:{status:"unmeasured",reason:"readback-missing-field"}}function G(e,t,a,r){if(!r?.representation?.type)return te(D(e),D(t),a,r);const o=r.representation,p=ae(e,o.field),v=ae(t,o.field),u=p?.status==="unmeasured"?p:Y(p?.value,{...o,state:p?.state}),b=v?.status==="unmeasured"?v:Y(v?.value,{...o,state:v?.state});return te(D(u),D(b),a,r)}function de(e){if(e?.identityVersion!==1)return!1;q(e.writerIdentity,"principal");for(const t of e.observers??[])q(t.identity,"principal");for(const t of e.targets??[]){if(q(t.identity,"target"),!t.surfaceMatch?.evidence?.source||!t.surfaceMatch?.evidence?.kind)throw new TypeError("typed-target-surface-evidence-required");q(t.surfaceMatch.surface,"surface")}return!0}function T(e,t){return t?{targetId:e.identity.id,surfaceId:e.surfaceMatch.surface.id}:{targetId:e.id??null}}function ne({observer:e,result:t,comparison:a,typed:r,context:o,transition:p}){const v=e.expect==="visible"?"field-parity":"visibility-policy";return{persona:e.persona,context:o,transition:p,invariant:v,...r?{principalId:e.identity.id,contextId:W(o,p).id,invariantId:Q("invariant",{name:v}).id,expectation:e.expect}:{},status:a.status,agreed:a.status==="measured"?a.agreed:null,reason:a.status==="measured"?null:a.reason??"representation-unmeasured",comparisonReason:a.reason??null,refetched:t.refetched===!0,typed:a.typed===!0,authoritative:a.authoritative,observed:a.observed}}async function ye({spec:e,driver:t}){const a=Array.isArray(e?.targets)?e.targets:[],r=de(e),o=Array.isArray(e?.observers)?e.observers:[],p=o.length,v=o.filter(l=>l.persona!==e.writer).length,u={targets:{planned:a.length,reached:0,compared:0,agreed:0,unmeasured:0},personas:{planned:1+p,completed:0,unmeasured:1+p},contexts:{planned:1+v+a.length*(1+v),completed:0,unmeasured:1+v+a.length*(1+v)},cleanups:{planned:1,completed:0,unmeasured:1}},b=[],d=[];let c;const S={attempted:!1,cleanupOk:null,verificationOk:null};let P=0,O=null,A=null,_=null,F=null,f=null,R=null,E=null,n={status:"measured",counts:u,findings:b,cases:[],mutationAccepted:!1};try{if(e?.causal&&(typeof t.authoritativeReadback!="function"||typeof t.expectedPostMutation!="function"))throw n.status="invalid",n.reason="causal-capability-unavailable",E=n.reason,Object.assign(new Error(n.reason),{code:n.reason});const l=await t.createContext({persona:e.writer,purpose:"writer"});d.push(l),P++;const C=[];for(const s of o){const g=s.persona!==e.writer,w=g?await t.createContext({persona:s.persona,purpose:"observer"}):l;g&&d.push(w);for(const y of a)await t.prime({context:w,target:y,spec:e});C.push({context:w,observer:s,crossPersona:g}),P++}if(e?.causal){if(f=process.hrtime.bigint(),typeof t.authoritativeReadback=="function")try{O=await t.authoritativeReadback({spec:e,mutation:null,phase:"before"})}catch{O=null}const s=N(O);if(!s||s.namespace!==e.fixtureNamespace||s.entity!==e.causal.entity||j(O,e.causal.effect.field)===void 0)throw n.status="invalid",n.reason="causal-pre-state-unavailable",E=n.reason,Object.assign(new Error(n.reason),{code:n.reason});try{A=await t.expectedPostMutation({spec:e,mutation:null,before:O,phase:"before-mutate"})}catch{A=null}const g=N(A);if(!g||g.namespace!==s.namespace||g.entity!==s.entity||g.entityId!==s.entityId||j(A,e.causal.effect.field)===void 0)throw n.status="invalid",n.reason="causal-expected-state-unavailable",E=n.reason,Object.assign(new Error(n.reason),{code:n.reason})}if(c=await t.mutate({context:l,spec:e}),n.mutationAccepted=c?.accepted===!0,!n.mutationAccepted)throw n.status="invalid",n.reason="mutation-not-accepted",Object.assign(new Error(n.reason),{code:n.reason});const H=[];for(const s of a){const g=[];for(const{context:w,observer:y,crossPersona:J}of C)g.push({observer:y,crossPersona:J,result:await t.observe({context:w,target:s,transition:s.transition})});H.push({target:s,observations:g})}const k=await t.authoritativeReadback({spec:e,mutation:c,phase:"after"});_=k;for(const s of H){const g=await t.createContext({persona:e.writer,purpose:"fresh"});d.push(g);const w=await t.observe({context:g,target:s.target,transition:"fresh-context"}),y=[];for(const{observer:i,crossPersona:m}of C){if(!m)continue;const h=await t.createContext({persona:i.persona,purpose:"fresh"});d.push(h);const I=await t.observe({context:h,target:s.target,transition:"fresh-context"});y.push({observer:i,result:I,comparison:I.unmeasured?{agreed:!1,status:"unmeasured",reason:I.unmeasured}:G(k,I.representation,i,s.target)})}const J=s.observations.map(({observer:i,result:m,crossPersona:h})=>{const I=G(k,m.representation,i,s.target),V=h?"cross-persona-warm-cache":m.unmeasured;return{observer:i,result:m,crossPersona:h,comparison:V?{...I,agreed:!1,status:"unmeasured",reason:V,observed:{...I.observed,status:"unmeasured",reason:V}}:I}}),z=G(k,w.representation,{expect:"visible"},s.target),x=w.unmeasured?{...z,agreed:!1,status:"unmeasured",reason:w.unmeasured,observed:{...z.observed,status:"unmeasured",reason:w.unmeasured}}:z;u.targets.reached++;const L={...T(s.target,r),route:s.target.route??null,observations:[...J.map(({observer:i,result:m,comparison:h})=>ne({observer:i,result:m,comparison:h,typed:r,context:"warm-cache",transition:s.target.transition??null})),...y.map(({observer:i,result:m,comparison:h})=>ne({observer:i,result:m,comparison:h,typed:r,context:"fresh-context",transition:"fresh-context"}))],fresh:{persona:e.writer,context:"fresh-context",invariants:["field-parity","durability"],...r?{principalId:e.writerIdentity.id,contextId:W("fresh-context","fresh-context").id,invariantIds:["field-parity","durability"].map(i=>Q("invariant",{name:i}).id),expectation:"visible"}:{},status:x.status,agreed:x.status==="measured"?x.agreed:null,reason:x.status==="measured"?null:x.reason??"representation-unmeasured",authoritative:x.authoritative,observed:x.observed}},U=[...J.filter(({crossPersona:i})=>!i),...y];if(x.status==="unmeasured"||U.some(({comparison:i})=>i.status==="unmeasured")){u.targets.unmeasured++,n.status="invalid";const i=x.status==="unmeasured"?x:U.find(({comparison:m})=>m.status==="unmeasured").comparison;n.reason=i.reason??"representation-unmeasured",n.cases.push({...L,status:"unmeasured",reason:n.reason,comparison:null});continue}u.targets.compared++;const $=U.every(({comparison:i})=>i.agreed)&&x.agreed;$&&u.targets.agreed++;for(const{observer:i,result:m,comparison:h,crossPersona:I}of J){if(I||h.agreed)continue;const V=x.agreed?m.refetched?"coherence.refetched-stale":"coherence.stale-after-write":"coherence.cross-principal-divergence",K=T(s.target,r),re=h.typed&&h.reason==="missing-required-summary"?Z(h,{...K,route:s.target.route??null,persona:i.persona}):null;b.push(re??{kind:V,...K,route:s.target.route??null,persona:i.persona,severity:"P1"})}for(const{observer:i,comparison:m}of y){if(m.agreed)continue;const h=T(s.target,r),I=m.typed&&m.reason==="missing-required-summary"?Z(m,{...h,route:s.target.route??null,persona:i.persona}):null;b.push(I??{kind:"coherence.cross-principal-divergence",...h,route:s.target.route??null,persona:i.persona,severity:"P1"})}x.agreed||b.push({kind:"coherence.write-not-durable",...T(s.target,r),route:s.target.route??null,severity:"P0"}),n.cases.push({...L,status:"measured",comparison:{agreed:$,authoritative:x.authoritative,fresh:x.observed}})}if(e?.causal&&typeof t.authoritativeReadback=="function")try{F=await t.authoritativeReadback({spec:e,mutation:c,phase:"after-observations"})}catch{F=null}f!=null&&(R=Number(process.hrtime.bigint()-f)/1e6)}catch(l){l?.code!=="mutation-not-accepted"&&l?.code!=="causal-capability-unavailable"&&(n.status="invalid",n.reason="observation-failed"),l?.code!=="mutation-not-accepted"&&l?.code!=="causal-capability-unavailable"&&(n.error=String(l?.message??l).split(`
|
|
2
|
+
`)[0].slice(0,200))}finally{if(u.personas.completed=P,u.personas.unmeasured=Math.max(0,u.personas.planned-u.personas.completed),u.contexts.completed=d.length,u.contexts.unmeasured=Math.max(0,u.contexts.planned-u.contexts.completed),c?.accepted){S.attempted=!0;let l,C;try{l=await t.cleanup({spec:e,mutation:c})}catch{l={ok:!1}}try{C=await t.verifyCleanup({spec:e,mutation:c})}catch{C={ok:!1}}S.cleanupOk=l?.ok===!0,S.verificationOk=C?.ok===!0,l?.ok!==!0||C?.ok!==!0?(n.status="invalid",n.reason="cleanup-unmeasured-or-failed",b.push({kind:"crud.cleanup-failed",severity:"P1"})):(u.cleanups.completed=1,u.cleanups.unmeasured=0)}for(const l of d)await t.closeContext(l).catch(()=>{});u.targets.unmeasured=Math.max(u.targets.unmeasured,u.targets.planned-u.targets.compared)}return n.observationEvidence={namespace:"coherence/flow-observation",version:1,mutationAccepted:n.mutationAccepted,targets:n.cases,causal:le(e,c,O,A,[_,F],n.cases,R,E),personasCompleted:u.personas.completed,contextsCompleted:u.contexts.completed,cleanup:S,failureReason:n.reason??null},n.causal=n.observationEvidence.causal,e?.causal&&n.causal.status!=="measured"&&(n.status="invalid",n.reason=n.causal.reason,n.observationEvidence.failureReason=n.reason),n}function xe(e){return e.reduce((t,a)=>{for(const[r,o]of Object.entries(a.counts.targets))t.targets[r]=(t.targets[r]??0)+o;return t},{targets:{}})}export{ge as COHERENCE_OBSERVED_SCHEMA_VERSION,te as compareObservationEvidence,he as compareState,xe as mergeObservationCounts,M as privateHash,ye as runObservationCase};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
async function w({spec:a,driver:e,context:t,mutation:c=null}){if(!a?.offlineReplay?.required)return{status:"unmeasured",reason:"no-declared-offline-oracle",findings:[]};if(["authoritativeReadback","setOffline","mutate","observe","waitForReplay","cleanup","verifyCleanup"].some(f=>typeof e?.[f]!="function"))return{status:"invalid",reason:"offline-driver-incomplete",findings:[]};let n=c,o=!1;try{const f=await e.authoritativeReadback({spec:a,mutation:n});await e.setOffline(t,!0),o=!0,n=n??await e.mutate({context:t,spec:a});const u=await e.observe({context:t,target:a.targets?.[0]??{},transition:"offline-local"});await e.setOffline(t,!1),o=!1;const r=await e.waitForReplay({context:t,spec:a,mutation:n}),l=await e.observe({context:t,target:a.targets?.[0]??{},transition:"offline-replay"}),i=await e.authoritativeReadback({spec:a,mutation:n}),s=await e.observe({context:t,target:a.targets?.[0]??{},transition:"fresh-context"}),g=await e.cleanup({spec:a,mutation:n}),p=await e.verifyCleanup({spec:a,mutation:n});if(!r?.ok||g?.ok!==!0||p?.ok!==!0)return{status:"invalid",reason:r?.ok?"offline-cleanup-failed":"offline-replay-missing",before:f,local:u,longLived:l,authoritative:i,fresh:s,findings:[]};const y=i?.state===s?.representation?.state&&i?.value===s?.representation?.value&&i?.state===l?.representation?.state&&i?.value===l?.representation?.value;return{status:"measured",before:f,local:u,longLived:l,authoritative:i,fresh:s,replay:r,agreed:y,findings:y?[]:[{kind:"coherence.offline-replay-divergence",severity:"P1"}]}}finally{o&&await e?.setOffline?.(t,!1).catch(()=>{})}}function d(a){return a?.status==="measured"?a.findings??[]:[]}export{d as classifyOfflineReplay,w as runOfflineReplay};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{canonicalize as y}from"../jcs.mjs";import{assertCoherenceIdentity as p,validateCoherencePlanIdentities as b}from"./identity.mjs";function I(e,n){if(p(e.mutationIdentity,"mutation"),e.mutationId!==e.mutationIdentity.id)throw new TypeError("typed-journey-mutation-conflict");if(!e.flowIdentity)return null;p(e.flowIdentity,"flow");const t=[];for(const i of n){if(p(i.identity,"flow"),!i.crosscheck?.mutationIdentity)throw new TypeError("typed-flow-mutation-required");p(i.crosscheck.mutationIdentity,"mutation");for(const a of i.crosscheck.targets??[]){if(p(a.identity,"target"),!a.surfaceMatch?.evidence?.source||!a.surfaceMatch?.evidence?.kind)throw new TypeError("typed-target-surface-evidence-required");p(a.surfaceMatch.surface,"surface")}i.identity.id===e.flowIdentity.id&&i.crosscheck.mutationIdentity.id===e.mutationIdentity.id&&t.push(i)}if(t.length>1)throw new TypeError("ambiguous-typed-flow-mutation");return t[0]??null}function R(e,n){if(e?.mutationIdentity)return I(e,n);const t=n.find(o=>o.crosscheck?.plan_journey===e.journeyId);if(t)return t;const i=new Set((e.targets??[]).map(o=>o.family).filter(Boolean)),a=n.find(o=>o.crosscheck?.entity&&i.has(o.crosscheck.entity));return a||(n.find(o=>o.route&&o.route===e.route)??null)}function w(e,n){p(e,"observation-cell");const t=e.coordinates;if(!t||y(e.material)!==y({namespace:"coherence/observation-cell",version:1,...t}))throw new TypeError("typed-obligation-coordinate-conflict");for(const[u,c]of[["mutation","mutation"],["surface","surface"],["principal","principal"],["context","context"],["invariant","invariant"]])p(t[u],c);if(!n)return{status:"unmeasured",reason:"not-reached"};const i=t.context.material.kind,a=t.invariant.material.name,o=i==="fresh-context"?n.fresh:null;if(i==="fresh-context"&&!o&&!(n.observations??[]).length)return{status:"unmeasured",reason:"fresh-context-not-observed"};if(o&&o.principalId===t.principal.id&&o.contextId===t.context.id){if(t.expectation!=="visible"||o.expectation!==t.expectation)throw new TypeError("typed-observation-expectation-conflict");return(o.invariantIds??[]).includes(t.invariant.id)?o.status!=="measured"?{status:"reached",reason:o.reason??"representation-unmeasured"}:{status:o.agreed?"agreed":"disagreed"}:{status:"unmeasured",reason:`invariant-not-observed:${a}`}}const d=(n.observations??[]).find(u=>u.principalId===t.principal.id&&u.contextId===t.context.id);if(!d)return{status:"unmeasured",reason:i==="fresh-context"?"typed-fresh-coordinate-not-observed":"typed-observation-coordinate-not-observed"};if(d.invariantId!==t.invariant.id)return{status:"unmeasured",reason:`invariant-not-observed:${a}`};if(d.expectation!==t.expectation)throw new TypeError("typed-observation-expectation-conflict");return d.status!=="measured"?{status:"reached",reason:d.reason??"representation-unmeasured"}:{status:d.agreed?"agreed":"disagreed"}}function g(e){const n=String(e??"").split("|");if(n.length!==5||n.some(u=>!u))return null;const[t,i,a,o,d]=n;return{mutationId:t,surfaceId:i,principal:a,context:o,invariant:d}}function x(e,n){if(!e)return{status:"unmeasured",reason:"malformed-obligation-id"};if(!n)return{status:"unmeasured",reason:"not-reached"};if(e.context==="fresh-context"){const i=n.fresh?.persona===e.principal?n.fresh:(n.observations??[]).find(o=>o.persona===e.principal&&o.context==="fresh-context");return i?(i.invariants??[i.invariant]).includes(e.invariant)?i.status!=="measured"?{status:"reached",reason:i.reason??"representation-unmeasured"}:{status:i.agreed?"agreed":"disagreed"}:{status:"unmeasured",reason:`invariant-not-observed:${e.invariant}`}:{status:"unmeasured",reason:`persona-not-observed-fresh:${e.principal}`}}const t=(n.observations??[]).find(i=>i.persona===e.principal&&i.context===e.context);return t?t.invariant!==e.invariant?{status:"unmeasured",reason:`invariant-not-observed:${e.invariant}`}:t.status!=="measured"?{status:"reached",reason:t.reason??"representation-unmeasured"}:{status:t.agreed?"agreed":"disagreed"}:{status:"unmeasured",reason:`persona-not-declared:${e.principal}`}}const O={unmeasured:0,reached:1,disagreed:2,agreed:2};function l(e,n){const t={planned:n.length,reached:0,compared:0,agreed:0,disagreed:0,unmeasured:0};for(const a of n){if(a.status==="unmeasured"){t.unmeasured++;continue}t.reached++,a.status!=="reached"&&(t.compared++,a.status==="agreed"?t.agreed++:t.disagreed++)}const i=t.reached===0?"unmeasured":t.disagreed?"disagreed":t.compared<t.planned?"partial":"agreed";return{surfaceId:e.surfaceId,route:e.route,status:i,counts:t,obligations:n}}function $(e,n,t){const i=[...e.obligationIds??[]].sort(),a=n.crosscheck.targets.find(d=>d.route===e.route);if(!a)return{...l(e,i.map(d=>({id:d,status:"unmeasured",reason:"no-declared-target"}))),reason:"no-declared-target"};const o=(t?.cases??[]).find(d=>d.targetId===a.id)??null;return l(e,i.map(d=>({id:d,...x(g(d),o)})))}function T(e,n,t,i){if(p(e.surfaceIdentity,"surface"),e.surfaceId!==e.surfaceIdentity.id)throw new TypeError("typed-plan-surface-conflict");const a=(n.crosscheck.targets??[]).filter(c=>c.surfaceMatch.surface.id===e.surfaceIdentity.id);if(a.length!==1)throw new TypeError(a.length?"ambiguous-declared-target-for-surface":"no-declared-target-for-surface");const o=a[0];if(o.route!==e.route)throw new TypeError("typed-target-route-conflict");const d=(t?.cases??[]).find(c=>c.targetId===o.identity.id&&c.surfaceId===e.surfaceIdentity.id)??null,u=[...e.obligations??[]].sort((c,r)=>c.id.localeCompare(r.id)).map(c=>{if(c.coordinates?.mutation?.id!==i.mutationIdentity.id||c.coordinates?.surface?.id!==e.surfaceIdentity.id)throw new TypeError("typed-obligation-endpoint-conflict");if(c.coordinates.target?.id&&c.coordinates.target.id!==o.identity.id)throw new TypeError("typed-obligation-target-conflict");const r=c.coordinates;return{id:c.id,mutationId:r.mutation.id,targetId:r.target?.id??o.identity.id,surfaceId:r.surface.id,principalId:r.principal.id,contextId:r.context.id,invariantId:r.invariant.id,expectation:r.expectation,...w(c,d)}});return{targetId:o.identity.id,...l(e,u)}}function K(e,n,t){return{journeyId:e.journeyId,flow:n,status:"unmeasured",reason:t,targets:(e.targets??[]).map(i=>({...l(i,[...i.obligationIds??[]].sort().map(a=>({id:a,status:"unmeasured",reason:t}))),reason:t}))}}function A(e,n,t){return{journeyId:e.journeyId,flow:n,status:"unmeasured",reason:t,targets:(e.targets??[]).map(i=>({...l(i,[...i.obligations??[]].sort((a,o)=>a.id.localeCompare(o.id)).map(a=>({id:a.id,mutationId:a.coordinates.mutation.id,targetId:a.coordinates.target?.id??null,surfaceId:a.coordinates.surface.id,principalId:a.coordinates.principal.id,contextId:a.coordinates.context.id,invariantId:a.coordinates.invariant.id,expectation:a.coordinates.expectation,status:"unmeasured",reason:t}))),reason:t}))}}function N(e){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("malformed-coherence-plan");if(Object.hasOwn(e,"schemaVersion")){if(e.schemaVersion===1)return"historical";if(e.schemaVersion===2)return"current";throw new TypeError(`unsupported-coherence-plan-version:${e.schemaVersion}`)}const n=(r,s)=>r&&typeof r=="object"&&!Array.isArray(r)&&Object.keys(r).sort().join("\0")===[...s].sort().join("\0"),t=e.plan?.selected,i=["discovered","resolved","unresolved","planned","reached","compared","agreed"],a=["obligations","discovered","unresolved","mutations","surfaces","principals","contexts","invariants"],o=["unresolvedWriters","unresolvedWriterObligations","writersWithNoReaderSurface","writerFamiliesWithNoReaderSurface"],d=["family","mutations","surfaces","principals","contexts","invariants","possible","excluded","discovered","resolved","unresolved","planned"],u=(r,s)=>n(r,s)&&s.every(f=>Number.isSafeInteger(r[f])&&r[f]>=0);if(!(n(e,["coverage","universe","invariants","families","unattributed","obligationIds","perRoute","plan"])&&u(e.coverage,i)&&u(e.universe,a)&&n(e.unattributed,o)&&o.slice(0,3).every(r=>Number.isSafeInteger(e.unattributed[r])&&e.unattributed[r]>=0)&&Array.isArray(e.unattributed.writerFamiliesWithNoReaderSurface)&&e.unattributed.writerFamiliesWithNoReaderSurface.every(r=>typeof r=="string")&&n(e.plan,["ok","reason","budget","selected","rejected","unselected"])&&typeof e.plan.ok=="boolean"&&(e.plan.reason===null||typeof e.plan.reason=="string")&&typeof e.plan.budget=="number"&&Number.isFinite(e.plan.budget)&&e.plan.budget>=0&&Number.isSafeInteger(e.plan.rejected)&&e.plan.rejected>=0&&Number.isSafeInteger(e.plan.unselected)&&e.plan.unselected>=0&&Array.isArray(e.obligationIds)&&e.obligationIds.every(r=>g(r))&&Array.isArray(e.invariants)&&e.invariants.every(r=>typeof r=="string")&&Array.isArray(e.families)&&e.families.every(r=>n(r,d)&&typeof r.family=="string"&&d.slice(1).filter(s=>s!=="excluded").every(s=>Number.isSafeInteger(r[s])&&r[s]>=0)&&r.excluded&&typeof r.excluded=="object"&&!Array.isArray(r.excluded)&&Object.values(r.excluded).every(s=>Number.isSafeInteger(s)&&s>=0))&&Array.isArray(e.perRoute)&&e.perRoute.every(r=>n(r,["route","obligations","uncovered"])&&typeof r.route=="string"&&Number.isSafeInteger(r.obligations)&&r.obligations>=0&&Number.isSafeInteger(r.uncovered)&&r.uncovered>=0)&&Array.isArray(t)&&t.every(r=>n(r,["journeyId","mutationId","route","covers","weight","cost","targets"])&&typeof r.journeyId=="string"&&typeof r.mutationId=="string"&&typeof r.route=="string"&&Number.isSafeInteger(r.covers)&&r.covers>=0&&Number.isSafeInteger(r.weight)&&r.weight>=0&&typeof r.cost=="number"&&Number.isFinite(r.cost)&&r.cost>=0&&Array.isArray(r.targets)&&r.targets.every(s=>n(s,["surfaceId","route","component","family","obligationIds"])&&typeof s.surfaceId=="string"&&typeof s.route=="string"&&(s.component===null||typeof s.component=="string")&&typeof s.family=="string"&&Array.isArray(s.obligationIds)&&s.obligationIds.every(f=>g(f))))))throw new TypeError("malformed-coherence-plan-hybrid");return"historical"}function M({source:e,runId:n,dimension:t,declaredFlows:i,executedByFlow:a}){if(!t||t.status!=="measured")return{status:"unmeasured",reason:t?.status==="invalid"?"coherence-obligations-invalid":"coherence-obligations-unmeasured"};const o=t.value??{};return N(o)==="historical"?{status:"unmeasured",reason:"legacy-coherence-plan-non-proof"}:S({source:e,runId:n,value:o,declaredFlows:i,executedByFlow:a})}function S({source:e,runId:n,value:t,declaredFlows:i,executedByFlow:a}){b(t);const d=(t.plan?.selected??[]).map(s=>{const f=I(s,i);if(!f)return A(s,null,"no-declared-flow");const m=a.get(f.name),h={journeyId:s.journeyId,flow:f.name,flowId:f.identity.id,status:m?"matched":"unmeasured",targets:(s.targets??[]).map(v=>T(v,f,m,s))};return m||(h.reason="flow-not-executed"),h}),u={discovered:t.coverage?.discovered??0,resolved:t.coverage?.resolved??0,unresolved:t.coverage?.unresolved??0,planned:t.coverage?.planned??0,reached:0,compared:0,agreed:0,disagreed:0},c=d.flatMap(s=>s.targets.flatMap(f=>f.obligations)).sort((s,f)=>s.id.localeCompare(f.id));for(const s of c)s.status!=="unmeasured"&&(u.reached++,s.status!=="reached"&&(u.compared++,s.status==="agreed"?u.agreed++:u.disagreed++));const r=d.filter(s=>s.status==="unmeasured").map(s=>({journeyId:s.journeyId,reason:s.reason,contract:s.reason==="no-declared-flow"?"verify.crud.json schema_version 3: declare a flow with the exact MutationId relation":`run with --flow ${JSON.stringify(s.flow)} (or raise --max-mutations) so the matched flow executes`}));return{status:"measured",source:e,runId:n??null,journeys:d,obligations:c,coverage:u,needed:r}}export{N as classifyCoherencePlan,M as joinPlan,R as matchFlow,g as parseObligationId};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{createHash as u}from"node:crypto";import s from"node:fs";import c from"node:path";import{canonicalize as l}from"../jcs.mjs";import{git as o,run as p}from"../proc.mjs";const f=/PASS|SECRET|TOKEN|KEY|CREDENTIAL/i,d=16*1024;function h(n){return"sha256:"+u("sha256").update(l(n)).digest("hex")}function m(){const n={};for(const[e,t]of Object.entries(process.env))f.test(e)||(n[e]=t);return n}function g(n){const e=o(n,["status","--porcelain=v1","-z"]);return e.code!==0?null:e.stdout.split("\0").filter(Boolean).sort()}function P(n){const e=s.realpathSync(n),t=o(e,["rev-parse","HEAD"]),r=g(e);if(t.code!==0||!/^[0-9a-f]{40}$/i.test(t.stdout.trim())||r==null)throw new Error(`cannot determine source identity for ${n}`);return{repoRealPath:e,gitSha:t.stdout.trim(),dirtyDigest:h(r),clean:r.length===0}}function y(n){if(Buffer.byteLength(n)>d)return null;const e=n.trim().split(`
|
|
2
|
+
`).filter(Boolean);if(e.length!==1)return null;try{const t=JSON.parse(e[0]);return!t||t.ok!==!0||typeof t.repoRealPath!="string"||!t.repoRealPath||!/^[0-9a-f]{40}$/i.test(t.gitSha??"")||!/^sha256:[0-9a-f]{64}$/.test(t.dirtyDigest??"")||typeof t.clean!="boolean"||typeof t.buildId!="string"||!t.buildId?null:{repoRealPath:t.repoRealPath,gitSha:t.gitSha,dirtyDigest:t.dirtyDigest,clean:t.clean,buildId:t.buildId}}catch{return null}}async function D({repo:n,base:e,adapterPath:t,timeoutMs:r=15e3}){if(!t||!s.existsSync(t))return{status:"unmeasured",reason:"no-provenance-adapter"};const i=await p(process.execPath,[t],{cwd:n,env:m(),replaceEnv:!0,fd3:JSON.stringify({base:e}),stdout:"capture",stderr:"capture",timeoutMs:r});if(i.timedOut)return{status:"invalid",reason:"provenance-timeout"};if(i.code!==0)return{status:"invalid",reason:"provenance-adapter-exit"};const a=y(i.stdout);return a?{status:"measured",provenance:a}:{status:"invalid",reason:"provenance-bad-status"}}function I(n,e){const t=[];return!e||typeof e!="object"?t.push("missing-served-provenance"):(c.resolve(e.repoRealPath)!==n.repoRealPath&&t.push("repo-path-mismatch"),e.gitSha!==n.gitSha&&t.push("git-sha-mismatch"),e.dirtyDigest!==n.dirtyDigest&&t.push("dirty-digest-mismatch"),e.clean!==n.clean&&t.push("clean-state-mismatch"),(typeof e.buildId!="string"||!e.buildId)&&t.push("missing-build-id")),{status:t.length?"invalid":"measured",problems:t,archivable:t.length===0}}export{I as compareProvenance,P as expectedSourceIdentity,D as loadServedProvenance};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const v=Object.freeze({invalid:4,partial:3,unmeasured:2,measured:1}),i=()=>({planned:0,reached:0,compared:0,agreed:0,unmeasured:0}),u=()=>({discovered:0,resolved:0,unresolved:0,planned:0,reached:0,compared:0,agreed:0});function p(r){const a=new Map;for(const t of r?.cases??[])for(const e of t.findings??[]){const n=e.rootCauseId??t.rootCauseId??`case:${t.id??"unknown"}`,s=a.get(n)??{rootCauseId:n,surfaces:new Set,routes:new Set,kinds:new Set,severity:e.severity??"P3"};e.surfaceId?s.surfaces.add(e.surfaceId):e.route&&s.surfaces.add(e.route),e.route&&s.routes.add(e.route),s.kinds.add(e.kind),(e.severity??"P3")<s.severity&&(s.severity=e.severity??"P3"),a.set(n,s)}return[...a.values()].map(t=>({...t,surfaces:[...t.surfaces].sort(),routes:[...t.routes].sort(),kinds:[...t.kinds].sort()})).sort((t,e)=>String(t.severity).localeCompare(String(e.severity))||t.rootCauseId.localeCompare(e.rootCauseId))}function m({linked:r,inventory:a}){const t=a?.coherence?.counts??a?.coherence?.coverage?.counts??{},e={discovered:t.mutationsDiscovered??t.writeCandidates??0,resolved:t.mutationsResolved??t.writesResolved??0,declared:0,executed:0};if(r?.status==="invalid")return{status:"invalid",provenance:{status:"invalid",problems:r.problems??["linked coherence artifact is invalid"]},mutations:e,obligations:u(),targets:i(),contexts:{planned:0,primed:0,observed:0},transitions:{planned:0,executed:0},enumCases:{discovered:0,planned:0,executed:0},clusters:[],unmeasuredReasons:[],artifactRef:r.path??null};if(!r?.report||r.status!=="linked")return{status:"unmeasured",provenance:{status:"unmeasured",problems:[]},mutations:e,obligations:u(),targets:i(),contexts:{planned:0,primed:0,observed:0},transitions:{planned:0,executed:0},enumCases:{discovered:0,planned:0,executed:0},clusters:[],unmeasuredReasons:["runtime coherence evidence not linked"],artifactRef:null};const n=r.report,s=n.counts??{},c=Array.isArray(n.provenance)?n.provenance[0]??{status:"unmeasured",problems:[]}:n.provenance??{status:"unmeasured",problems:[]};let o=n.status??"invalid";const d=s.targets??i();c.status==="invalid"||o==="invalid"?o="invalid":(d.unmeasured||d.planned!==d.compared||(s.transitions?.planned??0)!==(s.transitions?.executed??0)||(s.enumCases?.planned??0)!==(s.enumCases?.executed??0))&&(o="partial");const l={...e,...s.mutations??{}};return{status:o,provenance:c,mutations:l,obligations:s.obligations??u(),targets:d,contexts:s.contexts??{planned:0,primed:0,observed:0},transitions:s.transitions??{planned:0,executed:0},enumCases:s.enumCases??{discovered:0,planned:0,executed:0},clusters:p(n),unmeasuredReasons:[...new Set(n.unmeasured??(n.reason?[n.reason]:[]))].sort(),artifactRef:r.path??null}}const f=(r,a)=>m({linked:r?{status:"linked",report:r}:null,inventory:a});export{v as COHERENCE_STATUS_ORDER,p as coherenceClusters,f as coherenceCoverage,m as coherenceReportModel};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createHash as g}from"node:crypto";import{canonicalize as y}from"../jcs.mjs";const b=t=>"sha256:"+g("sha256").update(y(t)).digest("hex"),h=t=>({status:"measured",state:t,canonical:null,hash:null}),f=new Set(["failed","withheld","redacted","loading","forbidden"]),F=t=>f.has(t);function i(t){return{status:"unmeasured",reason:t}}function d(t){if(typeof t=="number")return Number.isFinite(t)?t:null;const e=String(t??"").trim();if(!/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/.test(e))return null;const r=Number(e);return Number.isFinite(r)?r:null}function c(t,e,r={}){if(typeof t=="number")return Number.isFinite(t)?t:null;const n=String(t??"").trim().match(/^([+-]?(?:\d+(?:\.\d+)?|\.\d+))(?:\s*([A-Za-z]+))?$/);if(!n)return null;const a=n[2]==null?null:r[n[2].toLowerCase()]??n[2].toLowerCase();return a!=null&&a!==e?null:d(n[1])}function S(t,e,r){let n=typeof t=="number"?String(t):String(t??"").trim();if(typeof t=="number"&&(!Number.isFinite(t)||Math.abs(t)>Number.MAX_SAFE_INTEGER)||n.startsWith("$")&&r!=="USD"||(n=n.replace(/^\$/,""),!/^[+-]?(?:\d{1,3}(?:,\d{3})*|\d+)(?:\.\d+)?$/.test(n)))return null;const a=n.startsWith("-"),s=n.replace(/^[+-]/,"").replaceAll(",",""),[o,u=""]=s.split(".");if(u.length>e&&/[^0]/.test(u.slice(e)))return null;const m=BigInt(o)*10n**BigInt(e)+BigInt((u.slice(0,e)+"0".repeat(e)).slice(0,e)),l=a?-m:m;return l<BigInt(Number.MIN_SAFE_INTEGER)||l>BigInt(Number.MAX_SAFE_INTEGER)?null:Number(l)}function p(t,e,r){const n=new Date(0);return n.setUTCFullYear(t,e-1,r),n.getUTCFullYear()===t&&n.getUTCMonth()===e-1&&n.getUTCDate()===r}function x(t,e={}){const r=e.state??(t==null?"absent":String(t)===""?"empty":"value");if(r==="loading")return i("representation-loading");if(r!=="value")return h(r);let n;if(e.type==="string"||!e.type)n=String(t).normalize("NFC").trim();else if(e.type==="number"){if(n=d(t),n==null)return{status:"unmeasured",reason:"invalid-number"}}else if(e.type==="count"){if(n=d(t),n==null||!Number.isSafeInteger(n)||n<0)return{status:"unmeasured",reason:"invalid-count"}}else if(e.type==="boolean")if(t===!0||t===!1)n=t;else if(typeof t=="string"&&/^(true|false)$/.test(t.trim().toLowerCase()))n=t.trim().toLowerCase()==="true";else return i("invalid-boolean");else if(e.type==="money"){if(!e.currency||!Number.isSafeInteger(e.scale)||e.scale<0||e.scale>6)return i("missing-money-semantics");const a=S(t,e.scale,e.currency);if(a==null)return i("invalid-money-precision");n={currency:e.currency,minor:a}}else if(e.type==="date"){if(!e.locale)return i("missing-date-locale");const a=String(t).match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/);if(!a||e.locale!=="en-US")return i("unsupported-date-format");const[,s,o,u]=a.map(Number);if(!p(u,s,o))return i("invalid-calendar-date");n=`${String(u).padStart(4,"0")}-${String(s).padStart(2,"0")}-${String(o).padStart(2,"0")}`}else{if(e.type==="enum")return i("unsupported-enum-semantics");if(e.type==="datetime")return i("unsupported-datetime-semantics");if(e.type==="duration"){if(!e.inputUnit||!e.canonicalUnit)return{status:"unmeasured",reason:"missing-duration-semantics"};const a=c(t,e.inputUnit,{min:"minute",mins:"minute",sec:"second",secs:"second",hr:"hour",hrs:"hour"}),s={minute:60,second:1,hour:3600};if(a==null||s[e.inputUnit]==null||e.canonicalUnit!=="second")return{status:"unmeasured",reason:"unsupported-duration-semantics"};if(n=a*s[e.inputUnit],!Number.isFinite(n))return{status:"unmeasured",reason:"duration-overflow"}}else if(e.type==="unit"){if(!e.inputUnit||!e.canonicalUnit||!Number.isFinite(e.factor))return{status:"unmeasured",reason:"missing-unit-semantics"};const a=c(t,e.inputUnit);if(a==null)return{status:"unmeasured",reason:"invalid-unit"};if(n=a*e.factor,!Number.isFinite(n))return{status:"unmeasured",reason:"unit-overflow"}}else return{status:"unmeasured",reason:"unsupported-representation-type"}}return{status:"measured",state:"value",canonical:n,hash:b(n)}}function I(t,e,r={}){if(t.status!=="measured"||e.status!=="measured")return{agreed:!1,status:"unmeasured",reason:t.reason??e.reason??"unmeasured-representation"};if(e.state==="loading")return{agreed:!1,status:"unmeasured",reason:"representation-loading"};if(f.has(t.state))return r.expectedState&&r.expectedState===t.state&&r.expectedState===e.state?{agreed:!0,reason:"visibility-policy"}:{agreed:!1,status:"unmeasured",reason:"authoritative-state-unavailable"};const n=r.expectedState;return!n&&r.role==="summary"&&r.optionalOnSummary&&e.state==="absent"?{agreed:!0,reason:"optional-on-summary"}:e.state==="absent"&&r.required?{agreed:!1,reason:"missing-required-summary"}:n&&(n==="forbidden"?!["forbidden","absent"].includes(e.state):e.state!==n)?{agreed:!1,reason:"visibility-policy-divergence"}:n==="forbidden"&&["forbidden","absent"].includes(e.state)?{agreed:!0,reason:"visibility-policy"}:n&&e.state===n&&(t.state==="value"||t.state===n)?{agreed:!0,reason:"visibility-policy"}:t.state!==e.state?{agreed:!1,reason:"honesty-state-divergence"}:t.state!=="value"?{agreed:!0,reason:"same-state"}:t.hash===e.hash?{agreed:!0,reason:"same-canonical-value"}:{agreed:!1,reason:"different-value"}}function w(t,e){return t.agreed?null:{kind:t.reason==="missing-required-summary"?"coherence.missing-required-summary":"coherence.representation-divergence",severity:t.reason==="missing-required-summary"?"P2":"P1",...e}}export{I as compareRepresentations,F as isUnavailableAuthoritativeState,x as normalizeRepresentation,w as representationFinding};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import W from"node:path";import{git as B}from"../proc.mjs";const v=90;function D(t,{windowDays:a=v}={}){const s=B(t,["log",`--since=${a}.days.ago`,"--name-only","--pretty=format:%H","--no-merges"]);if(s.code!==0)return{status:"unmeasured",reason:"git-log-failed",counts:new Map,commits:0};const n=new Map;let r=0,i=null;for(const o of s.stdout.split(`
|
|
2
|
+
`)){const u=o.trim();if(u){if(/^[0-9a-f]{40}$/i.test(u)){r++,i=new Set;continue}!i||i.has(u)||(i.add(u),n.set(u,(n.get(u)??0)+1))}}return r?{status:"measured",reason:null,counts:n,commits:r}:{status:"unmeasured",reason:"no-commits-in-window",counts:n,commits:0}}function V(t,{reads:a,mutations:s,surfaces:n}){const r=new Set;for(const i of t.mutationIds??[]){const o=s.get(i);o?.file&&r.add(o.file)}for(const i of t.readIds??[]){const o=a.get(i);o?.file&&r.add(o.file)}for(const i of t.surfaceIds??[]){const o=n.get(i);o?.file&&r.add(o.file)}return[...r].sort()}const $=t=>t==null?null:Math.round(t*1e3)/1e3;function H({repo:t,coherence:a,observed:s=null,mandatoryRoutes:n=[],windowDays:r=v,changes:i=null}){const o=a?.resourceFamilies??[],u=new Map((a?.reads??[]).map(e=>[e.id,e])),w=new Map((a?.mutations??[]).map(e=>[e.id,e])),x=new Map((a?.surfaces??[]).map(e=>[e.id,e])),l=i??D(t,{windowDays:r}),O=new Set(n),R=[3,4].includes(s?.schemaVersion)&&s.status==="measured"?s:null,I=new Set,p=new Map,j=e=>w.get(e?.mutationId)?.family??null;for(const e of R?.plan?.journeys??[])for(const c of e.targets??[])for(const m of c.obligations??[]){const f=j(m);f&&((m.status==="agreed"||m.status==="disagreed")&&I.add(f),m.status==="disagreed"&&p.set(f,(p.get(f)??0)+1))}const d=o.map(e=>{const c=V(e,{reads:u,mutations:w,surfaces:x}),f=1+(e.surfaceIds??[]).filter(y=>O.has(x.get(y)?.route)).length+(p.get(e.family)??0),A=(e.invalidationsUnresolved??0)+(e.readsUnresolvedKey??0),C=(e.invalidations??0)+(e.readIds??[]).length,k=!I.has(e.family),F=(A+1)/(C+1)*(k?2:1),M=(e.surfaceIds??[]).length,h=l.status==="measured"?c.reduce((y,U)=>y+(l.counts.get(U)??0),0):null,g=h==null?null:h/r;return{family:e.family,files:c,impact:f,uncertainty:$(F),affectedSurfaces:M,commits:h,changeRate:$(g),risk:g==null?null:$(f*F*M*g),reason:g==null?l.reason:null,neverCompared:k,remeasureOn:c}});d.sort((e,c)=>(c.risk??-1)-(e.risk??-1)||e.family.localeCompare(c.family));const S=d.filter(e=>e.risk!=null).length;return{schemaVersion:1,status:o.length===0?"unmeasured":l.status==="measured"?"measured":"unmeasured",reason:o.length===0?"no-resource-families":l.status==="measured"?null:l.reason,windowDays:r,commitsInWindow:l.commits,counts:{families:d.length,ranked:S,unmeasured:d.length-S},families:d}}function K(t,{max:a=10}={}){const s=[];if(!t?.families?.length)return s;s.push(`risk (impact x uncertainty x surfaces x change-rate over ${t.windowDays}d): ${t.counts.ranked} ranked / ${t.counts.families} families`);for(const n of t.families.slice(0,a))s.push(n.risk==null?` ${n.family}: unmeasured (${n.reason})`:` ${n.family}: ${n.risk} = ${n.impact} x ${n.uncertainty} x ${n.affectedSurfaces} x ${n.changeRate} (${n.commits} commit(s))`);return t.families.length>a&&s.push(` ... ${t.families.length-a} more`),s}const L=t=>W.join(t,".verify","coherence-risk.json");export{D as changeCountsByFile,H as coherenceRisk,K as renderRisk,L as riskArtifactPath};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import{parseTypedKeyExpression as C}from"./cache-key.mjs";const w=new Map;let k=0;const A=32*1024*1024;function y(l,r,t){const i=(r.length+t.length)*2;return i>A||(k+i>A&&(w.clear(),k=0),w.set(l+r,t),k+=i),t}function S(l){const r=w.get("comments:"+l);if(r!==void 0)return r;let t="",i="code",o=!1;for(let c=0;c<l.length;c++){const s=l[c],f=l[c+1];if(i==="line"){t+=s===`
|
|
2
|
+
`?(i="code",`
|
|
3
|
+
`):" ";continue}if(i==="block"){s==="*"&&f==="/"?(t+=" ",c++,i="code"):t+=s===`
|
|
4
|
+
`?`
|
|
5
|
+
`:" ";continue}if(i!=="code"){t+=s,!o&&s===i&&(i="code"),o=!o&&s==="\\",s!=="\\"&&(o=!1);continue}if(s==="/"&&f==="/"){t+=" ",c++,i="line";continue}if(s==="/"&&f==="*"){t+=" ",c++,i="block";continue}t+=s,(s==="'"||s==='"'||s==="`")&&(i=s)}return y("comments:",l,t)}function E(l){const r=w.get("code:"+l);if(r!==void 0)return r;let t="";const i=(a,n)=>({type:"code",interpolationDepth:a,regexAllowed:!0,statementStart:n,parens:[],braces:[],pendingControl:null,blockExpected:null,afterArrow:!1,declarationPrefix:!1}),o=[i(0,!0)],c=a=>a===`
|
|
6
|
+
`?`
|
|
7
|
+
`:" ",s=new Set(["await","case","delete","in","instanceof","new","of","return","throw","typeof","void","yield"]),f=new Set(["catch","for","if","switch","while","with"]),h=new Set(["do","else"]),g=new Set(["finally","try"]),p=()=>{const a=o.at(-1);a?.type==="code"&&(a.regexAllowed=!1,a.statementStart=!1,a.pendingControl=null,a.afterArrow=!1,a.declarationPrefix=!1)};for(let a=0;a<l.length;a++){const n=l[a],x=l[a+1],e=o.at(-1);if(e.type==="line"){t+=c(n),n===`
|
|
8
|
+
`&&o.pop();continue}if(e.type==="block"){n==="*"&&x==="/"?(t+=" ",a++,o.pop()):t+=c(n);continue}if(e.type==="string"){t+=c(n),e.escape?e.escape=!1:n==="\\"?e.escape=!0:n===e.quote&&(o.pop(),p());continue}if(e.type==="regex"){if(e.closed){if(/[dgimsuvy]/.test(n)){t+=" ";continue}o.pop(),p(),a--;continue}if(n===`
|
|
9
|
+
`||n==="\r"){o.pop(),p(),a--;continue}t+=" ",e.escape?e.escape=!1:n==="\\"?e.escape=!0:n==="["?e.characterClass=!0:n==="]"?e.characterClass=!1:n==="/"&&!e.characterClass&&(e.closed=!0);continue}if(e.type==="template"){if(e.escape){t+=c(n),e.escape=!1;continue}if(n==="\\"){t+=" ",e.escape=!0;continue}if(n==="`"){t+=" ",o.pop(),p();continue}if(n==="$"&&x==="{"){t+=" ",a++,o.push(i(1,!1));continue}t+=c(n);continue}if(n==="/"&&x==="/"){t+=" ",a++,o.push({type:"line"});continue}if(n==="/"&&x==="*"){t+=" ",a++,o.push({type:"block"});continue}if(n==="/"&&e.regexAllowed&&l[a-1]!=="<"){t+=" ",o.push({type:"regex",escape:!1,characterClass:!1,closed:!1});continue}if(n==="'"||n==='"'){t+=" ",o.push({type:"string",quote:n,escape:!1});continue}if(n==="`"){t+=" ",o.push({type:"template",escape:!1});continue}if(n==="("){e.parens.push({control:e.pendingControl,blockAfter:e.blockExpected}),e.pendingControl=null,e.blockExpected=null,e.afterArrow=!1,e.regexAllowed=!0,e.statementStart=!1,t+=n;continue}if(n===")"){const u=e.parens.pop();e.blockExpected=u?.blockAfter??null,e.regexAllowed=!!u?.control,e.statementStart=!!u?.control,e.pendingControl=null,e.afterArrow=!1,t+=n;continue}if(n==="{"){const u=e.blockExpected??(e.afterArrow?"value-block":e.statementStart||e.pendingControl==="catch"?"block":"object");e.braces.push(u),e.interpolationDepth&&e.interpolationDepth++,e.regexAllowed=!0,e.statementStart=u!=="object",e.pendingControl=null,e.blockExpected=null,e.afterArrow=!1,e.declarationPrefix=!1,t+=n;continue}if(n==="}"){if(e.interpolationDepth&&(e.interpolationDepth--,e.interpolationDepth===0)){t+=" ",o.pop();continue}const u=e.braces.pop()??"block";e.regexAllowed=u==="block",e.statementStart=u==="block",e.pendingControl=null,e.blockExpected=null,e.afterArrow=!1,e.declarationPrefix=!1,t+=n;continue}if(/[A-Za-z_$]/.test(n)){let u=a+1;for(;u<l.length&&/[\w$]/.test(l[u]);)u++;const d=l.slice(a,u);t+=d;const b=e.regexAllowed,m=e.statementStart;e.pendingControl==="for"&&d==="await"||(e.pendingControl=b&&f.has(d)?d:null),(d==="function"||d==="class")&&l.slice(0,a).trimEnd().at(-1)!=="."?(e.blockExpected=m||e.declarationPrefix?"block":"value-block",e.declarationPrefix=!1):g.has(d)&&l.slice(0,a).trimEnd().at(-1)!=="."?(e.blockExpected="block",e.declarationPrefix=!1):d==="export"&&m||(d==="default"||d==="async")&&(m||e.declarationPrefix)?e.declarationPrefix=!0:(d!=="await"||e.pendingControl!=="for")&&(e.declarationPrefix=!1),e.statementStart=b&&h.has(d),e.regexAllowed=s.has(d)||e.statementStart,e.afterArrow=!1,a=u-1;continue}if((n==="+"||n==="-")&&x===n){t+=n+x,e.statementStart=!1,a++;continue}t+=n,!/\s/.test(n)&&(e.pendingControl=null,e.declarationPrefix=!1,n===";"?(e.regexAllowed=!0,e.statementStart=!0):n==="/"||"=!&|+*%^~<>".includes(n)||"[,?:".includes(n)?(e.regexAllowed=!0,e.statementStart=!1,e.afterArrow=n===">"&&l[a-1]==="="):(e.regexAllowed=!1,e.statementStart=!1,e.afterArrow=!1))}return y("code:",l,t)}function v(l,r,t=null){const i={"(":")","[":"]","{":"}"},o=l[r];if(!i[o])return null;const c=t??E(l);let s=[i[o]];for(let f=r+1;f<c.length;f++){const h=c[f];if(i[h])s.push(i[h]);else if(h===s.at(-1)&&(s.pop(),!s.length))return{text:l.slice(r,f+1),end:f+1}}return null}function B(l,r=","){const t=[],i=S(l);let o=0,c=[],s=null,f=!1;const h={"(":")","[":"]","{":"}"};for(let g=0;g<i.length;g++){const p=i[g];if(s){!f&&p===s&&(s=null),f=!f&&p==="\\",p!=="\\"&&(f=!1);continue}if(p==="'"||p==='"'||p==="`"){s=p;continue}h[p]?c.push(h[p]):p===c.at(-1)?c.pop():p===r&&!c.length&&(t.push(l.slice(o,g).trim()),o=g+1)}return t.push(l.slice(o).trim()),t.filter(Boolean)}function P(l,r){return l.slice(0,r).split(`
|
|
10
|
+
`).length}function D(l){const r=new Map,t=S(l),i=/\bconst\s+([A-Za-z_$][\w$]*)\s*=\s*/g;let o;for(;o=i.exec(t);){let c=o.index+o[0].length;for(;c<t.length&&!`;
|
|
11
|
+
`.includes(t[c]);)c++;const s={expression:l.slice(o.index+o[0].length,c).trim(),start:o.index,line:P(l,o.index)};r.set(o[1],[...r.get(o[1])??[],s])}return r}function M(l,r){const t=r instanceof Map?{bindings:r}:r??{};return C(l,t)}function $(l,r){let t=r;for(;t<l.length&&/\s/.test(l[t]);)t++;if(l[t]==="<"){let i=0;for(;t<l.length&&t<r+400;t++)if(l[t]==="<")i++;else if(l[t]===">"&&l[t-1]!=="="&&(i--,i===0)){t++;break}for(;t<l.length&&/\s/.test(l[t]);)t++}return l[t]==="("?t:-1}export{v as balancedSlice,$ as callParen,D as collectConstBindings,P as lineAt,S as maskComments,E as maskNonCode,M as parseKeyExpression,B as splitTopLevel};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import{balancedSlice as B,maskComments as W,maskNonCode as Z}from"./structural-js.mjs";const E="[A-Za-z_$][\\w$]*",J=24,P=/(?:^|\n)\s*import\s+(?!\s*\()(?:((?:type\s+)?(?:[A-Za-z_$][\w$]*\s*,\s*)?(?:\{[^}]*\}|\*\s+as\s+[A-Za-z_$][\w$]*|[A-Za-z_$][\w$]*))\s+from\s+)?['"]([^'"]+)['"]/g;function T(a){const n=Z(a);return[...a.matchAll(P)].filter(o=>n.slice(o.index+o[0].indexOf("import")).startsWith("import"))}function j(a){return a.startsWith(".")||a.startsWith("/")||a.startsWith("@/")||a.startsWith("~/")}function M(a,n,o,c){const s=n.slice(0,o);return{file:a,start:o,end:c,line:s.split(`
|
|
2
|
+
`).length,column:o-s.lastIndexOf(`
|
|
3
|
+
`)}}function I(a){return a.sort((n,o)=>JSON.stringify(n).localeCompare(JSON.stringify(o)))}function K({file:a,source:n=""}){const o=W(n),c=[],s=(t,l,r)=>{const f=t[0].lastIndexOf(r),i=t.index+f;c.push({specifier:r,kind:l,resolvedFile:null,span:M(a,n,i,i+r.length)})};for(const t of T(o))s(t,"static-import",t[2]);for(const t of o.matchAll(/\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g))s(t,"dynamic-import",t[1]);for(const t of o.matchAll(/(?:^|\n)\s*export\s*\{[^}\n]*\}\s*from\s*['"]([^'"]+)['"]/g))s(t,"named-reexport",t[1]);for(const t of o.matchAll(/(?:^|\n)\s*export\s*\*\s*from\s*['"]([^'"]+)['"]/g))s(t,"export-star",t[1]);return I(c)}function D(a,n,o){const c=(a.moduleRefs??[]).filter(r=>r.specifier===n&&r.kind===o);if(c.length)return c[0];const s=[...new Set(a.imports??[])];if(s.length===1)return{specifier:n,kind:o,resolvedFile:s[0],span:null};const t=n.replace(/^.*\//,"").replace(/\.[^.]+$/,""),l=s.filter(r=>r.replace(/^.*\//,"").replace(/\.[^.]+$/,"")===t);return{specifier:n,kind:o,resolvedFile:l.length===1?l[0]:null,span:null}}function z(a,n){let o=n;for(;/\s/.test(a[o]??"");)o++;return o}function C(a,n,o,c=!1){let s=z(n,o);/^async\b/.test(n.slice(s))&&(s=z(n,s+5));let t=s,l=s;if(n[s]==="("){const m=B(a,s,c?n:null);if(!m)return null;t=s+1,l=m.end-1,s=m.end}else{const m=n.slice(s).match(new RegExp(`^(${E})`));if(!m)return null;l=s+m[1].length,s=l}const r=n.indexOf("=>",s);if(r<0||/[;=\n]/.test(n.slice(s,r)))return null;const f=n.slice(s,r).trim();if(f&&!f.startsWith(":"))return null;const i=z(n,r+2);if(n[i]==="{"){const m=B(a,i,c?n:null);return m?{paramsStart:t,paramsEnd:l,bodyStart:i+1,end:m.end}:null}if("([".includes(n[i])){const m=B(a,i,c?n:null);return m?{paramsStart:t,paramsEnd:l,bodyStart:i,end:m.end}:null}let d=i;for(;d<a.length&&!`;
|
|
4
|
+
`.includes(n[d]);)d++;return{paramsStart:t,paramsEnd:l,bodyStart:i,end:d}}function Q(a){const{file:n,source:o=""}=a,c=W(o),s=[];for(const t of c.matchAll(new RegExp(`\\b(export\\s+)?(default\\s+)?(?:async\\s+)?function\\s+(${E})\\s*\\(`,"g"))){const l=t[3],r=c.indexOf("(",t.index),f=B(o,r),i=f?c.indexOf("{",f.end):-1,d=i>=0?B(o,i):null,m=t.index+t[0].lastIndexOf(l),w=o.indexOf(`
|
|
5
|
+
`,t.index+t[0].length);s.push({key:`${n}#${l}`,file:n,name:l,kind:"function",exported:!!t[1],default:!!t[2],presentation:/^[A-Z]/.test(l),span:M(n,o,m,m+l.length),start:t.index,paramsStart:r+1,paramsEnd:f?.end?f.end-1:r+1,bodyStart:i>=0?i+1:t.index+t[0].length,end:d?.end??(w<0?o.length:w),supported:!!d})}for(const t of c.matchAll(new RegExp(`\\b(export\\s+)?const\\s+(${E})\\s*=`,"g"))){const l=s.filter(O=>O.bodyStart<=t.index&&t.index<O.end).sort((O,y)=>O.end-O.bodyStart-(y.end-y.bodyStart))[0],r=t[2],f=t.index+t[0].lastIndexOf(r),i=C(o,c,t.index+t[0].length);if(l&&!i)continue;let d=o.indexOf(`
|
|
6
|
+
`,t.index+t[0].length);d<0&&(d=o.length);const m=z(c,t.index+t[0].length),w="([{".includes(c[m]??"")?B(o,m):null;s.push({key:l?`${l.key}/${r}@${t.index}`:`${n}#${r}`,...l?{scope:{start:l.bodyStart,end:l.end}}:{},file:n,name:r,kind:"const",exported:!!t[1],default:!1,presentation:/^[A-Z]/.test(r),span:M(n,o,f,f+r.length),start:t.index,paramsStart:i?.paramsStart??t.index+t[0].length,paramsEnd:i?.paramsEnd??t.index+t[0].length,bodyStart:i?.bodyStart??t.index+t[0].length,end:i?.end??w?.end??d,supported:!!i})}return s}function U(a,n,o,{masked:c=!1}={}){const s=c?a:Z(a),t=n.replace(/[$]/g,"\\$&"),l=(f,i)=>f<=o&&o<i,r=f=>B(a,f,s);for(const f of s.matchAll(/\(/g)){const i=r(f.index);if(!i||!new RegExp(`\\b${t}\\b`).test(i.text))continue;const d=C(a,s,f.index,!0);if(d&&l(d.bodyStart,d.end))return!0}for(const f of s.matchAll(new RegExp(`\\b${t}\\b\\s*=>`,"g"))){const i=C(a,s,f.index,!0);if(i&&l(i.bodyStart,i.end))return!0}for(const f of s.matchAll(new RegExp(`\\bfunction(?:\\s+${E})?\\s*\\(`,"g"))){const i=s.indexOf("(",f.index),d=r(i);if(!d||!new RegExp(`\\b${t}\\b`).test(d.text))continue;const m=s.indexOf("{",d.end),w=m>=0?r(m):null;if(w&&l(m+1,w.end))return!0}for(const f of s.matchAll(/\bcatch\s*\(([^)]*)\)\s*\{/g)){if(!new RegExp(`\\b${t}\\b`).test(f[1]))continue;const i=f.index+f[0].lastIndexOf("{"),d=r(i);if(d&&l(i+1,d.end))return!0}return!1}function H(a,n,o,c){const s=n.replace(/[$]/g,"\\$&");return new RegExp(`\\b${s}\\b`).test(o.slice(a.paramsStart,a.paramsEnd))||new RegExp(`\\b(?:const|let|var|function|class)\\s+(?:${s}\\b|\\{[^}]*\\b${s}\\b)`).test(o.slice(a.bodyStart,a.end))?!0:U(o.slice(a.bodyStart,a.end),n,c-a.bodyStart,{masked:!0})}function X(a){const{file:n,source:o=""}=a,c=[],s=[],t=W(o);for(const l of T(t)){if(!l[1])continue;const r=l[1].trim(),f=l[2],i=D(a,f,"static-import"),d=(y,F,L)=>c.push({file:n,local:y,imported:F,kind:L,specifier:f,resolvedFile:i.resolvedFile,source:i.span??M(n,o,l.index,l.index+l[0].length)}),m=r.match(/\{([^}]*)\}/)?.[1];if(m!=null)for(const y of m.split(",").map(F=>F.trim()).filter(Boolean)){const F=y.match(new RegExp(`^(${E})(?:\\s+as\\s+(${E}))?$`));F&&d(F[2]??F[1],F[1],"named")}const w=r.match(new RegExp(`\\*\\s+as\\s+(${E})`));w&&d(w[1],"*","namespace");const O=r.match(new RegExp(`^(${E})(?:\\s*,|$)`));O&&d(O[1],"default","default")}for(const l of t.matchAll(/(?:^|\n)\s*export\s*\{([^}\n]*)\}(?:\s*from\s*['"]([^'"]+)['"])?/g)){const r=l[2]??null,f=r?D(a,r,"named-reexport"):null;for(const i of l[1].split(",").map(d=>d.trim()).filter(Boolean)){const d=i.match(new RegExp(`^(${E})(?:\\s+as\\s+(${E}))?$`));d&&s.push({file:n,name:d[2]??d[1],local:r?null:d[1],imported:r?d[1]:null,specifier:r,resolvedFile:f?.resolvedFile??null,kind:r?"named-reexport":"local-export",source:f?.span??M(n,o,l.index,l.index+l[0].length)})}}for(const l of t.matchAll(new RegExp(`\\bexport\\s+default\\s+(${E})\\s*;?`,"g")))l[1]!=="function"&&s.push({file:n,name:"default",local:l[1],imported:null,resolvedFile:null,kind:"local-export",source:M(n,o,l.index,l.index+l[0].length)});return{imports:c,exports:s}}function _(a,n){const o=new Map;for(const c of a)o.set(n(c),[...o.get(n(c))??[],c]);return o}function V(a=[]){const n=[...a].sort((e,p)=>e.file.localeCompare(p.file)),o=new Map(n.map(e=>[e.file,e.source??""])),c=new Map(n.map(e=>[e.file,Z(e.source??"")])),s=n.flatMap(Q),t=n.map(e=>({unit:e,...X(e)})),l=t.flatMap(e=>e.imports),r=t.flatMap(e=>e.exports);for(const e of s)e.exported&&r.push({file:e.file,name:e.default?"default":e.name,local:e.name,imported:null,resolvedFile:null,kind:"local-export",source:e.span});const f=_(r,e=>`${e.file}#${e.name}`),i=_(s,e=>`${e.file}#${e.name}`),d=_(l,e=>`${e.file}#${e.local}`),m=(e,p,x=new Set)=>{const g=`${e}#${p}`;if(x.has(g))return{reason:"ambiguous-alias"};const R=f.get(g)??[];if(R.length!==1)return{reason:n.find($=>$.file===e)?.moduleRefs?.some($=>$.kind==="export-star")?"export-star":"unsupported-syntax"};const b=R[0];if(b.local){const k=i.get(`${e}#${b.local}`)??[];return k.length===1?{key:k[0].key}:{reason:"ambiguous-alias"}}return b.resolvedFile?m(b.resolvedFile,b.imported,new Set([...x,g])):j(b.specifier)?{reason:"unresolved-module"}:{external:!0}};for(const e of l){if(e.kind==="namespace")continue;if(!e.resolvedFile){e.resolution=j(e.specifier)?"unresolved":"external",e.reason=e.resolution==="unresolved"?"unresolved-module":null;continue}const p=m(e.resolvedFile,e.imported);e.target=p.key??null,e.resolution=p.key?"resolved":p.external?"external":"unresolved",e.reason=p.reason??null}const w=[],O=[],y=(e,p,x,g)=>O.push({from:e,to:"unknown-export",symbol:g,resolution:"unresolved",reason:p,source:x,provenance:{adapter:"structural-js",method:"symbol-use"}});for(const e of s){const x=(o.get(e.file)??"").slice(e.start,e.end),g=/\blazy\s*\(\s*\(\s*\)\s*=>\s*import\s*\(\s*['"]([^'"]+)['"]\s*\)\s*\)/.exec(x);if(!g)continue;const R=n.find(k=>k.file===e.file)?.moduleRefs?.find(k=>k.kind==="dynamic-import"&&k.specifier===g[1]&&k.resolvedFile);if(!R)continue;const b=m(R.resolvedFile,"default");b.key?w.push({from:e.key,to:b.key,symbol:e.name,resolution:"resolved",reason:null,source:R.span,provenance:{adapter:"structural-js",method:"lazy-import"}}):b.external||y(e.key,b.reason,R.span,e.name)}const F=(e,p,x,g,R=null)=>{const b=d.get(`${e.file}#${p}`)??[];if(b.length&&H(e,p,c.get(e.file)??"",x.start)){y(e.key,"ambiguous-alias",x,g);return}const k=(i.get(`${e.file}#${p}`)??[]).filter(v=>!v.scope||v.scope.start<=x.start&&x.start<v.scope.end),$=v=>v.scope?v.scope.end-v.scope.start:1/0,S=Math.min(...k.map($)),h=k.filter(v=>$(v)===S);if(h.length===1&&h[0].key!==e.key){w.push({from:e.key,to:h[0].key,symbol:g,resolution:"resolved",reason:null,source:x,provenance:{adapter:"structural-js",method:"direct-call"}});return}if(b.length!==1){(b.length>1||h.length>1)&&y(e.key,"ambiguous-alias",x,g);return}const u=b[0];if(["useQuery","useMutation","useQueryClient"].includes(u.local)&&!u.resolvedFile)return;if(!u.resolvedFile)return u.resolution==="external"?void 0:y(e.key,"unresolved-module",x,g);const A=R==null&&u.kind!=="namespace"?{key:u.target,reason:u.reason}:m(u.resolvedFile,R??u.imported);if(!A.key)return A.external?void 0:y(e.key,A.reason,x,g);w.push({from:e.key,to:A.key,symbol:g,resolution:"resolved",reason:null,source:x,provenance:{adapter:"structural-js",method:u.kind==="namespace"?"namespace-member":"import-binding"}})};for(const e of s){const p=o.get(e.file)??"";!e.supported&&e.exported&&e.presentation&&y(e.key,"unsupported-syntax",e.span,e.name);const x=(c.get(e.file)??"").slice(e.bodyStart,e.end),g=e.bodyStart,R=[],b=s.filter($=>$.file===e.file&&$.key!==e.key&&e.bodyStart<=$.start&&$.end<=e.end);for(const $ of l.filter(S=>S.file===e.file&&S.kind==="namespace")){const S=$.local.replace(/[$]/g,"\\$&");for(const h of x.matchAll(new RegExp(`\\b${S}\\s*\\.\\s*(${E})`,"g"))){const u=g+h.index,A=u+h[0].length;R.push([u,A]),F(e,$.local,M(e.file,p,u,A),p.slice(u,A),h[1])}for(const h of x.matchAll(new RegExp(`\\b${S}\\s*\\[`,"g"))){const u=g+h.index;y(e.key,"computed-member",M(e.file,p,u,u+h[0].length),p.slice(u,u+h[0].length))}for(const h of x.matchAll(new RegExp(`\\.\\.\\.\\s*${S}\\b`,"g"))){const u=g+h.index;y(e.key,"namespace-spread",M(e.file,p,u,u+h[0].length),p.slice(u,u+h[0].length))}for(const h of x.matchAll(new RegExp(`\\b(?:const|let|var)\\s*\\{[^}]+\\}\\s*=\\s*${S}\\b`,"g"))){const u=g+h.index;y(e.key,"unsupported-syntax",M(e.file,p,u,u+h[0].length),p.slice(u,u+h[0].length))}}const k=[new RegExp(`\\b(${E})\\s*(?:<[^;{}()]*>)?\\s*\\(`,"g"),new RegExp(`<(${E})\\b`,"g")];for(const $ of k)for(const S of x.matchAll($)){const h=S.index+S[0].indexOf(S[1]),u=g+h,A=u+S[1].length;R.some(([v,q])=>u>=v&&A<=q)||b.some(v=>v.start<=u&&u<v.end)||F(e,S[1],M(e.file,p,u,A),p.slice(u,A))}}for(const e of n)for(const p of e.moduleRefs??[]){if(p.kind==="dynamic-import"){const x=Y({declarations:s},e.file,p.span.start)?.key??`${e.file}#<module>`;y(x,"dynamic-import",p.span,e.source.slice(p.span.start,p.span.end))}p.kind==="export-star"&&y(`${e.file}#<module>`,"export-star",p.span,e.source.slice(p.span.start,p.span.end))}const L=new Set(r.filter(e=>e.local).map(e=>`${e.file}#${e.local}`)),N=new Set(r.filter(e=>e.name==="default"&&e.local).map(e=>`${e.file}#${e.local}`));for(const e of s)e.exported=L.has(e.key),e.default=e.default||N.has(e.key);return{declarations:I(s),exports:I(r),imports:I(l),uses:I(w),unknownEdges:I(O)}}function Y(a,n,o){return(a.declarations??[]).filter(c=>c.file===n&&c.bodyStart<=o&&o<c.end).sort((c,s)=>c.end-c.start-(s.end-s.start))[0]??null}function ee(a,n,{stopAtPresentation:o=!1}={}){const c=new Map((a.declarations??[]).map(r=>[r.key,r])),s=_((a.uses??[]).filter(r=>r.resolution==="resolved"),r=>r.from),t=new Set,l=[{key:n,depth:0}];for(;l.length;){const{key:r,depth:f}=l.shift();if(!(t.has(r)||f>J)){t.add(r);for(const i of(s.get(r)??[]).sort((d,m)=>d.to.localeCompare(m.to)))o&&i.to!==n&&c.get(i.to)?.presentation&&c.get(i.to)?.exported||t.has(i.to)||l.push({key:i.to,depth:f+1})}}return[...t]}export{V as buildSymbolIndex,Y as declarationForOffset,U as nestedShadowAt,K as scanModuleReferences,ee as traceSymbolUses};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{balancedSlice as b,maskNonCode as A,splitTopLevel as $,collectConstBindings as q,parseKeyExpression as O}from"./structural-js.mjs";import{declarationForOffset as w}from"./symbols.mjs";import{evaluateCacheKeyExpression as E,keyResolution as R}from"./cache-key.mjs";import{expectedCacheOperationEffects as S}from"./contracts.mjs";const M=(e,n)=>e.slice(0,n).split(`
|
|
2
|
+
`).length,D=(e,n,t,s)=>{const r=n.slice(0,t);return{file:e,start:t,end:t+s.length,line:r.split(`
|
|
3
|
+
`).length,column:t-r.lastIndexOf(`
|
|
4
|
+
`)}};function T(e){const n=new Map;for(const t of $(e,",")){const s=t.match(/^([A-Za-z_$][\w$]*)\s*:\s*([\s\S]*)$/);s&&!n.has(s[1])&&n.set(s[1],s[2].trim())}return n}const Z="invalidateQueries|refetchQueries|resetQueries|removeQueries|setQueryData|setQueriesData|clear",K="emit|publish|trigger|broadcast";function P(e,n){return O(e,n).segments[0]}function _(e,n,t,s){const r=e.split(".")[0],a=n.get(r)?.at(-1)?.expression??"",f=(s?.declarations??[]).filter(i=>i.file===t?.split("#")[0]&&i.name===r),h=f.length===1?f[0].key:null;let y="unknown";return/\b(?:useQueryCache|getQueryCache)\s*\(|\bnew\s+QueryCache\s*\(/.test(a)?y="query-cache":/\b(?:useQueryClient|getQueryClient)\s*\(|\bnew\s+QueryClient\s*\(/.test(a)&&(y="query-client"),{expression:e,ownerSymbol:t,targetSymbol:h,kind:y,resolution:y==="unknown"?"unresolved":"resolved",reason:y==="unknown"?"unsupported-client":null}}function N({operation:e,receiverExpression:n,argsText:t,sourceRef:s,owner:r,bindings:a,resolver:f,source:h}){const y={file:s.file,source:h,start:s.end-1-t.length,ownerSymbol:r,bindings:a,symbolIndex:f.symbolIndex,units:f.units,contracts:f.contracts},i=k=>({...y,start:y.start+Math.max(0,t.indexOf(k))}),o=_(n,a,r,f.symbolIndex),u=$(t,",");let l=null,c=new Map;e==="setQueryData"?l=u[0]??null:u[0]?.trim().startsWith("{")&&u[0].trim().endsWith("}")?(c=T(u[0].trim().slice(1,-1)),l=c.get("queryKey")??null):u[0]&&e!=="clear"&&(l=u[0]);const d=l==null?null:E(l,i(l)),m=d?.patterns.length===1?d.patterns[0]:l==null?null:O(l,i(l)),p=c.get("exact")?.trim(),x=e==="setQueryData"||p==="true"?!0:p==="false"||p==null?!1:null,g=c.get("predicate"),v=g==null?null:P(g,i(g)),Q={};for(const k of["fetchStatus","refetchType","stale","type"]){if(!c.has(k))continue;const I=P(c.get(k),i(c.get(k)));Q[k]=I.kind==="literal"?I.value:I}let C=m==null?"all":x===!0||e==="setQueryData"?"exact":x===null?"unknown":"prefix";return e==="clear"&&(C="all"),{sourceRef:s,receiver:o,operation:e,key:m,keyMatch:C,exact:m==null?!1:x,predicate:v,filters:Q,effects:S({operation:e,receiver:o,filters:Q}),resolution:o.resolution==="resolved"&&(m==null||R(m)==="resolved")&&x!==null?"resolved":"unresolved",reason:o.reason??(d?.reason||(x===null?"dynamic-key":null)),keyProvenance:d?.provenance??[],provenance:[{adapter:"tanstack",method:"direct-call",confidence:"exact",resolutionPath:[]}]}}function F({receiverExpression:e,sourceRef:n,owner:t,bindings:s,symbolIndex:r}){const a=_(e,s,t,r);return a.resolution==="resolved"?null:{sourceRef:n,receiver:a,operation:"invalidateQueries",key:null,keyMatch:"all",exact:!1,predicate:null,filters:{},effects:S({operation:"invalidateQueries",receiver:a,filters:{}}),resolution:"unresolved",reason:"unresolvable-side-channel",keyProvenance:[],provenance:[{adapter:"tanstack",method:"side-channel-call",confidence:"uncertain",resolutionPath:[]}]}}function z(e,n,t,s,r,a){const f=[],h=A(e),y=new RegExp(`\\b([A-Za-z_$][\\w$]*(?:\\.[A-Za-z_$][\\w$]*)*)\\s*\\.\\s*(${Z})\\s*\\(`,"g");for(const o of h.matchAll(y)){const u=o.index+o[0].length-1,l=b(e,u);if(!l)continue;const c=n+o.index,d=n+l.end,m=s??(a.symbolIndex?w(a.symbolIndex,t.file,c)?.key??null:null);f.push(N({operation:o[2],receiverExpression:o[1],argsText:l.text.slice(1,-1),sourceRef:{file:t.file,start:c,end:d},owner:m,bindings:r,resolver:a,source:t.source??""}))}const i=new RegExp(`\\b([A-Za-z_$][\\w$]*(?:\\.[A-Za-z_$][\\w$]*)*)\\s*\\.\\s*(?:${K})\\s*\\(`,"g");for(const o of h.matchAll(i)){const u=o.index+o[0].length-1,l=b(e,u);if(!l)continue;const c=n+o.index,d=n+l.end,m=s??(a.symbolIndex?w(a.symbolIndex,t.file,c)?.key??null:null),p=F({receiverExpression:o[1],sourceRef:{file:t.file,start:c,end:d},owner:m,bindings:r,symbolIndex:a.symbolIndex});p&&f.push(p)}return f}function H(e){const n=e.predicate&&!e.key||e.keyMatch==="unknown"?"predicate":e.keyMatch;return{pattern:e.key??{segments:[]},match:n,confidence:e.resolution==="resolved"?"exact":"unresolved",...e.operation==="setQueryData"?{direct:!0}:{}}}function j(e,n={}){const t=e.source??"",s=A(t),r=n.bindings??q(t),a=[],f=[],h=[],y=z(t,0,e,null,r,n);for(const i of s.matchAll(/\buseQuery\s*\(\s*\{/g)){const o=s.indexOf("{",i.index),u=b(t,o),l=M(t,i.index),c=D(e.file,t,i.index,"useQuery"),d=n.symbolIndex?w(n.symbolIndex,e.file,i.index)?.key??null:null;if(!u){h.push({file:e.file,line:l,span:c,owner:d,reason:"unresolved-query-shape"});continue}const p=T(u.text.slice(1,-1)).get("queryKey"),x=p?E(p,{file:e.file,source:t,start:o+1+u.text.slice(1,-1).indexOf(p),ownerSymbol:d,bindings:r,symbolIndex:n.symbolIndex,units:n.units,contracts:n.contracts}):null,g=x?.patterns.length===1?x.patterns[0]:p?O(p,{file:e.file,source:t,ownerSymbol:d,bindings:r}):{segments:[{kind:"unknown",expression:"",ownerSymbol:d,targetSymbol:null,origin:c,resolutionPath:[],resolution:"unresolved",reason:"unsupported-expression"}]},v=u.text.match(/\.(?:get|fetch)\s*\(\s*['"]([^'"]+)['"]/)?.[1]??null;a.push({file:e.file,line:l,span:c,owner:d,pattern:g,endpoint:v,keyProvenance:x?.provenance??[]})}for(const i of s.matchAll(/\buseMutation\s*\(\s*\{/g)){const o=s.indexOf("{",i.index),u=b(t,o),l=M(t,i.index),c=D(e.file,t,i.index,"useMutation"),d=n.symbolIndex?w(n.symbolIndex,e.file,i.index)?.key??null:null;if(!u){h.push({file:e.file,line:l,span:c,owner:d,reason:"unresolved-mutation-shape"});continue}const m=u.text.slice(1,-1),p=m.match(/\.(?:post|put|patch|delete)\s*\(\s*['"]([^'"]+)/)?.[1]??null,x=o+1,g=z(m,x,e,d,r,n);f.push({file:e.file,line:l,span:c,owner:d,endpoint:p,operations:g,invalidations:g.map(H)})}return{readCandidates:a,mutationCandidates:f,operationCandidates:y,unresolved:h}}export{j as extractTanstackUnit};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{operationReadPairs as I,reduceOperationCoverage as w}from"./analyze.mjs";import{SURFACE_KINDS as x}from"./contracts.mjs";const p=40,$=new Set(x.filter(e=>e!=="route"));function y(e,s,f){let i=!1,n=!1;for(const t of e){const r=f.filter(o=>(s.operationIds??[]).includes(o.operationId)&&o.readId===t).map(o=>o.effectCoverage),u=w(r);u!=="covered"&&(u==="unresolved"?n=!0:i=!0)}return i?!1:n?"unresolved":!0}function C(e){const s=new Map((e?.reads??[]).map(t=>[t.id,t])),f=new Map((e?.cacheKeys??[]).map(t=>[t.id,t])),i=I((e?.cacheOperations??[]).map(t=>({...t,material:{...t.material,key:f.get(t.material.keyId)?.material??null}})),e?.reads??[]),n=[];for(const t of e?.mutations??[]){if(!t.family)continue;const r=new Set((e.reads??[]).filter(o=>o.family===t.family).map(o=>o.id));if(!r.size)continue;const u=[];for(const o of e.surfaces??[]){const a=(o.readIds??[]).filter(l=>r.has(l));a.length&&u.push({surfaceId:o.id,route:o.route,component:o.component??null,covered:y(a,t,i)})}u.length&&(u.sort((o,a)=>o.surfaceId.localeCompare(a.surfaceId)),n.push({mutationId:t.id,label:v(t),file:t.file,line:t.line,family:t.family,invalidations:(t.operationIds??[]).length,surfaces:u}))}return n.sort((t,r)=>t.mutationId.localeCompare(r.mutationId)),n}function R(e){const s=new Map((e?.reads??[]).map(t=>[t.id,t])),f=new Map((e?.cacheKeys??[]).map(t=>[t.id,t])),i=I((e?.cacheOperations??[]).map(t=>({...t,material:{...t.material,key:f.get(t.material.keyId)?.material??null}})),e?.reads??[]),n=[];for(const t of e?.surfaces??[]){if(!$.has(t.kind))continue;const r=[...new Set((t.readIds??[]).map(a=>s.get(a)?.family).filter(Boolean))].sort();if(!r.length)continue;const u=new Set(r),o=[];for(const a of e.mutations??[]){if(!a.family||!u.has(a.family))continue;const l=(t.readIds??[]).filter(d=>s.get(d)?.family===a.family);o.push({mutationId:a.id,label:v(a),file:a.file,line:a.line,family:a.family,covered:y(l,a,i)})}o.length&&(o.sort((a,l)=>a.mutationId.localeCompare(l.mutationId)),n.push({surfaceId:t.id,route:t.route,component:t.component,families:r,writers:o}))}return n.sort((t,r)=>t.surfaceId.localeCompare(r.surfaceId)),n}function M(e,{principals:s=[],contexts:f=["warm-cache","fresh-context"]}={}){const i=new Map((e?.reads??[]).map(a=>[a.id,a])),n=new Set;for(const a of e?.mutations??[])a.family&&n.add(a.family);for(const a of e?.reads??[])a.family&&n.add(a.family);const t=Math.max(1,s.length),r=f.length;let u=0;const o=[];for(const a of[...n].sort()){const l=(e.mutations??[]).filter(c=>c.family===a),d=(e.surfaces??[]).filter(c=>(c.readIds??[]).some(m=>i.get(m)?.family===a));u+=l.length*d.length*t*r;for(const c of l)for(const m of d)o.push({mutationId:c.id,surfaceId:m.id})}return o.sort((a,l)=>a.mutationId===l.mutationId?a.surfaceId.localeCompare(l.surfaceId):a.mutationId.localeCompare(l.mutationId)),{count:u,principals:t,contexts:r,pairs:o}}function h(e){return e===!0?"":e==="unresolved"?" (unresolved)":" (uncovered)"}function g(e,s,f){const i=[e],n=s.slice(0,p);for(const t of n)i.push(f(t));return s.length>p&&i.push(` ... ${s.length-p} more`),i}function v(e){return(e.hook?e.hook+"()":e.file??"mutation")+(e.file?" ("+e.file+":"+e.line+")":"")}function O({fanOut:e=[],fanIn:s=[],obligations:f}={}){const i=[];return i.push(...g("fan-out (mutation -> family -> surfaces)",e,n=>` ${n.mutationId} [${n.family}] -> ${n.surfaces.map(t=>`${t.route}:${t.component??t.surfaceId}${h(t.covered)}`).join(", ")}`)),i.push(""),i.push(...g("fan-in (surface <- writers)",s,n=>` ${n.route}:${n.component} <- ${n.writers.map(t=>`${t.label??t.mutationId}${h(t.covered)}`).join(", ")}`)),f&&(i.push(""),i.push(`static Cartesian estimate: ${f.count} (mutation x surface x principal x context; not the kernel obligation universe)`)),i}export{R as fanIn,C as fanOut,v as mutationLabel,M as obligationUniverse,O as renderViews};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function g(r,o){return{discovered:r.length,resolved:r.length,unresolved:0,planned:o.size,reached:0,compared:0,agreed:0}}function p(r,o){return{selected:[],rejected:[],coverage:g(r,new Set),ok:!1,reason:o}}function b(r,o,l){if(!Number.isFinite(l)||l<0)return"budget must be a finite non-negative number";const s=new Set;for(const e of r){if(!e||typeof e.id!="string"||!e.id)return"obligation id is required";if(s.has(e.id))return`duplicate obligation id: ${e.id}`;if(s.add(e.id),!Number.isFinite(e.weight)||e.weight<0)return`obligation ${e.id} has an invalid weight`;if(typeof e.mandatory!="boolean")return`obligation ${e.id} must declare mandatory`}const c=new Set;for(const e of o){if(!e||typeof e.id!="string"||!e.id)return"candidate id is required";if(c.has(e.id))return`duplicate candidate id: ${e.id}`;if(c.add(e.id),!Number.isFinite(e.cost)||e.cost<=0)return`candidate ${e.id} has an invalid cost`;if(!Array.isArray(e.obligationIds))return`candidate ${e.id} must declare obligationIds`;if(new Set(e.obligationIds).size!==e.obligationIds.length)return`candidate ${e.id} has duplicate obligation ids`;for(const d of e.obligationIds)if(!s.has(d))return`candidate ${e.id} references unknown obligation ${d}`}return null}function m({obligations:r=[],candidates:o=[],budget:l}){if(!Array.isArray(r)||!Array.isArray(o))return p([],"obligations and candidates must be arrays");const s=b(r,o,l);if(s)return p(r,s);let c=l;const e=new Map(r.map(t=>[t.id,t])),d=new Set,f=[],a=[...o].sort((t,i)=>t.id.localeCompare(i.id)),h=t=>{f.push(t),c-=t.cost;for(const i of t.obligationIds)d.add(i);a.splice(a.indexOf(t),1)};for(const t of r.filter(i=>i.mandatory).sort((i,n)=>i.id.localeCompare(n.id))){if(d.has(t.id))continue;const i=a.filter(n=>n.cost<=c&&n.obligationIds.includes(t.id)).sort((n,u)=>n.cost-u.cost||n.id.localeCompare(u.id));if(!i.length)return{selected:f,rejected:a,coverage:g(r,d),ok:!1,reason:`mandatory obligation ${t.id} cannot fit budget`};h(i[0])}for(;a.length;){const t=a.filter(i=>i.cost<=c).map(i=>({candidate:i,gain:i.obligationIds.filter(n=>!d.has(n)).reduce((n,u)=>n+e.get(u).weight,0)})).filter(i=>i.gain>0).sort((i,n)=>n.gain/i.candidate.cost-i.gain/n.candidate.cost||i.candidate.id.localeCompare(n.candidate.id));if(!t.length)break;h(t[0].candidate)}return{selected:f,rejected:a,coverage:g(r,d),ok:!0,reason:null}}export{m as selectCoherenceJourneys};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import l from"node:fs";import f from"node:path";const g=Object.freeze({doctor:"verify --preflight",research:"init --study",stability:"verify --runs N",coherence:"measure coherence",crud:"measure crud",experiments:"measure experiments",shadow:"measure shadow",invariants:"measure invariants",triage:"show",next:"show next",ledger:"show ledger",graph:"show graph",report:"show report",ci:"show ci",diff:"show diff",runs:"show runs",marathon:"run",loop:"run loop",watch:"run watch",serve:"run serve",lanes:"fix <plan|gate|close|rebase|board>",fp:"fix fp",atlas:"dev atlas",selftest:"dev selftest",validate:"dev validate",version:"dev version"}),i=[["Prepare a run",new Set(["init","verify"])],["Measure the app",new Set(["measure"])],["Read results",new Set(["show"])],["Fix and automate",new Set(["run","fix"])],["Maintain the harness",new Set(["dev"])]];function c(s,e){const o=e[s];return o?o.split(`
|
|
2
|
+
`,1)[0].trim():`qa ${s}`}function u(s){return i.find(([,e])=>e.has(s))?.[0]??"Other commands"}function w({commandsDir:s,help:e}){return l.readdirSync(s).filter(t=>/^[a-z][a-z0-9-]*\.mjs$/.test(t)).map(t=>f.basename(t,".mjs")).sort().map(t=>Object.freeze({name:t,title:c(t,e),group:u(t)}))}function v(s){const e=new Map;for(const r of s){const n=e.get(r.group)??[];n.push(r.name),e.set(r.group,n)}const o=i.map(([r])=>r).filter(r=>e.has(r)),t=[...e.keys()].filter(r=>!o.includes(r)).sort();return[...o,...t].map(r=>({group:r,commands:e.get(r)}))}function x(s,e,o){const t=String(o??"").trim().toLowerCase();if(!t)return[];const r=Object.keys(e).filter(n=>n.includes(" ")).map(n=>({name:n,title:c(n,e),group:u(n.split(" ")[0])}));return[...s,...r].filter(({name:n,title:a})=>n.toLowerCase().includes(t)||a.toLowerCase().includes(t)||(e[n]??"").toLowerCase().includes(t))}function y(s,e){return d(s,e.map(({name:o})=>o))}function d(s,e){const o=String(s??"").toLowerCase();let t=null,r=1/0;for(const n of e){const a=m(o,n);a<r&&(t=n,r=a)}return r<=Math.max(2,Math.floor(o.length/3))?t:null}function m(s,e){const o=Array.from({length:e.length+1},(t,r)=>r);for(let t=1;t<=s.length;t++){let r=o[0];o[0]=t;for(let n=1;n<=e.length;n++){const a=o[n];o[n]=Math.min(o[n]+1,o[n-1]+1,r+(s[t-1]===e[n-1]?0:1)),r=a}}return o[e.length]}export{g as RETIRED_COMMANDS,w as commandCatalog,v as groupedCatalog,d as nearest,y as nearestCommand,x as searchCatalog};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{UsageError as m}from"../cli.mjs";import*as d from"./impl/atlas.mjs";import*as l from"./impl/selftest.mjs";import*as f from"./impl/validate.mjs";import*as p from"./impl/version.mjs";const i={atlas:d,selftest:l,validate:f,version:p},n=new Set(Object.keys(i));async function u(a){const{parsed:t,name:r}=a;let o=null,s=t.positional;if(!t.command&&n.has(r))o=r;else{const e=s[0];if(!n.has(e))throw new m(`qa dev needs a kind: one of ${[...n].join(", ")} (got ${e?`"${e}"`:"none"})`);o=e,s=s.slice(1)}return i[o].run({...a,parsed:{...t,command:o,positional:s}})}export{u as run};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{UsageError as a}from"../cli.mjs";import*as e from"./impl/lanes.mjs";import*as i from"./impl/fp.mjs";const s=new Set(["plan","gate","close","rebase","board"]);async function t(r){const{parsed:n}=r,o=n.positional[0];if(s.has(o))return e.run(r);if(o==="fp")return i.run({...r,parsed:{...n,command:"fp",positional:n.positional.slice(1)}});throw new a(`qa fix needs a sub: one of ${[...s,"fp"].join(", ")} (got ${o?`"${o}"`:"none"})`)}export{t as run};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import a from"node:path";import{resolveRepo as e,InvalidError as f}from"../../cli.mjs";import{exists as m,readJson as l,readText as y}from"../../fs.mjs";async function d({parsed:i,out:n}){const r=e(i),s=a.join(r,".verify","analysis.json");if(!m(s))throw new f(`analysis missing: ${s}; run qa init --analysis ${r} first`);const o=l(s,{required:!0,what:"analysis.json"});if(i.flags.format==="json")return n.emit(o),0;const t=a.join(r,".verify","analysis.md");return n.say(y(t)),n.emit({ok:!0,repo:r,analysis:o}),0}export{d as run};
|