solidity-argus 0.3.5 → 0.3.6

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.
@@ -8,10 +8,6 @@ export interface FindingStore {
8
8
  serialize(): string
9
9
  }
10
10
 
11
- /**
12
- * Creates a finding store with deduplication by check+file+lines
13
- * Deduplication key: `${check}:${file}:${lines[0]}-${lines[1]}`
14
- */
15
11
  function isValidHydrationFinding(f: unknown): f is Finding {
16
12
  if (typeof f !== "object" || f === null) return false
17
13
  const obj = f as Record<string, unknown>
@@ -28,39 +24,26 @@ function isValidHydrationFinding(f: unknown): f is Finding {
28
24
  }
29
25
 
30
26
  export function createFindingStore(state: AuditState): FindingStore {
31
- const findingMap = new Map<string, Finding>()
27
+ let observationCounter = state.findings.length
32
28
 
33
- function generateId(check: string, file: string, lines: [number, number]): string {
34
- const key = `${check}:${file}:${lines[0]}-${lines[1]}`
35
- // Use deterministic hash for stable IDs
29
+ function generateObservationId(check: string, file: string, lines: [number, number]): string {
30
+ const key = `${check}:${file}:${lines[0]}-${lines[1]}:${observationCounter}`
31
+ observationCounter += 1
36
32
  return createHash("sha256").update(key).digest("hex").substring(0, 16)
37
33
  }
38
34
 
39
- // Hydrate findingMap from persisted state.findings
40
- for (const f of state.findings) {
41
- if (!isValidHydrationFinding(f)) continue
42
- const id = generateId(f.check, f.file, f.lines)
43
- if (!findingMap.has(id)) {
44
- findingMap.set(id, { ...f, id })
45
- }
46
- }
35
+ const hydratedFindings = state.findings.filter(isValidHydrationFinding)
47
36
 
48
37
  function addFinding(finding: Omit<Finding, "id">): Finding {
49
- const id = generateId(finding.check, finding.file, finding.lines)
50
-
51
- // Check if finding already exists (deduplication)
52
- const existing = findingMap.get(id)
53
- if (existing) {
54
- return existing
55
- }
38
+ const id = generateObservationId(finding.check, finding.file, finding.lines)
56
39
 
57
40
  const newFinding: Finding = {
58
41
  ...finding,
59
42
  id,
60
43
  }
61
44
 
62
- findingMap.set(id, newFinding)
63
45
  state.findings.push(newFinding)
46
+ hydratedFindings.push(newFinding)
64
47
 
65
48
  return newFinding
66
49
  }
@@ -69,11 +52,13 @@ export function createFindingStore(state: AuditState): FindingStore {
69
52
  severity?: FindingSeverity
70
53
  source?: Finding["source"]
71
54
  }): Finding[] {
55
+ const findings = hydratedFindings.slice()
56
+
72
57
  if (!filter) {
73
- return Array.from(findingMap.values())
58
+ return findings
74
59
  }
75
60
 
76
- return Array.from(findingMap.values()).filter((finding) => {
61
+ return findings.filter((finding) => {
77
62
  if (filter.severity && finding.severity !== filter.severity) {
78
63
  return false
79
64
  }
@@ -85,12 +70,17 @@ export function createFindingStore(state: AuditState): FindingStore {
85
70
  }
86
71
 
87
72
  function hasFinding(check: string, file: string, lines: [number, number]): boolean {
88
- const id = generateId(check, file, lines)
89
- return findingMap.has(id)
73
+ return hydratedFindings.some(
74
+ (finding) =>
75
+ finding.check === check &&
76
+ finding.file === file &&
77
+ finding.lines[0] === lines[0] &&
78
+ finding.lines[1] === lines[1],
79
+ )
90
80
  }
91
81
 
92
82
  function serialize(): string {
93
- const findings = Array.from(findingMap.values())
83
+ const findings = hydratedFindings.slice()
94
84
  const contractCount = state.contractsReviewed.length
95
85
  const findingCount = findings.length
96
86
 
@@ -245,7 +245,7 @@ export function validateEventSequence(events: AuditEvent[]): void {
245
245
  export function projectFindings(events: AuditEvent[]): CanonicalFinding[] {
246
246
  validateEventSequence(events)
247
247
 
248
- const byId = new Map<string, CanonicalFinding>()
248
+ const findings: CanonicalFinding[] = []
249
249
 
250
250
  for (const event of events) {
251
251
  if (event.type !== "finding.added") continue
@@ -258,10 +258,15 @@ export function projectFindings(events: AuditEvent[]): CanonicalFinding[] {
258
258
  )
259
259
  }
260
260
 
261
- byId.set(validation.data.id, validation.data)
261
+ findings.push({
262
+ ...validation.data,
263
+ seq: event.seq,
264
+ run_id: event.run_id,
265
+ schema_version: event.schema_version,
266
+ })
262
267
  }
263
268
 
264
- return Array.from(byId.values()).sort((left, right) => {
269
+ return findings.sort((left, right) => {
265
270
  const bySeverity = SEVERITY_RANK[left.severity] - SEVERITY_RANK[right.severity]
266
271
  if (bySeverity !== 0) return bySeverity
267
272
 
@@ -271,7 +276,16 @@ export function projectFindings(events: AuditEvent[]): CanonicalFinding[] {
271
276
  const byLine = left.lines[0] - right.lines[0]
272
277
  if (byLine !== 0) return byLine
273
278
 
274
- return left.id.localeCompare(right.id)
279
+ const byIssue = left.issue_fingerprint.localeCompare(right.issue_fingerprint)
280
+ if (byIssue !== 0) return byIssue
281
+
282
+ const byObservation = left.observation_fingerprint.localeCompare(right.observation_fingerprint)
283
+ if (byObservation !== 0) return byObservation
284
+
285
+ const byId = left.id.localeCompare(right.id)
286
+ if (byId !== 0) return byId
287
+
288
+ return left.seq - right.seq
275
289
  })
276
290
  }
277
291
 
@@ -1,4 +1,5 @@
1
1
  import type {
2
+ ArgusAgentName,
2
3
  AuditPhase,
3
4
  Finding,
4
5
  FindingSeverity,
@@ -7,7 +8,7 @@ import type {
7
8
  ToolExecution,
8
9
  } from "./types"
9
10
 
10
- export const SCHEMA_VERSION = "1.0.0"
11
+ export const SCHEMA_VERSION = "2.0.0"
11
12
 
12
13
  export type AuditEventType =
13
14
  | "session.created"
@@ -45,6 +46,11 @@ export interface CanonicalFinding extends Finding {
45
46
  run_id: string
46
47
  seq: number
47
48
  schema_version: string
49
+ observation_id: string
50
+ issue_fingerprint: string
51
+ observation_fingerprint: string
52
+ reported_by_agent: ArgusAgentName
53
+ reported_by_session_id?: string
48
54
  }
49
55
 
50
56
  export interface CanonicalToolExecution extends ToolExecution {
@@ -156,6 +162,13 @@ const VALID_SOURCES: ReadonlySet<CanonicalFinding["source"]> = new Set([
156
162
  "solodit",
157
163
  "fuzz",
158
164
  ])
165
+ const VALID_AGENTS: ReadonlySet<ArgusAgentName> = new Set([
166
+ "argus",
167
+ "sentinel",
168
+ "pythia",
169
+ "scribe",
170
+ "unknown",
171
+ ])
159
172
 
160
173
  function isRecord(value: unknown): value is Record<string, unknown> {
161
174
  return typeof value === "object" && value !== null && !Array.isArray(value)
@@ -197,6 +210,10 @@ export function validateCanonicalFinding(raw: unknown): ValidationResult<Canonic
197
210
  pushRequiredStringError(errors, raw, "file")
198
211
  pushRequiredStringError(errors, raw, "run_id")
199
212
  pushRequiredStringError(errors, raw, "schema_version")
213
+ pushRequiredStringError(errors, raw, "observation_id")
214
+ pushRequiredStringError(errors, raw, "issue_fingerprint")
215
+ pushRequiredStringError(errors, raw, "observation_fingerprint")
216
+ pushRequiredStringError(errors, raw, "reported_by_agent")
200
217
 
201
218
  if (typeof raw.seq !== "number" || !Number.isInteger(raw.seq) || raw.seq < 0) {
202
219
  errors.push({
@@ -253,6 +270,37 @@ export function validateCanonicalFinding(raw: unknown): ValidationResult<Canonic
253
270
  })
254
271
  }
255
272
 
273
+ if (
274
+ typeof raw.reported_by_agent !== "string" ||
275
+ !VALID_AGENTS.has(raw.reported_by_agent as ArgusAgentName)
276
+ ) {
277
+ errors.push({
278
+ field: "reported_by_agent",
279
+ code: "enum",
280
+ message: "reported_by_agent must be one of: argus, sentinel, pythia, scribe, unknown",
281
+ })
282
+ }
283
+
284
+ if (
285
+ raw.reported_by_session_id != null &&
286
+ (typeof raw.reported_by_session_id !== "string" ||
287
+ raw.reported_by_session_id.trim().length === 0)
288
+ ) {
289
+ errors.push({
290
+ field: "reported_by_session_id",
291
+ code: "invalid",
292
+ message: "reported_by_session_id must be a non-empty string when provided",
293
+ })
294
+ }
295
+
296
+ if (raw.schema_version !== SCHEMA_VERSION) {
297
+ errors.push({
298
+ field: "schema_version",
299
+ code: "version_mismatch",
300
+ message: `schema_version must be ${SCHEMA_VERSION}`,
301
+ })
302
+ }
303
+
256
304
  if (errors.length > 0) {
257
305
  return { success: false, errors }
258
306
  }
@@ -260,7 +308,6 @@ export function validateCanonicalFinding(raw: unknown): ValidationResult<Canonic
260
308
  return { success: true, data: raw as unknown as CanonicalFinding }
261
309
  }
262
310
 
263
-
264
311
  export function validateCanonicalToolExecution(
265
312
  raw: unknown,
266
313
  ): ValidationResult<CanonicalToolExecution> {
@@ -1,4 +1,5 @@
1
1
  export type FindingSeverity = "Critical" | "High" | "Medium" | "Low" | "Informational"
2
+ export type ArgusAgentName = "argus" | "sentinel" | "pythia" | "scribe" | "unknown"
2
3
  export type AuditPhase =
3
4
  | "reconnaissance"
4
5
  | "scanning"
@@ -10,7 +11,7 @@ export type AuditPhase =
10
11
  | "complete"
11
12
 
12
13
  export interface Finding {
13
- id: string // unique hash: check+file+lines
14
+ id: string
14
15
  check: string // detector name e.g. "reentrancy-eth"
15
16
  severity: FindingSeverity
16
17
  confidence: "High" | "Medium" | "Low"
@@ -18,6 +19,15 @@ export interface Finding {
18
19
  file: string // relative file path
19
20
  lines: [number, number] // [start, end]
20
21
  source: "slither" | "manual" | "pattern" | "scvd" | "solodit" | "fuzz"
22
+ reported_by_agent?: ArgusAgentName
23
+ reported_by_session_id?: string
24
+ issue_fingerprint?: string
25
+ observation_fingerprint?: string
26
+ observation_id?: string
27
+ observation_ids?: string[]
28
+ reported_by_agents?: string[]
29
+ sources?: string[]
30
+ observation_count?: number
21
31
  remediation?: string
22
32
  exploitReference?: string
23
33
  provenance?: {
@@ -0,0 +1,125 @@
1
+ import { type ToolContext, tool } from "@opencode-ai/plugin"
2
+ import { normalizeToCanonicalFinding } from "../state/adapters"
3
+ import { SCHEMA_VERSION } from "../state/schemas"
4
+ import type { ArgusAgentName } from "../state/types"
5
+
6
+ type RecordFindingArgs = {
7
+ finding?: string
8
+ findings?: string
9
+ }
10
+
11
+ type RecordFindingResponse = {
12
+ success: boolean
13
+ count: number
14
+ findings: ReturnType<typeof normalizeToCanonicalFinding>["data"][]
15
+ schema_version: string
16
+ }
17
+
18
+ function parseFindingObject(raw: string, label: "finding" | "findings"): Record<string, unknown>[] {
19
+ let parsed: unknown
20
+ try {
21
+ parsed = JSON.parse(raw)
22
+ } catch {
23
+ throw new Error(`${label} must be valid JSON`)
24
+ }
25
+
26
+ if (label === "finding") {
27
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
28
+ throw new Error("finding must be a JSON object")
29
+ }
30
+ return [parsed as Record<string, unknown>]
31
+ }
32
+
33
+ if (!Array.isArray(parsed)) {
34
+ throw new Error("findings must be a JSON array")
35
+ }
36
+
37
+ return parsed.filter(
38
+ (item): item is Record<string, unknown> =>
39
+ typeof item === "object" && item !== null && !Array.isArray(item),
40
+ )
41
+ }
42
+
43
+ function normalizeAgent(value: string): ArgusAgentName {
44
+ if (value === "argus" || value === "sentinel" || value === "pythia" || value === "scribe") {
45
+ return value
46
+ }
47
+
48
+ return "unknown"
49
+ }
50
+
51
+ export async function executeRecordFinding(
52
+ args: RecordFindingArgs,
53
+ context: ToolContext,
54
+ ): Promise<string> {
55
+ const rawFindings: Record<string, unknown>[] = []
56
+
57
+ if (typeof args.finding === "string" && args.finding.trim().length > 0) {
58
+ rawFindings.push(...parseFindingObject(args.finding, "finding"))
59
+ }
60
+ if (typeof args.findings === "string" && args.findings.trim().length > 0) {
61
+ rawFindings.push(...parseFindingObject(args.findings, "findings"))
62
+ }
63
+
64
+ if (rawFindings.length === 0) {
65
+ throw new Error("Provide at least one finding via finding or findings")
66
+ }
67
+
68
+ const reportedByAgent = normalizeAgent(context.agent)
69
+ const reportedBySessionId = context.sessionID
70
+ const runId = context.sessionID || "manual-run"
71
+
72
+ const findings: ReturnType<typeof normalizeToCanonicalFinding>["data"][] = []
73
+ const errors: string[] = []
74
+
75
+ for (const [index, rawFinding] of rawFindings.entries()) {
76
+ const normalized = normalizeToCanonicalFinding(rawFinding, runId, index + 1, {
77
+ reportedByAgent,
78
+ reportedBySessionId,
79
+ observationId: `${reportedBySessionId}:${index + 1}`,
80
+ })
81
+
82
+ const diagnosticsErrors = normalized.diagnostics.filter((diag) => diag.level === "error")
83
+ if (diagnosticsErrors.length > 0) {
84
+ errors.push(
85
+ ...diagnosticsErrors.map(
86
+ (diag) => `[index:${index}] ${diag.field ?? "$root"}: ${diag.message}`,
87
+ ),
88
+ )
89
+ continue
90
+ }
91
+
92
+ findings.push(normalized.data)
93
+ }
94
+
95
+ if (errors.length > 0) {
96
+ throw new Error(`Failed to record finding(s): ${errors.join("; ")}`)
97
+ }
98
+
99
+ const response: RecordFindingResponse = {
100
+ success: true,
101
+ count: findings.length,
102
+ findings,
103
+ schema_version: SCHEMA_VERSION,
104
+ }
105
+
106
+ return JSON.stringify(response)
107
+ }
108
+
109
+ export const recordFindingTool = tool({
110
+ description:
111
+ "Record manually identified findings in canonical format for durable event-backed tracking.",
112
+ args: {
113
+ finding: tool.schema
114
+ .string()
115
+ .optional()
116
+ .describe("Serialized JSON object containing a single finding payload."),
117
+ findings: tool.schema
118
+ .string()
119
+ .optional()
120
+ .describe("Serialized JSON array containing one or more finding payload objects."),
121
+ },
122
+ async execute(args, context) {
123
+ return executeRecordFinding(args, context)
124
+ },
125
+ })
@@ -10,7 +10,11 @@ import { createLogger } from "../shared/logger"
10
10
  import { resolveProjectDir } from "../shared/project-utils"
11
11
  import { resolveReportPath } from "../shared/report-path-resolver"
12
12
  import { normalizeToCanonicalFinding } from "../state/adapters"
13
- import { stableHash } from "../state/projectors"
13
+ import {
14
+ compareIssueFingerprintSets,
15
+ dedupeFindingsForFinalOutput,
16
+ } from "../state/finding-aggregation"
17
+ import { projectFindings, stableHash } from "../state/projectors"
14
18
  import { type ReportInput, SCHEMA_VERSION, validateReportInput } from "../state/schemas"
15
19
  import type { AuditState, Finding, FindingSeverity } from "../state/types"
16
20
  import { checkReportPreflight } from "./report-preflight"
@@ -1009,7 +1013,7 @@ export function buildProvenanceAppendix(
1009
1013
  exec.endTime != null &&
1010
1014
  typeof exec.endTime === "number" &&
1011
1015
  !Number.isNaN(exec.endTime)
1012
- const duration = hasTimes ? formatDuration(exec.endTime! - exec.startTime) : "N/A"
1016
+ const duration = hasTimes ? formatDuration((exec.endTime as number) - exec.startTime) : "N/A"
1013
1017
  const status =
1014
1018
  typeof exec.success === "boolean"
1015
1019
  ? exec.success
@@ -1033,7 +1037,10 @@ export function buildProvenanceAppendix(
1033
1037
  lines.push(`- Pattern pack version: \`${state.patternVersion}\``)
1034
1038
  }
1035
1039
  if (syncExec) {
1036
- const syncTime = typeof syncExec.startTime === "number" && !Number.isNaN(syncExec.startTime) ? new Date(syncExec.startTime).toISOString() : "N/A"
1040
+ const syncTime =
1041
+ typeof syncExec.startTime === "number" && !Number.isNaN(syncExec.startTime)
1042
+ ? new Date(syncExec.startTime).toISOString()
1043
+ : "N/A"
1037
1044
  lines.push(`- SCVD last synced: ${syncTime}`)
1038
1045
  }
1039
1046
  }
@@ -1094,6 +1101,7 @@ export async function executeReportGeneration(
1094
1101
  const { reportInput, diagnostics } = parseReportInputPayload(args, context)
1095
1102
  const preflightPolicy = args.preflight_policy ?? "warn"
1096
1103
  let preflightWarningSection: string | null = null
1104
+ const warningBullets: string[] = []
1097
1105
  try {
1098
1106
  const readEventsFn = deps.readEvents ?? readEvents
1099
1107
  const events = await readEventsFn(reportInput.run_id, reportInput.projectDir)
@@ -1109,21 +1117,37 @@ export async function executeReportGeneration(
1109
1117
  parts.push(`missing required tools: ${preflightResult.missingRequiredTools.join(", ")}`)
1110
1118
  throw new Error(`Preflight failed (strict-fail): ${parts.join("; ")}`)
1111
1119
  }
1112
- const lines: string[] = [
1113
- "## \u26A0 Completeness Warning",
1114
- "",
1115
- "This report was generated with incomplete orchestration state.",
1116
- "",
1117
- ]
1118
1120
  if (preflightResult.orphanedTools.length > 0)
1119
- lines.push(`- Orphaned tools: ${preflightResult.orphanedTools.join(", ")}`)
1121
+ warningBullets.push(`- Orphaned tools: ${preflightResult.orphanedTools.join(", ")}`)
1120
1122
  if (preflightResult.missingLifecycle.length > 0)
1121
- lines.push(`- Missing lifecycle: ${preflightResult.missingLifecycle.join(", ")}`)
1123
+ warningBullets.push(`- Missing lifecycle: ${preflightResult.missingLifecycle.join(", ")}`)
1122
1124
  if (preflightResult.missingRequiredTools.length > 0)
1123
- lines.push(`- Missing required tools: ${preflightResult.missingRequiredTools.join(", ")}`)
1125
+ warningBullets.push(
1126
+ `- Missing required tools: ${preflightResult.missingRequiredTools.join(", ")}`,
1127
+ )
1124
1128
  if (preflightResult.warnings.length > 0)
1125
- lines.push(`- Warnings: ${preflightResult.warnings.join(", ")}`)
1126
- preflightWarningSection = lines.join("\n")
1129
+ warningBullets.push(`- Warnings: ${preflightResult.warnings.join(", ")}`)
1130
+ }
1131
+
1132
+ const eventFindings = dedupeFindingsForFinalOutput(projectFindings(events))
1133
+ const inputFindings = dedupeFindingsForFinalOutput(reportInput.findings)
1134
+ const parity = compareIssueFingerprintSets(eventFindings, inputFindings)
1135
+
1136
+ if (!parity.matches) {
1137
+ const mismatchSummary = `missing=${parity.missing.length}, extra=${parity.extra.length}`
1138
+ if (preflightPolicy === "strict-fail") {
1139
+ throw new Error(
1140
+ `Preflight failed (strict-fail): finding parity mismatch (${mismatchSummary})`,
1141
+ )
1142
+ }
1143
+
1144
+ warningBullets.push(`- Finding parity mismatch: ${mismatchSummary}`)
1145
+ if (parity.missing.length > 0) {
1146
+ warningBullets.push(`- Missing issue fingerprints: ${parity.missing.join(", ")}`)
1147
+ }
1148
+ if (parity.extra.length > 0) {
1149
+ warningBullets.push(`- Extra issue fingerprints: ${parity.extra.join(", ")}`)
1150
+ }
1127
1151
  }
1128
1152
  } catch (err) {
1129
1153
  if (err instanceof Error && err.message.startsWith("Preflight failed (strict-fail)")) {
@@ -1134,10 +1158,22 @@ export async function executeReportGeneration(
1134
1158
  }
1135
1159
  // warn mode: skip preflight when events cannot be read
1136
1160
  }
1161
+
1162
+ if (warningBullets.length > 0) {
1163
+ preflightWarningSection = [
1164
+ "## \u26A0 Completeness Warning",
1165
+ "",
1166
+ "This report was generated with incomplete orchestration state.",
1167
+ "",
1168
+ ...warningBullets,
1169
+ ].join("\n")
1170
+ }
1171
+
1137
1172
  const state = reportInputToAuditState(reportInput)
1138
1173
  const scope = args.scope.length > 0 ? args.scope : reportInput.scope
1174
+ const finalFindings = dedupeFindingsForFinalOutput(reportInput.findings)
1139
1175
  const findings = sortFindingsDeterministically(
1140
- state.findings.filter((finding) => shouldIncludeFinding(finding, threshold)),
1176
+ finalFindings.filter((finding) => shouldIncludeFinding(finding, threshold)),
1141
1177
  )
1142
1178
  const qualityGates = validateReportQuality(findings, qualityGatePolicy)
1143
1179
  if (!qualityGates.passed && qualityGatePolicy === "strict-fail") {