From a363e4cc22bcd1998b2a56db845bea8d2ab81a30 Mon Sep 17 00:00:00 2001 From: Byron Wall Date: Sat, 21 Nov 2026 09:35:58 -0500 Subject: [PATCH] feat(engine): fileSignals op for data-flow metrics, findings and work packets One tier-2 op builds the legacy report once and returns per-file metrics, impossible-defense and repeated-fork findings, and dataflow.md (the old CLI's work-packets, defensive-ledger, repeated-forks, prop-relay, context-relay and fan-out views). Co-Authored-By: Claude Opus 5.5 --- client/src/dataflow/contract.generated.ts | 31 ++++ engine/bin/srcly-engine.ts | 1 + engine/src/service/analysis-service.ts | 4 +- engine/src/service/analysis-worker.ts | 2 + engine/src/srcly/contracts/file-signals.ts | 52 ++++++ engine/src/srcly/contracts/registry.ts | 2 + engine/src/srcly/ops/file-signals.ts | 173 ++++++++++++++++++ engine/test/srcly/file-signals.test.ts | 62 +++++++ .../contracts/fileSignals.schema.json | 164 +++++++++++++++++ server/app/services/dataflow/models.py | 39 ++++ server/tests/test_dataflow_models.py | 7 + 11 files changed, 536 insertions(+), 1 deletion(-) create mode 100644 engine/src/srcly/contracts/file-signals.ts create mode 100644 engine/src/srcly/ops/file-signals.ts create mode 100644 engine/test/srcly/file-signals.test.ts create mode 100644 server/app/services/dataflow/contracts/fileSignals.schema.json diff --git a/client/src/dataflow/contract.generated.ts b/client/src/dataflow/contract.generated.ts index 26521328..050195ec 100644 --- a/client/src/dataflow/contract.generated.ts +++ b/client/src/dataflow/contract.generated.ts @@ -592,3 +592,34 @@ export type RoutePathResult = { label: string; } | null; }; + +/** Result of the `fileSignals` op. */ +export type FileSignalsResult = { + outcome: "ok" | "assumed" | "partial" | "not-analyzed" | "unsupported" | "stale" | "cancelled" | "budget"; + generation: number; + programHash: string; + tsconfig: string; + typescript: string; + nullProof: boolean; + reason: string | null; + files: { + file: string; + metrics: { + impossibleDefenses: number; + relayHops: number; + fanOut: number; + representationChanges: number; + pathDepth: number; + }; + }[]; + findings: { + rule: "impossible-defense" | "repeated-fork"; + file: string; + line: number; + column: number; + endLine: number; + message: string; + }[]; + unplacedDefenses: number; + markdown: string; +}; diff --git a/engine/bin/srcly-engine.ts b/engine/bin/srcly-engine.ts index 5188db8b..2ba36158 100644 --- a/engine/bin/srcly-engine.ts +++ b/engine/bin/srcly-engine.ts @@ -107,6 +107,7 @@ function workerOperation(frame: RequestFrame): AnalysisOperation | null { if (frame.op === "functionEffects") return { kind: "function-effects", params }; if (frame.op === "fileExports") return { kind: "file-exports", params }; if (frame.op === "routePath") return { kind: "route-path", params }; + if (frame.op === "fileSignals") return { kind: "file-signals", params }; if (frame.op === "routeSurface") { if (typeof params.route !== "string") throw new EngineError("invalid-request", "routeSurface needs params.route"); return { kind: "route-surface", route: params.route, expectedGeneration }; diff --git a/engine/src/service/analysis-service.ts b/engine/src/service/analysis-service.ts index 0288a6d2..c25f4418 100644 --- a/engine/src/service/analysis-service.ts +++ b/engine/src/service/analysis-service.ts @@ -78,7 +78,9 @@ export type AnalysisOperation = | { kind: "anchor-graph"; params: Record } | { kind: "function-effects"; params: Record } | { kind: "route-path"; params: Record } - | { kind: "file-exports"; params: Record }; + | { kind: "file-exports"; params: Record } + /** Tier 2: the legacy report as per-file metrics, findings and `dataflow.md`. */ + | { kind: "file-signals"; params: Record }; export function createAnalysisService(args: AnalyzerArgs, engine: EngineConfig | null = null) { let workerUrl = import.meta.url.endsWith(".ts") diff --git a/engine/src/service/analysis-worker.ts b/engine/src/service/analysis-worker.ts index c70db39d..88bef5e2 100644 --- a/engine/src/service/analysis-worker.ts +++ b/engine/src/service/analysis-worker.ts @@ -13,6 +13,7 @@ import type { AnalysisOperation, AnalysisProgress, AnalysisWorkerData, AnalysisW import { errorPayload } from "../srcly/protocol"; import { anchorGraphOp } from "../srcly/ops/anchor-graph"; import { fileExportsOp } from "../srcly/ops/file-exports"; +import { fileSignalsOp } from "../srcly/ops/file-signals"; import { functionEffectsOp } from "../srcly/ops/function-effects"; import { routeGraphOp, routeSurfaceOp } from "../srcly/ops/route-graph"; import { routePathOp } from "../srcly/ops/route-path"; @@ -90,6 +91,7 @@ function perform(operation: AnalysisOperation, requestId: number, cancellation: if (operation.kind === "anchor-graph") return announce(anchorGraphOp(requireSession(), operation.params, cancellation)); if (operation.kind === "function-effects") return announce(functionEffectsOp(requireSession(), operation.params, cancellation)); if (operation.kind === "file-exports") return announce(fileExportsOp(requireSession(), operation.params, cancellation)); + if (operation.kind === "file-signals") return announce(fileSignalsOp(requireSession(), operation.params)); if (operation.kind === "route-path") return announce(routePathOp(requireSession(), operation.params, cancellation)); if (operation.kind === "refresh") { const report = cache.refresh(); diff --git a/engine/src/srcly/contracts/file-signals.ts b/engine/src/srcly/contracts/file-signals.ts new file mode 100644 index 00000000..fa931aa0 --- /dev/null +++ b/engine/src/srcly/contracts/file-signals.ts @@ -0,0 +1,52 @@ +import { z } from "zod"; +import { generationFields, outcomeSchema } from "./primitives"; + +/** + * Tier-2 evidence for srcly's pipelines (M7): per-file data-flow metrics, + * finding spans for the code viewer and `srcly report`, and the work-packet + * Markdown that `srcly report --dataflow` writes as `dataflow.md`. All of it + * comes from one legacy report (`fullReport()`), so it is slow: minutes on a + * big app. Only a batch caller asks for it. + */ +export const dataflowRuleSchema = z.enum(["impossible-defense", "repeated-fork"]); + +export const dataflowFindingSchema = z.strictObject({ + rule: dataflowRuleSchema, + /** Relative to the engine root. */ + file: z.string(), + line: z.number().int().positive(), + column: z.number().int().positive(), + endLine: z.number().int().positive(), + message: z.string(), +}); + +/** The worst render path in a file, or the dead guards in it. Each is a count, never a score. */ +export const fileMetricsSchema = z.strictObject({ + /** `??` and `?.` in the file whose guarded value the types say is never null or undefined. */ + impossibleDefenses: z.number().int().nonnegative(), + /** The most component boundaries one of the file's render sinks crosses (prop relay). */ + relayHops: z.number().int().nonnegative(), + /** The most render sinks one of the file's sinks' sources also feeds. */ + fanOut: z.number().int().nonnegative(), + /** The most representation-only steps (alias, pack, spread) on one of the file's render paths. */ + representationChanges: z.number().int().nonnegative(), + /** The most steps from a source to one of the file's JSX sinks. */ + pathDepth: z.number().int().nonnegative(), +}); + +export const fileSignalsResultSchema = z.strictObject({ + outcome: outcomeSchema, + ...generationFields, + reason: z.string().nullable(), + /** Every first-party program file, sinks or not: a file listed here was analyzed. */ + files: z.array(z.strictObject({ file: z.string(), metrics: fileMetricsSchema })), + findings: z.array(dataflowFindingSchema), + /** Impossible defenses whose file the report did not name and srcly could not place: counted here, never guessed. */ + unplacedDefenses: z.number().int().nonnegative(), + /** `dataflow.md`: work packets, defensive ledger, repeated forks, prop and context relay, fan-out. */ + markdown: z.string(), +}); + +export type DataflowFinding = z.infer; +export type FileMetrics = z.infer; +export type FileSignalsResult = z.infer; diff --git a/engine/src/srcly/contracts/registry.ts b/engine/src/srcly/contracts/registry.ts index 6af5bcf1..e4a4b751 100644 --- a/engine/src/srcly/contracts/registry.ts +++ b/engine/src/srcly/contracts/registry.ts @@ -1,6 +1,7 @@ import type { z } from "zod"; import { anchorGraphResultSchema } from "./anchor-graph"; import { fileExportsResultSchema } from "./file-exports"; +import { fileSignalsResultSchema } from "./file-signals"; import { functionEffectsResultSchema } from "./function-effects"; import { helloResultSchema } from "./hello"; import { routeGraphResultSchema } from "./route-graph"; @@ -25,4 +26,5 @@ export const CONTRACTS: { op: string; typeName: string; schema: z.ZodType }[] = { op: "functionEffects", typeName: "FunctionEffectsResult", schema: functionEffectsResultSchema }, { op: "fileExports", typeName: "FileExportsResult", schema: fileExportsResultSchema }, { op: "routePath", typeName: "RoutePathResult", schema: routePathResultSchema }, + { op: "fileSignals", typeName: "FileSignalsResult", schema: fileSignalsResultSchema }, ]; diff --git a/engine/src/srcly/ops/file-signals.ts b/engine/src/srcly/ops/file-signals.ts new file mode 100644 index 00000000..37c6a631 --- /dev/null +++ b/engine/src/srcly/ops/file-signals.ts @@ -0,0 +1,173 @@ +import path from "node:path"; +import type * as TypeScript from "typescript"; +import { renderMarkdownView } from "../../reports/markdown-views"; +import type { AnalysisReport, DefenseRecord, Sink } from "../../types"; +import { fileSignalsResultSchema, type DataflowFinding, type FileMetrics, type FileSignalsResult } from "../contracts/file-signals"; +import { checkGeneration, requireTypescript, type EngineSession, type TsTier1 } from "../session"; + +/** Items per view: what the checked-in example reports use, so the two stay comparable. */ +export const DATAFLOW_MAX_ITEMS = 8; + +/** The views `dataflow.md` holds, in reading order. */ +export const DATAFLOW_VIEWS = ["work-packets", "defensive-ledger", "repeated-forks", "prop-relay", "context-relay", "fan-out"] as const; + +/** + * Tier 2 (M7): build the legacy report once and project it for srcly's + * pipelines. Metrics and findings are per file; the Markdown is the old + * CLI's views, unchanged except for who made them and how to rerun them. + */ +export function fileSignalsOp(session: EngineSession, params: { expectedGeneration?: unknown }): FileSignalsResult { + const tier1 = requireTypescript(session.tier1(), "Data-flow signals"); + checkGeneration(tier1, params.expectedGeneration); + const report = tier1.fullReport(); + const rel = (file: string) => path.relative(tier1.root, file).split(path.sep).join("/"); + const files = new Map( + tier1.inputs.files.map((file) => [rel(file), { impossibleDefenses: 0, relayHops: 0, fanOut: 0, representationChanges: 0, pathDepth: 0 }]), + ); + const { findings: defenses, unplaced } = impossibleDefenses(tier1, report); + const findings: DataflowFinding[] = [...defenses, ...repeatedForks(report)]; + for (const finding of defenses) { + const metrics = files.get(finding.file); + if (metrics) metrics.impossibleDefenses += 1; + } + for (const sink of report.rankings.all as Sink[]) { + const metrics = files.get(sink.file); + if (!metrics) continue; + metrics.relayHops = Math.max(metrics.relayHops, sink.metrics.mergeWidth - 1); + metrics.fanOut = Math.max(metrics.fanOut, sink.metrics.reachableSinks); + metrics.representationChanges = Math.max(metrics.representationChanges, sink.metrics.representationChurn); + metrics.pathDepth = Math.max(metrics.pathDepth, sink.metrics.maximumPathDepth); + } + findings.sort((a, b) => (a.file < b.file ? -1 : a.file > b.file ? 1 : a.line - b.line || a.column - b.column)); + return fileSignalsResultSchema.parse({ + outcome: "ok", + generation: tier1.generation.id, + programHash: tier1.generation.programHash, + tsconfig: tier1.generation.tsconfig, + typescript: tier1.generation.typescript, + nullProof: tier1.generation.nullProof, + reason: null, + files: [...files].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([file, metrics]) => ({ file, metrics })), + findings, + unplacedDefenses: unplaced, + markdown: dataflowMarkdown(tier1, report), + }); +} + +/** + * One finding per type-impossible `??` or `?.`, however many sinks it feeds. + * The legacy report records a defense's line and column but not its file, so + * it is placed in the first file on the sink's path whose text at that spot is + * the defense (a helper's guard lives in the helper's file, not the sink's). + */ +function impossibleDefenses(tier1: TsTier1, report: AnalysisReport) { + const seen = new Set(); + const findings: DataflowFinding[] = []; + let unplaced = 0; + for (const sink of report.sinks as Sink[]) { + for (const defense of sink.defenses) { + if (defense.verdict !== "impossible") continue; + const candidates = [sink.file, ...sink.representativeSteps.map((step) => step.file).filter((file): file is string => Boolean(file))]; + const placed = candidates.map((file) => placeDefense(tier1, file, defense)).find((span) => span !== null) ?? null; + const key = placed ? `${placed.file}:${placed.line}:${placed.column}` : `?${sink.file}:${defense.location.line}:${defense.location.column}|${defense.expression}`; + if (seen.has(key)) continue; + seen.add(key); + if (!placed) { + unplaced += 1; + continue; + } + const type = defense.type ? ` \`${defense.type}\`` : ""; + findings.push({ + rule: "impossible-defense", + ...placed, + message: `\`${oneLine(defense.expression)}\` guards a value whose type${type} is never null or undefined, so the fallback never runs. Remove it after checking the contract.`, + }); + } + } + return { findings, unplaced }; +} + +/** The defense's span in `file` when the source there reads as its expression (whitespace aside). */ +function placeDefense(tier1: TsTier1, file: string, defense: DefenseRecord) { + const source = tier1.program.getSourceFile(path.resolve(tier1.root, file)); + if (!source) return null; + const { line, column } = defense.location; + const starts = source.getLineStarts(); + if (line < 1 || line > starts.length || column < 1) return null; + const start = starts[line - 1] + column - 1; + if (start >= (starts[line] ?? source.text.length + 1)) return null; + const wanted = defense.expression.replace(/\s+/g, ""); + let end = start; + let matched = 0; + const text = source.text; + while (end < text.length && matched < wanted.length) { + const char = text[end]; + end += 1; + if (/\s/.test(char)) continue; + if (char !== wanted[matched]) return null; + matched += 1; + } + if (matched < wanted.length) return null; + return { file, line, column, endLine: lineOf(tier1.ts, source, end) }; +} + +function lineOf(ts: typeof TypeScript, source: TypeScript.SourceFile, position: number) { + return ts.getLineAndCharacterOfPosition(source, position).line + 1; +} + +/** One finding per component that tests the same discriminant at several sibling branch sites. */ +function repeatedForks(report: AnalysisReport): DataflowFinding[] { + return (report.repeatedForks ?? []).map((fork) => { + const lines = fork.sites.map((site) => site.line); + const component = fork.component ? `\`${fork.component}\`` : "This render scope"; + const branches = fork.branchValues.length ? ` (${fork.branchValues.map((value) => `\`${value}\``).join(", ")})` : ""; + return { + rule: "repeated-fork", + file: fork.file, + line: fork.line, + column: fork.column, + endLine: Math.max(fork.line, ...lines), + message: `${component} tests \`${oneLine(fork.discriminant)}\` at ${fork.siteCount} sibling branch sites (lines ${lines.join(", ")}). Split it into one sub-component per branch${branches}.`, + }; + }); +} + +function oneLine(text: string) { + const flat = text.replace(/\s+/g, " ").trim(); + return flat.length > 120 ? `${flat.slice(0, 117)}…` : flat; +} + +/** + * The old CLI's views, one after another under one title. Each view keeps its + * text; its headings drop one level, its provenance names srcly, and the + * `tsx-dataflow` rerun footer goes (srcly's footer says how to rerun). + */ +export function dataflowMarkdown(tier1: TsTier1, report: AnalysisReport) { + const sections = DATAFLOW_VIEWS.map((view) => + srclyView(renderMarkdownView(report, { ...tier1.args, view, format: "markdown", maxItems: DATAFLOW_MAX_ITEMS, maxItemsExplicit: true, out: null })), + ); + return [ + "# Data flow", + "", + "Render-path evidence from srcly's data-flow engine (the TypeScript checker), for agents and reviewers. Read the work packets first, then the ledgers below them.", + "", + ...sections, + "---", + "", + "_Regenerate:_ `srcly report --dataflow`", + "", + ].join("\n"); +} + +/** One view as a section of `dataflow.md`. Exported for the test that compares it with the old CLI's output. */ +export function srclyView(markdown: string) { + const footer = markdown.indexOf("\n---\n\n_Regenerate this report:_"); + const body = (footer >= 0 ? markdown.slice(0, footer) : markdown).trimEnd(); + let fenced = false; + const lines = body.split("\n").map((line) => { + if (line.startsWith("```")) fenced = !fenced; + if (fenced || !line.startsWith("#")) return line; + return `#${line}`; + }); + return `${lines.join("\n").replace("Generated by **tsx-dataflow**,", "Generated by **srcly**'s data-flow engine,")}\n`; +} diff --git a/engine/test/srcly/file-signals.test.ts b/engine/test/srcly/file-signals.test.ts new file mode 100644 index 00000000..dff5bbed --- /dev/null +++ b/engine/test/srcly/file-signals.test.ts @@ -0,0 +1,62 @@ +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { describe, expect, it } from "vitest"; +import { fileSignalsOp, srclyView } from "../../src/srcly/ops/file-signals"; +import { createEngineSession } from "../../src/srcly/session"; +import { chooseTypescript } from "../../src/srcly/typescript-choice"; + +const root = fileURLToPath(new URL("../../examples/bad-ish-solid", import.meta.url)); +const source = path.join(root, "src"); +const session = createEngineSession({ root, source, tsconfig: null, typescriptFrom: chooseTypescript(root, source).from }); +const result = fileSignalsOp(session, {}); + +describe("fileSignals carries tsx-data-flow's reporting into srcly (M7)", () => { + it("finds each type-impossible guard once, in the file that holds it", () => { + const defenses = result.findings.filter((f) => f.rule === "impossible-defense"); + expect(defenses.map((f) => `${f.file}:${f.line}`)).toEqual([ + "src/DashboardShell.tsx:12", + "src/DashboardShell.tsx:13", + "src/DashboardShell.tsx:51", + "src/DashboardShell.tsx:52", + "src/DashboardShell.tsx:53", + "src/DashboardShell.tsx:68", + "src/DashboardShell.tsx:68", + "src/DashboardShell.tsx:110", + "src/DashboardShell.tsx:111", + "src/DashboardShell.tsx:133", + "src/DashboardShell.tsx:134", + "src/DashboardShell.tsx:135", + ]); + expect(defenses[0].message).toContain('`route.toolbar.theme ?? "light"`'); + expect(result.unplacedDefenses).toBe(0); + const metrics = Object.fromEntries(result.files.map((f) => [f.file, f.metrics])); + expect(metrics["src/DashboardShell.tsx"].impossibleDefenses).toBe(12); + expect(metrics["src/view-models.ts"].impossibleDefenses).toBe(0); + }); + + it("finds Chart's repeated fork on props.type, Solid sites included", () => { + const forks = result.findings.filter((f) => f.rule === "repeated-fork"); + expect(forks).toEqual([ + expect.objectContaining({ file: "src/Chart.tsx", line: 37, endLine: 48 }), + ]); + expect(forks[0].message).toContain("`props.type` at 4 sibling branch sites (lines 37, 38, 45, 48)"); + }); + + it("measures every program file, the worst render path per file", () => { + expect(result.files.map((f) => f.file)).toEqual(["src/Chart.tsx", "src/DashboardShell.tsx", "src/types.ts", "src/view-models.ts"]); + const shell = result.files.find((f) => f.file === "src/DashboardShell.tsx")!.metrics; + expect(shell).toMatchObject({ pathDepth: 15, relayHops: 6, representationChanges: 8 }); + expect(shell.fanOut).toBeGreaterThan(1); + }); + + it("writes dataflow.md from the old CLI's views, with srcly's provenance and footer", () => { + // Each view's text is the old CLI's, byte for byte (checked against the archived + // tsx-data-flow on this example at --max-items 8); here only srcly's changes. + expect(srclyView("# Title\n\n> Generated by **tsx-dataflow**, x\n\n```\n# kept\n```\n\n---\n\n_Regenerate this report:_\n")).toBe( + "## Title\n\n> Generated by **srcly**'s data-flow engine, x\n\n```\n# kept\n```\n", + ); + expect(result.markdown).not.toContain("tsx-dataflow"); + expect(result.markdown).toContain("### WORK ITEM DF-001"); + expect(result.markdown).toContain("### Stop Recommendation"); + }); +}); diff --git a/server/app/services/dataflow/contracts/fileSignals.schema.json b/server/app/services/dataflow/contracts/fileSignals.schema.json new file mode 100644 index 00000000..9864b8a1 --- /dev/null +++ b/server/app/services/dataflow/contracts/fileSignals.schema.json @@ -0,0 +1,164 @@ +{ + "title": "FileSignalsResult", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "outcome": { + "type": "string", + "enum": [ + "ok", + "assumed", + "partial", + "not-analyzed", + "unsupported", + "stale", + "cancelled", + "budget" + ] + }, + "generation": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "programHash": { + "type": "string" + }, + "tsconfig": { + "type": "string" + }, + "typescript": { + "type": "string" + }, + "nullProof": { + "type": "boolean" + }, + "reason": { + "type": [ + "string", + "null" + ] + }, + "files": { + "type": "array", + "items": { + "type": "object", + "properties": { + "file": { + "type": "string" + }, + "metrics": { + "type": "object", + "properties": { + "impossibleDefenses": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "relayHops": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "fanOut": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "representationChanges": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "pathDepth": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "impossibleDefenses", + "relayHops", + "fanOut", + "representationChanges", + "pathDepth" + ], + "additionalProperties": false + } + }, + "required": [ + "file", + "metrics" + ], + "additionalProperties": false + } + }, + "findings": { + "type": "array", + "items": { + "type": "object", + "properties": { + "rule": { + "type": "string", + "enum": [ + "impossible-defense", + "repeated-fork" + ] + }, + "file": { + "type": "string" + }, + "line": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "column": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "endLine": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "message": { + "type": "string" + } + }, + "required": [ + "rule", + "file", + "line", + "column", + "endLine", + "message" + ], + "additionalProperties": false + } + }, + "unplacedDefenses": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "markdown": { + "type": "string" + } + }, + "required": [ + "outcome", + "generation", + "programHash", + "tsconfig", + "typescript", + "nullProof", + "reason", + "files", + "findings", + "unplacedDefenses", + "markdown" + ], + "additionalProperties": false +} diff --git a/server/app/services/dataflow/models.py b/server/app/services/dataflow/models.py index 5471cfe4..f69bfa01 100644 --- a/server/app/services/dataflow/models.py +++ b/server/app/services/dataflow/models.py @@ -724,3 +724,42 @@ class AnchorGraphResponse(BaseModel): generation: int | None = None programHash: str | None = None graph: AnchorGraphResult | None = None + + +# ---- file signals (contracts/fileSignals.schema.json) ------------------------ + + +class DataflowFinding(BaseModel): + rule: Literal["impossible-defense", "repeated-fork"] + file: str + line: int + column: int + endLine: int + message: str + + +class DataflowFileMetrics(BaseModel): + impossibleDefenses: int + relayHops: int + fanOut: int + representationChanges: int + pathDepth: int + + +class DataflowFileSignals(BaseModel): + file: str + metrics: DataflowFileMetrics + + +class FileSignalsResult(BaseModel): + outcome: Outcome + generation: int + programHash: str + tsconfig: str + typescript: str + nullProof: bool + reason: str | None + files: list[DataflowFileSignals] + findings: list[DataflowFinding] + unplacedDefenses: int + markdown: str diff --git a/server/tests/test_dataflow_models.py b/server/tests/test_dataflow_models.py index c284d00e..3d0afd12 100644 --- a/server/tests/test_dataflow_models.py +++ b/server/tests/test_dataflow_models.py @@ -23,6 +23,7 @@ ("functionEffects", models.FunctionEffectsResult), ("routePath", models.RoutePathResult), ("fileExports", models.FileExportsResult), + ("fileSignals", models.FileSignalsResult), ], ) def test_model_fields_match_the_schema(op, model): @@ -106,3 +107,9 @@ def test_anchor_graph_nested_fields_match(): assert set(schema["nodes"]["items"]["properties"]["kind"]["enum"]) == set( models.AnchorNode.model_fields["kind"].annotation.__args__ ) + + +def test_file_signals_nested_fields_match(): + schema = json.loads((CONTRACTS / "fileSignals.schema.json").read_text())["properties"] + assert set(models.DataflowFinding.model_fields) == set(schema["findings"]["items"]["properties"]) + assert set(models.DataflowFileMetrics.model_fields) == set(schema["files"]["items"]["properties"]["metrics"]["properties"])