arkaik-mcp 0.2.3 → 0.4.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/dist/index.js CHANGED
@@ -5,6 +5,9 @@ var __export = (target, all) => {
5
5
  __defProp(target, name, { get: all[name], enumerable: true });
6
6
  };
7
7
 
8
+ // src/index.ts
9
+ import { dirname as dirname4 } from "node:path";
10
+
8
11
  // src/protocol.ts
9
12
  import { createInterface } from "node:readline";
10
13
  var PROTOCOL_VERSION = "2025-06-18";
@@ -15281,7 +15284,12 @@ var DeliverableShippedEventSchema = external_exports.object({
15281
15284
  summary: external_exports.string().optional(),
15282
15285
  url: external_exports.string().optional(),
15283
15286
  node_ids: external_exports.array(external_exports.string()).optional(),
15284
- platform: PlatformSchema.optional()
15287
+ platform: PlatformSchema.optional(),
15288
+ lab_note: external_exports.object({
15289
+ en: external_exports.object({ title: external_exports.string(), summary: external_exports.string() }).catchall(external_exports.unknown()),
15290
+ fr: external_exports.object({ title: external_exports.string().optional(), summary: external_exports.string().optional() }).catchall(external_exports.unknown()).optional(),
15291
+ suggested: external_exports.record(external_exports.string(), external_exports.unknown()).optional()
15292
+ }).catchall(external_exports.unknown()).optional().meta({ description: "The Lab Note a merged PR carried (slice 3); en.title/en.summary required when present." })
15285
15293
  }).catchall(external_exports.unknown());
15286
15294
  var IdeaProposedEventSchema = external_exports.object({
15287
15295
  ...envelope,
@@ -15317,6 +15325,55 @@ var RefStatusChangedEventSchema = external_exports.object({
15317
15325
  synced_at: external_exports.string()
15318
15326
  }).catchall(external_exports.unknown());
15319
15327
  var JournalBaselineEventSchema = external_exports.object({ ...envelope, type: external_exports.literal("journal.baseline"), node_ids: external_exports.array(external_exports.string()) }).catchall(external_exports.unknown());
15328
+ var QualityAuditCompletedEventSchema = external_exports.object({
15329
+ ...envelope,
15330
+ type: external_exports.literal("quality.audit.completed"),
15331
+ audit_id: external_exports.string(),
15332
+ framework_version: external_exports.string(),
15333
+ commit: external_exports.string().optional(),
15334
+ scores: external_exports.record(external_exports.string(), external_exports.record(external_exports.string(), external_exports.number())).optional(),
15335
+ counts: external_exports.object({
15336
+ critical: external_exports.number().optional(),
15337
+ high: external_exports.number().optional(),
15338
+ medium: external_exports.number().optional(),
15339
+ low: external_exports.number().optional(),
15340
+ info: external_exports.number().optional()
15341
+ }).catchall(external_exports.unknown()).optional()
15342
+ }).catchall(external_exports.unknown());
15343
+ var QualityFindingOpenedEventSchema = external_exports.object({
15344
+ ...envelope,
15345
+ type: external_exports.literal("quality.finding.opened"),
15346
+ finding_id: external_exports.string(),
15347
+ criterion_id: external_exports.string(),
15348
+ surface: external_exports.string(),
15349
+ severity: external_exports.string(),
15350
+ priority: external_exports.string(),
15351
+ title: external_exports.string(),
15352
+ node_ids: external_exports.array(external_exports.string()).optional(),
15353
+ issue_url: external_exports.string().optional()
15354
+ }).catchall(external_exports.unknown());
15355
+ var QualityFindingResolvedEventSchema = external_exports.object({
15356
+ ...envelope,
15357
+ type: external_exports.literal("quality.finding.resolved"),
15358
+ finding_id: external_exports.string(),
15359
+ resolved_by: external_exports.string().optional(),
15360
+ node_ids: external_exports.array(external_exports.string()).optional()
15361
+ }).catchall(external_exports.unknown());
15362
+ var QualityFindingAcceptedEventSchema = external_exports.object({
15363
+ ...envelope,
15364
+ type: external_exports.literal("quality.finding.accepted"),
15365
+ finding_id: external_exports.string(),
15366
+ reason: external_exports.string(),
15367
+ node_ids: external_exports.array(external_exports.string()).optional()
15368
+ }).catchall(external_exports.unknown());
15369
+ var QualitySignalTrippedEventSchema = external_exports.object({
15370
+ ...envelope,
15371
+ type: external_exports.literal("quality.signal.tripped"),
15372
+ criterion_id: external_exports.string(),
15373
+ surface: external_exports.string(),
15374
+ signal: external_exports.string(),
15375
+ detail: external_exports.string().optional()
15376
+ }).catchall(external_exports.unknown());
15320
15377
  var JOURNAL_EVENT_SCHEMAS = {
15321
15378
  "node.created": NodeCreatedEventSchema,
15322
15379
  "node.updated": NodeUpdatedEventSchema,
@@ -15332,7 +15389,12 @@ var JOURNAL_EVENT_SCHEMAS = {
15332
15389
  "ref.added": RefAddedEventSchema,
15333
15390
  "ref.removed": RefRemovedEventSchema,
15334
15391
  "ref.status_changed": RefStatusChangedEventSchema,
15335
- "journal.baseline": JournalBaselineEventSchema
15392
+ "journal.baseline": JournalBaselineEventSchema,
15393
+ "quality.audit.completed": QualityAuditCompletedEventSchema,
15394
+ "quality.finding.opened": QualityFindingOpenedEventSchema,
15395
+ "quality.finding.resolved": QualityFindingResolvedEventSchema,
15396
+ "quality.finding.accepted": QualityFindingAcceptedEventSchema,
15397
+ "quality.signal.tripped": QualitySignalTrippedEventSchema
15336
15398
  };
15337
15399
  var KnownJournalEventSchema = external_exports.union([
15338
15400
  NodeCreatedEventSchema,
@@ -15349,9 +15411,117 @@ var KnownJournalEventSchema = external_exports.union([
15349
15411
  RefAddedEventSchema,
15350
15412
  RefRemovedEventSchema,
15351
15413
  RefStatusChangedEventSchema,
15352
- JournalBaselineEventSchema
15414
+ JournalBaselineEventSchema,
15415
+ QualityAuditCompletedEventSchema,
15416
+ QualityFindingOpenedEventSchema,
15417
+ QualityFindingResolvedEventSchema,
15418
+ QualityFindingAcceptedEventSchema,
15419
+ QualitySignalTrippedEventSchema
15353
15420
  ]);
15354
15421
 
15422
+ // ../schema/src/quality-schemas.ts
15423
+ var GradeSchema = external_exports.enum(["A", "B", "C", "D", "E"]);
15424
+ var KritikScalesSchema = external_exports.object({
15425
+ grades: external_exports.partialRecord(GradeSchema, external_exports.number()).optional(),
15426
+ severity_buckets: external_exports.partialRecord(external_exports.enum(["critical", "high", "medium", "low", "info"]), external_exports.tuple([external_exports.number(), external_exports.number()])).optional(),
15427
+ caps: external_exports.object({ critical_open: GradeSchema.optional(), high_open: GradeSchema.optional() }).catchall(external_exports.unknown()).optional()
15428
+ }).catchall(external_exports.unknown()).meta({
15429
+ id: "KritikScales",
15430
+ description: "Overridable maturity/severity/grade scales carried by a criteria pack. Absent entries fall back to the framework defaults (packages/kritik-library/SPEC.md \xA7 4)."
15431
+ });
15432
+ var KritikReferenceSchema = external_exports.object({ title: external_exports.string(), anchor: external_exports.string().optional(), url: external_exports.string().optional() }).catchall(external_exports.unknown()).meta({ id: "KritikReference", description: "A stable external anchor behind a criterion (OWASP control, GDPR article, WCAG SC\u2026)." });
15433
+ var KritikIssueTemplateSchema = external_exports.object({
15434
+ title_template: external_exports.string().optional(),
15435
+ labels: external_exports.array(external_exports.string()).optional(),
15436
+ body_skeleton: external_exports.string().optional()
15437
+ }).catchall(external_exports.unknown()).meta({ id: "KritikIssueTemplate", description: "Per-criterion issue skeleton \u2014 what `arkaik kritik issue` prefills." });
15438
+ var KritikDomainSchema = external_exports.object({ code: external_exports.string(), name: external_exports.string(), description: external_exports.string().optional() }).catchall(external_exports.unknown()).meta({ id: "KritikDomain", description: "A top-level criteria category owning a roll-up row in the matrix." });
15439
+ var KritikCriterionSchema = external_exports.object({
15440
+ id: external_exports.string().meta({ description: "Stable identifier, `<DOMAIN>-NN`. Never redefined \u2014 retired via superseded_by." }),
15441
+ domain: external_exports.string(),
15442
+ subcategory: external_exports.string().optional(),
15443
+ name: external_exports.string().optional(),
15444
+ question: external_exports.string().optional(),
15445
+ definition: external_exports.string().optional(),
15446
+ rationale: external_exports.string().optional(),
15447
+ applies_to: external_exports.array(external_exports.string()).optional().meta({ description: "Surface ids where the criterion is meaningful; absence means N/A." }),
15448
+ level_anchors: external_exports.record(external_exports.string(), external_exports.string()).optional().meta({ description: "Observable descriptions per maturity level, keyed l0\u2026l4." }),
15449
+ default_impact: external_exports.number().optional(),
15450
+ weight: external_exports.number().optional().meta({ description: "Weight in the domain roll-up (1\u20133; 3 = load-bearing). Absent means 1." }),
15451
+ references: external_exports.array(KritikReferenceSchema).optional(),
15452
+ checklist: external_exports.array(external_exports.string()).optional(),
15453
+ signals: external_exports.array(external_exports.string()).optional().meta({ description: "Mechanically checkable monitoring hooks run between audits." }),
15454
+ remediation: external_exports.string().optional(),
15455
+ issue: KritikIssueTemplateSchema.optional(),
15456
+ superseded_by: external_exports.string().optional()
15457
+ }).catchall(external_exports.unknown()).meta({ id: "KritikCriterion", description: "The atomic auditable unit (packages/kritik-library/SPEC.md \xA7 5)." });
15458
+ var KritikLibrarySchema = external_exports.object({
15459
+ version: external_exports.string().meta({ description: "Semver of the pack; matrices are comparable only within a major." }),
15460
+ domains: external_exports.array(KritikDomainSchema),
15461
+ criteria: external_exports.array(KritikCriterionSchema),
15462
+ scales: KritikScalesSchema.optional()
15463
+ }).catchall(external_exports.unknown()).meta({
15464
+ id: "KritikLibrary",
15465
+ description: "A versioned criteria pack. Embedded on export; repos may instead pin it as a sidecar file."
15466
+ });
15467
+ var SurfaceDefSchema = external_exports.object({
15468
+ id: external_exports.string(),
15469
+ title: external_exports.string(),
15470
+ platform: PlatformSchema.optional().meta({
15471
+ description: "Optional bridge to PLATFORM_IDS where a surface is also a view-shipping platform. Surfaces are not platforms (RFC \xA7 2)."
15472
+ }),
15473
+ path: external_exports.string().optional()
15474
+ }).catchall(external_exports.unknown()).meta({ id: "SurfaceDef", description: "One independently assessable body of code \u2014 an audit target, chosen at install." });
15475
+ var QualityProfileSchema = external_exports.object({
15476
+ surfaces: external_exports.array(SurfaceDefSchema),
15477
+ domain_weights: external_exports.record(external_exports.string(), external_exports.number()).optional().meta({
15478
+ description: "Per-domain weight in the surface roll-up, keyed by domain code. A missing weight is 1."
15479
+ })
15480
+ }).catchall(external_exports.unknown()).meta({ id: "QualityProfile", description: "The project's parameterization of the pack (RFC \xA7 6)." });
15481
+ var QualityAssessmentSchema = external_exports.object({
15482
+ criterion_id: external_exports.string(),
15483
+ surface: external_exports.string(),
15484
+ level: external_exports.union([external_exports.literal(0), external_exports.literal(1), external_exports.literal(2), external_exports.literal(3), external_exports.literal(4)]).meta({
15485
+ description: "Maturity 0\u20134. N/A is the absence of the row, never a level."
15486
+ }),
15487
+ evidence: external_exports.string().meta({ description: "file:line / config citations. A score without evidence is an opinion, not an assessment." }),
15488
+ audit_id: external_exports.string(),
15489
+ commit: external_exports.string().optional(),
15490
+ ts: external_exports.string()
15491
+ }).catchall(external_exports.unknown()).meta({ id: "QualityAssessment", description: "One (criterion \xD7 surface) score \u2014 latest wins; history lives in the journal." });
15492
+ var QualityFindingSchema = external_exports.object({
15493
+ id: external_exports.string(),
15494
+ criterion_id: external_exports.string(),
15495
+ surface: external_exports.string(),
15496
+ title: external_exports.string(),
15497
+ detail: external_exports.string(),
15498
+ evidence: external_exports.string(),
15499
+ impact: external_exports.number().meta({ description: "Worst plausible consequence, 1\u20135." }),
15500
+ likelihood: external_exports.number().meta({ description: "Probability it materializes, 1\u20135." }),
15501
+ cost: external_exports.enum(["S", "M", "L", "XL"]),
15502
+ status: external_exports.enum(["open", "resolved", "refuted", "accepted-risk"]),
15503
+ remediation: external_exports.string().optional(),
15504
+ node_ids: external_exports.array(external_exports.string()).optional().meta({ description: "Graph nodes this finding is about \u2014 the tie deliverable.shipped already uses." }),
15505
+ issue_url: external_exports.string().optional(),
15506
+ commit: external_exports.string().optional().meta({
15507
+ description: "Commit SHA anchoring the file:line evidence. Required by policy on any finding written away from a checkout (issue #400 decision 4) \u2014 without it a stale citation is indistinguishable from a wrong one."
15508
+ }),
15509
+ verification: external_exports.object({ verdict: external_exports.enum(["CONFIRMED", "REFUTED", "DOWNGRADED"]), note: external_exports.string().optional() }).catchall(external_exports.unknown()).optional().meta({ description: "Result of the adversarial refutation pass. Refuted findings are disclosed, not deleted." })
15510
+ }).catchall(external_exports.unknown()).meta({
15511
+ id: "QualityFinding",
15512
+ description: "One concrete defect. Severity and priority are deliberately absent \u2014 they are derived from impact \xD7 likelihood and cost (deriveQualityMatrix), so a finding can never carry a severity its own numbers disagree with."
15513
+ });
15514
+ var QualitySectionSchema = external_exports.object({
15515
+ framework_version: external_exports.string(),
15516
+ library: KritikLibrarySchema.optional(),
15517
+ profile: QualityProfileSchema,
15518
+ assessments: external_exports.array(QualityAssessmentSchema),
15519
+ findings: external_exports.array(QualityFindingSchema)
15520
+ }).catchall(external_exports.unknown()).meta({
15521
+ id: "QualitySection",
15522
+ description: "The project's Kritik state (docs/rfcs/kritik.md \xA7 4.1) \u2014 profile, assessments, findings. Criteria are library content, not graph nodes; the matrix is a projection, never stored."
15523
+ });
15524
+
15355
15525
  // ../schema/src/bundle.ts
15356
15526
  var PlatformStatusMapSchema = external_exports.partialRecord(
15357
15527
  PlatformSchema,
@@ -15493,7 +15663,8 @@ var ProjectMetadataSchema = external_exports.object({
15493
15663
  }),
15494
15664
  products: external_exports.array(ProductDefinitionSchema).optional().meta({
15495
15665
  description: "Product definitions (docs/spec/bundle-format.md \xA7 Products) \u2014 additive; unknown fields preserved."
15496
- })
15666
+ }),
15667
+ pollen: external_exports.object({ plant: external_exports.string().regex(/^[a-z0-9][a-z0-9-]*$/).optional() }).catchall(external_exports.unknown()).optional().meta({ description: "Federation settings \u2014 docs/spec/services.md \xA7 Pollen feed. `plant` enables the feed." })
15497
15668
  }).catchall(external_exports.unknown()).meta({ id: "ProjectMetadata", description: "Optional project-level UI settings." });
15498
15669
  var ProjectSchema = external_exports.object({
15499
15670
  id: external_exports.string().meta({ description: "Unique project identifier." }),
@@ -15521,6 +15692,9 @@ var ProjectBundleSchema = external_exports.object({
15521
15692
  edges: external_exports.array(EdgeSchema).meta({ description: "All edges (relationships) between nodes." }),
15522
15693
  journal: external_exports.array(JournalEventSchema).optional().meta({
15523
15694
  description: "Optional embedded journal events \u2014 the Level 2 interchange projection (docs/spec/journal.md). Canonical storage in repos is the JSONL sidecar; a bundle without a journal is Level 0/1, not an error."
15695
+ }),
15696
+ quality: QualitySectionSchema.optional().meta({
15697
+ description: "Optional Kritik quality state (docs/rfcs/kritik.md \xA7 4.1) \u2014 the pinned pack version, the project's surface profile, its assessments and findings. Additive: a bundle without it is not an error, and the comparative matrix is derived from it (deriveQualityMatrix), never stored."
15524
15698
  })
15525
15699
  }).catchall(external_exports.unknown()).meta({
15526
15700
  id: "ProjectBundle",
@@ -15740,6 +15914,207 @@ function listMaps(project) {
15740
15914
  return [...BUILT_IN_MAPS, ...custom2];
15741
15915
  }
15742
15916
 
15917
+ // ../schema/src/quality.ts
15918
+ var asArray = (value) => Array.isArray(value) ? value : [];
15919
+ var MATURITY_LEVELS = [0, 1, 2, 3, 4];
15920
+ var FINDING_SEVERITIES = ["critical", "high", "medium", "low", "info"];
15921
+ var REMEDIATION_COSTS = ["S", "M", "L", "XL"];
15922
+ var FINDING_STATUSES = ["open", "resolved", "refuted", "accepted-risk"];
15923
+ var QUALITY_GRADES = ["A", "B", "C", "D", "E"];
15924
+ var DEFAULT_GRADE_BANDS = { A: 85, B: 70, C: 55, D: 40, E: 0 };
15925
+ var DEFAULT_SEVERITY_BUCKETS = {
15926
+ critical: [20, 25],
15927
+ high: [12, 19],
15928
+ medium: [6, 11],
15929
+ low: [2, 5],
15930
+ info: [1, 1]
15931
+ };
15932
+ var DEFAULT_CAPS = {
15933
+ critical_open: "D",
15934
+ high_open: "B"
15935
+ };
15936
+ var CROSS_SURFACE_ID = "cross-surface";
15937
+ function mergeKritikLibrary(pack, overlay) {
15938
+ if (!overlay || typeof overlay !== "object") return pack;
15939
+ const domains = [...asArray(pack.domains)];
15940
+ for (const domain2 of asArray(overlay.domains)) {
15941
+ if (typeof domain2?.code !== "string" || domain2.code === "") continue;
15942
+ const at = domains.findIndex((existing) => existing?.code === domain2.code);
15943
+ if (at >= 0) domains[at] = domain2;
15944
+ else domains.push(domain2);
15945
+ }
15946
+ const criteria = [...asArray(pack.criteria)];
15947
+ for (const criterion of asArray(overlay.criteria)) {
15948
+ if (typeof criterion?.id !== "string" || criterion.id === "") continue;
15949
+ const at = criteria.findIndex((existing) => existing?.id === criterion.id);
15950
+ if (at >= 0) criteria[at] = criterion;
15951
+ else criteria.push(criterion);
15952
+ }
15953
+ const scales = pack.scales || overlay.scales ? { ...pack.scales ?? {}, ...overlay.scales ?? {} } : void 0;
15954
+ return { ...pack, domains, criteria, ...scales ? { scales } : {} };
15955
+ }
15956
+ function bucketsOf(library) {
15957
+ const stored = library?.scales?.severity_buckets;
15958
+ const out = { ...DEFAULT_SEVERITY_BUCKETS };
15959
+ if (!stored || typeof stored !== "object") return out;
15960
+ for (const severity of FINDING_SEVERITIES) {
15961
+ const band = stored[severity];
15962
+ if (Array.isArray(band) && typeof band[0] === "number" && typeof band[1] === "number") {
15963
+ out[severity] = [band[0], band[1]];
15964
+ }
15965
+ }
15966
+ return out;
15967
+ }
15968
+ function bandsOf(library) {
15969
+ const stored = library?.scales?.grades;
15970
+ const out = { ...DEFAULT_GRADE_BANDS };
15971
+ if (!stored || typeof stored !== "object") return out;
15972
+ for (const grade of QUALITY_GRADES) {
15973
+ const min = stored[grade];
15974
+ if (typeof min === "number" && Number.isFinite(min)) out[grade] = min;
15975
+ }
15976
+ return out;
15977
+ }
15978
+ function capsOf(library) {
15979
+ const stored = library?.scales?.caps;
15980
+ const pick2 = (value, fallback) => typeof value === "string" && QUALITY_GRADES.includes(value) ? value : fallback;
15981
+ return {
15982
+ critical_open: pick2(stored?.critical_open, DEFAULT_CAPS.critical_open),
15983
+ high_open: pick2(stored?.high_open, DEFAULT_CAPS.high_open)
15984
+ };
15985
+ }
15986
+ function severityOf(finding, library) {
15987
+ const impact = typeof finding.impact === "number" ? finding.impact : 0;
15988
+ const likelihood = typeof finding.likelihood === "number" ? finding.likelihood : 0;
15989
+ const score = impact * likelihood;
15990
+ const buckets = bucketsOf(library);
15991
+ const worstFirst = [...FINDING_SEVERITIES].sort((a, b) => buckets[b][0] - buckets[a][0]);
15992
+ for (const severity of worstFirst) {
15993
+ if (score >= buckets[severity][0]) return severity;
15994
+ }
15995
+ return "info";
15996
+ }
15997
+ function priorityOf(finding, library) {
15998
+ const severity = severityOf(finding, library);
15999
+ const cheap = finding.cost === "S";
16000
+ if (severity === "critical") return "P0";
16001
+ if (severity === "high") return cheap ? "P0" : "P1";
16002
+ if (severity === "medium") return cheap ? "P1" : "P2";
16003
+ if (severity === "low") return cheap ? "P2" : "P3";
16004
+ return "P3";
16005
+ }
16006
+ function gradeOf(score, library) {
16007
+ const bands = bandsOf(library);
16008
+ const bestFirst = [...QUALITY_GRADES].sort((a, b) => bands[b] - bands[a]);
16009
+ for (const grade of bestFirst) {
16010
+ if (score >= bands[grade]) return grade;
16011
+ }
16012
+ return "E";
16013
+ }
16014
+ function capGrade(grade, cap) {
16015
+ return QUALITY_GRADES[Math.max(QUALITY_GRADES.indexOf(grade), QUALITY_GRADES.indexOf(cap))];
16016
+ }
16017
+ function isOpenFinding(finding) {
16018
+ return (finding.status ?? "open") === "open";
16019
+ }
16020
+ function resolveKritikLibrary(section, library) {
16021
+ const explicit = library ?? section?.library;
16022
+ if (explicit && Array.isArray(explicit.criteria) && Array.isArray(explicit.domains)) return explicit;
16023
+ if (!section) return void 0;
16024
+ const ids = /* @__PURE__ */ new Set();
16025
+ for (const row of [...asArray(section.assessments), ...asArray(section.findings)]) {
16026
+ if (typeof row?.criterion_id === "string" && row.criterion_id !== "") ids.add(row.criterion_id);
16027
+ }
16028
+ if (ids.size === 0) return void 0;
16029
+ const domainOf = (id) => id.includes("-") ? id.slice(0, id.lastIndexOf("-")) : id;
16030
+ const criteria = [...ids].sort().map((id) => ({ id, domain: domainOf(id), weight: 1 }));
16031
+ const domains = [...new Set(criteria.map((c) => c.domain))].sort().map((code) => ({ code, name: code }));
16032
+ return { version: explicit?.version ?? "unknown", domains, criteria, scales: explicit?.scales };
16033
+ }
16034
+ function deriveQualityMatrix(bundle, library) {
16035
+ const section = bundle.quality;
16036
+ const pack = resolveKritikLibrary(section, library);
16037
+ const assessments = asArray(section?.assessments);
16038
+ const findings = asArray(section?.findings);
16039
+ const openFindings = findings.filter((finding) => isOpenFinding(finding));
16040
+ const declared2 = asArray(section?.profile?.surfaces).map((surface) => surface?.id).filter((id) => typeof id === "string" && id !== "");
16041
+ const surfaces = declared2.length > 0 ? [...new Set(declared2)] : [...new Set(assessments.map((a) => a.surface).filter((id) => typeof id === "string" && id !== ""))].sort();
16042
+ const domains = asArray(pack?.domains).map((domain2) => domain2?.code).filter((code) => typeof code === "string" && code !== "");
16043
+ const domainOfCriterion = /* @__PURE__ */ new Map();
16044
+ const weightOfCriterion = /* @__PURE__ */ new Map();
16045
+ for (const criterion of asArray(pack?.criteria)) {
16046
+ if (typeof criterion?.id !== "string") continue;
16047
+ if (typeof criterion.domain === "string") domainOfCriterion.set(criterion.id, criterion.domain);
16048
+ weightOfCriterion.set(criterion.id, typeof criterion.weight === "number" && criterion.weight > 0 ? criterion.weight : 1);
16049
+ }
16050
+ const caps = capsOf(pack);
16051
+ const weights = section?.profile?.domain_weights;
16052
+ const matrix = {};
16053
+ for (const domain2 of domains) {
16054
+ matrix[domain2] = {};
16055
+ for (const surface of surfaces) {
16056
+ const rows = assessments.filter((a) => a.surface === surface && domainOfCriterion.get(a.criterion_id) === domain2);
16057
+ if (rows.length === 0) {
16058
+ matrix[domain2][surface] = null;
16059
+ continue;
16060
+ }
16061
+ let earned = 0;
16062
+ let available = 0;
16063
+ for (const row of rows) {
16064
+ const weight = weightOfCriterion.get(row.criterion_id) ?? 1;
16065
+ const level = typeof row.level === "number" ? Math.min(Math.max(row.level, 0), 4) : 0;
16066
+ earned += level * weight;
16067
+ available += 4 * weight;
16068
+ }
16069
+ if (available === 0) {
16070
+ matrix[domain2][surface] = null;
16071
+ continue;
16072
+ }
16073
+ const score = Math.round(earned / available * 100);
16074
+ const cellSeverities = openFindings.filter((finding) => finding.surface === surface && domainOfCriterion.get(finding.criterion_id) === domain2).map((finding) => severityOf(finding, pack));
16075
+ const banded = gradeOf(score, pack);
16076
+ let grade = banded;
16077
+ if (cellSeverities.includes("critical")) grade = capGrade(grade, caps.critical_open);
16078
+ else if (cellSeverities.includes("high")) grade = capGrade(grade, caps.high_open);
16079
+ matrix[domain2][surface] = {
16080
+ score,
16081
+ grade,
16082
+ capped: grade !== banded,
16083
+ criteria: rows.length,
16084
+ findings: {
16085
+ critical: cellSeverities.filter((s) => s === "critical").length,
16086
+ high: cellSeverities.filter((s) => s === "high").length,
16087
+ medium: cellSeverities.filter((s) => s === "medium").length,
16088
+ low: cellSeverities.filter((s) => s === "low").length
16089
+ }
16090
+ };
16091
+ }
16092
+ }
16093
+ const overall = {};
16094
+ for (const surface of surfaces) {
16095
+ let weighted = 0;
16096
+ let total = 0;
16097
+ for (const domain2 of domains) {
16098
+ const cell = matrix[domain2]?.[surface];
16099
+ if (!cell) continue;
16100
+ const weight = typeof weights?.[domain2] === "number" ? weights[domain2] : 1;
16101
+ weighted += cell.score * weight;
16102
+ total += weight;
16103
+ }
16104
+ overall[surface] = total > 0 ? Math.round(weighted / total) : null;
16105
+ }
16106
+ const finding_counts = { critical: 0, high: 0, medium: 0, low: 0, info: 0 };
16107
+ for (const finding of openFindings) finding_counts[severityOf(finding, pack)]++;
16108
+ return {
16109
+ framework_version: section?.framework_version,
16110
+ surfaces,
16111
+ domains,
16112
+ matrix,
16113
+ overall,
16114
+ finding_counts
16115
+ };
16116
+ }
16117
+
15743
16118
  // ../schema/src/validate.ts
15744
16119
  var VALID_STAGES = ["beta", "monitoring", "deprecated"];
15745
16120
  var VALID_VIEW_CARD_VARIANTS = ["compact", "large"];
@@ -16436,6 +16811,160 @@ function validateBundle(input) {
16436
16811
  for (const id of flowGraph.keys()) {
16437
16812
  dfs(id);
16438
16813
  }
16814
+ const quality = bundle.quality;
16815
+ if (typeof quality === "object" && quality !== null && !Array.isArray(quality)) {
16816
+ const section = quality;
16817
+ const assessments = Array.isArray(section.assessments) ? section.assessments : [];
16818
+ const qualityFindings = Array.isArray(section.findings) ? section.findings : [];
16819
+ const profile = typeof section.profile === "object" && section.profile !== null ? section.profile : void 0;
16820
+ const declaredSurfaces = /* @__PURE__ */ new Set();
16821
+ if (Array.isArray(profile?.surfaces)) {
16822
+ profile.surfaces.forEach((entry, index) => {
16823
+ if (typeof entry !== "object" || entry === null || Array.isArray(entry)) return;
16824
+ const surface = entry;
16825
+ const surfaceId = typeof surface.id === "string" ? surface.id : void 0;
16826
+ if (surfaceId === void 0 || surfaceId.trim() === "") return;
16827
+ if (declaredSurfaces.has(surfaceId)) {
16828
+ warn(`quality.profile.surfaces[${index}].id`, "quality-duplicate-surface", `Duplicate surface id "${surfaceId}" \u2014 the first wins`);
16829
+ }
16830
+ declaredSurfaces.add(surfaceId);
16831
+ });
16832
+ }
16833
+ if (declaredSurfaces.size === 0 && (assessments.length > 0 || qualityFindings.length > 0)) {
16834
+ warn(
16835
+ "quality.profile.surfaces",
16836
+ "quality-no-surfaces",
16837
+ "Quality data is stored but the profile declares no surfaces \u2014 the matrix falls back to the surfaces the assessments name"
16838
+ );
16839
+ }
16840
+ const library = typeof section.library === "object" && section.library !== null ? section.library : void 0;
16841
+ const knownCriteria = /* @__PURE__ */ new Set();
16842
+ const retiredCriteria = /* @__PURE__ */ new Map();
16843
+ if (Array.isArray(library?.criteria)) {
16844
+ for (const entry of library.criteria) {
16845
+ if (typeof entry !== "object" || entry === null) continue;
16846
+ const criterion = entry;
16847
+ if (typeof criterion.id !== "string") continue;
16848
+ knownCriteria.add(criterion.id);
16849
+ if (typeof criterion.superseded_by === "string" && criterion.superseded_by !== "") {
16850
+ retiredCriteria.set(criterion.id, criterion.superseded_by);
16851
+ }
16852
+ }
16853
+ } else if (assessments.length > 0 || qualityFindings.length > 0) {
16854
+ warn(
16855
+ "quality.library",
16856
+ "quality-library-missing",
16857
+ "No criteria pack is embedded \u2014 criterion ids cannot be resolved to domains or weights; the matrix uses a synthesized library"
16858
+ );
16859
+ }
16860
+ if (typeof section.framework_version !== "string" || section.framework_version === "") {
16861
+ warn("quality.framework_version", "quality-framework-version-missing", "Quality section has no framework_version \u2014 scores are not comparable across audits without one");
16862
+ }
16863
+ const checkRowRefs = (row, path, label) => {
16864
+ const criterionId = typeof row.criterion_id === "string" ? row.criterion_id : void 0;
16865
+ if (criterionId !== void 0 && knownCriteria.size > 0 && !knownCriteria.has(criterionId)) {
16866
+ warn(`${path}.criterion_id`, "quality-unknown-criterion", `${label}: criterion "${criterionId}" is not in the pinned library`);
16867
+ }
16868
+ const supersededBy = criterionId !== void 0 ? retiredCriteria.get(criterionId) : void 0;
16869
+ if (supersededBy !== void 0) {
16870
+ warn(`${path}.criterion_id`, "quality-retired-criterion", `${label}: criterion "${criterionId}" is retired \u2014 superseded by "${supersededBy}"`);
16871
+ }
16872
+ const surface = typeof row.surface === "string" ? row.surface : void 0;
16873
+ if (surface !== void 0 && surface !== CROSS_SURFACE_ID && declaredSurfaces.size > 0 && !declaredSurfaces.has(surface)) {
16874
+ warn(`${path}.surface`, "quality-unknown-surface", `${label}: surface "${surface}" is not declared in the profile`);
16875
+ }
16876
+ };
16877
+ const seenCells = /* @__PURE__ */ new Set();
16878
+ assessments.forEach((entry, index) => {
16879
+ if (typeof entry !== "object" || entry === null || Array.isArray(entry)) return;
16880
+ const assessment = entry;
16881
+ const path = `quality.assessments[${index}]`;
16882
+ const label = `Assessment ${index}`;
16883
+ checkRowRefs(assessment, path, label);
16884
+ const level = assessment.level;
16885
+ if (typeof level !== "number" || !Number.isInteger(level) || level < 0 || level > 4) {
16886
+ warn(`${path}.level`, "quality-level-range", `${label}: level must be an integer 0-4 (N/A is the absence of the row, not a level)`);
16887
+ }
16888
+ if (assessment.surface === CROSS_SURFACE_ID) {
16889
+ warn(`${path}.surface`, "quality-cross-surface-assessment", `${label}: "${CROSS_SURFACE_ID}" is a findings-only lens \u2014 it carries no matrix column, so this score would render nowhere`);
16890
+ }
16891
+ if (typeof assessment.evidence !== "string" || assessment.evidence.trim() === "") {
16892
+ warn(`${path}.evidence`, "quality-assessment-no-evidence", `${label}: scored with no evidence \u2014 a score without a citation is an opinion, not an assessment`);
16893
+ }
16894
+ const criterionId = typeof assessment.criterion_id === "string" ? assessment.criterion_id : void 0;
16895
+ const surface = typeof assessment.surface === "string" ? assessment.surface : void 0;
16896
+ if (criterionId !== void 0 && surface !== void 0) {
16897
+ const cell = `${criterionId}\0${surface}`;
16898
+ if (seenCells.has(cell)) {
16899
+ warn(`${path}`, "quality-duplicate-assessment", `${label}: a second score for (${criterionId} x ${surface}) \u2014 the section stores latest-per-cell, so this cell is ambiguous`);
16900
+ }
16901
+ seenCells.add(cell);
16902
+ }
16903
+ });
16904
+ const seenFindingIds = /* @__PURE__ */ new Set();
16905
+ qualityFindings.forEach((entry, index) => {
16906
+ if (typeof entry !== "object" || entry === null || Array.isArray(entry)) return;
16907
+ const finding = entry;
16908
+ const path = `quality.findings[${index}]`;
16909
+ const label = `Finding ${index}`;
16910
+ checkRowRefs(finding, path, label);
16911
+ const findingId = typeof finding.id === "string" ? finding.id : void 0;
16912
+ if (findingId !== void 0) {
16913
+ if (seenFindingIds.has(findingId)) {
16914
+ warn(`${path}.id`, "quality-duplicate-finding-id", `Duplicate finding id "${findingId}"`);
16915
+ }
16916
+ seenFindingIds.add(findingId);
16917
+ }
16918
+ for (const field of ["impact", "likelihood"]) {
16919
+ const value = finding[field];
16920
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > 5) {
16921
+ warn(`${path}.${field}`, "quality-risk-range", `${label}: ${field} must be an integer 1-5 \u2014 severity is derived from impact x likelihood`);
16922
+ }
16923
+ }
16924
+ for (const derived of ["severity", "priority"]) {
16925
+ if (derived in finding) {
16926
+ warn(`${path}.${derived}`, "quality-derived-field-stored", `${label}: ${derived} is derived from impact, likelihood and cost \u2014 storing it lets it drift from the numbers behind it`);
16927
+ }
16928
+ }
16929
+ if (finding.status === "accepted-risk" && (typeof finding.detail !== "string" || finding.detail.trim() === "")) {
16930
+ warn(`${path}.detail`, "quality-accepted-risk-no-note", `${label}: accepted-risk with no note \u2014 an accepted risk is a decision and reads like one`);
16931
+ }
16932
+ });
16933
+ const openedInJournal = /* @__PURE__ */ new Set();
16934
+ const journalEvents = Array.isArray(bundle.journal) ? bundle.journal : [];
16935
+ journalEvents.forEach((entry) => {
16936
+ if (typeof entry !== "object" || entry === null) return;
16937
+ const event = entry;
16938
+ if (event.type === "quality.finding.opened" && typeof event.finding_id === "string") openedInJournal.add(event.finding_id);
16939
+ });
16940
+ journalEvents.forEach((entry, index) => {
16941
+ if (typeof entry !== "object" || entry === null) return;
16942
+ const event = entry;
16943
+ const type = typeof event.type === "string" ? event.type : "";
16944
+ if (!type.startsWith("quality.")) return;
16945
+ if (typeof event.actor !== "string" || event.actor.trim() === "") {
16946
+ warn(`journal[${index}].actor`, "quality-event-no-actor", `Journal event ${index}: ${type} has no actor \u2014 human, agent and CI scores become indistinguishable`);
16947
+ }
16948
+ if (type === "quality.finding.resolved" && typeof event.finding_id === "string") {
16949
+ if (!openedInJournal.has(event.finding_id) && !seenFindingIds.has(event.finding_id)) {
16950
+ warn(
16951
+ `journal[${index}].finding_id`,
16952
+ "quality-resolved-never-opened",
16953
+ `Journal event ${index}: resolves finding "${event.finding_id}", which no quality.finding.opened event or stored finding ever declared`
16954
+ );
16955
+ }
16956
+ }
16957
+ if (type === "quality.finding.accepted" && typeof event.finding_id === "string") {
16958
+ if (!openedInJournal.has(event.finding_id) && !seenFindingIds.has(event.finding_id)) {
16959
+ warn(
16960
+ `journal[${index}].finding_id`,
16961
+ "quality-accepted-never-opened",
16962
+ `Journal event ${index}: accepts finding "${event.finding_id}", which no quality.finding.opened event or stored finding ever declared`
16963
+ );
16964
+ }
16965
+ }
16966
+ });
16967
+ }
16439
16968
  for (const finding of crossCheckJournal(bundle)) findings.push(finding);
16440
16969
  return result();
16441
16970
  }
@@ -17106,136 +17635,1405 @@ function applyOps(input, ops) {
17106
17635
  return { nodes, edges, eventInputs, synthesizedEdges, cascadedEdgeIds };
17107
17636
  }
17108
17637
 
17109
- // src/tools.ts
17110
- async function load(ctx) {
17111
- let graph;
17112
- try {
17113
- graph = await ctx.store.load();
17114
- } catch (error51) {
17115
- throw new ToolError(`Cannot load ${ctx.store.describe()}: ${error51.message}`);
17116
- }
17638
+ // ../schema/src/quality-ops.ts
17639
+ function upsertAssessment(assessments, next) {
17640
+ const index = assessments.findIndex(
17641
+ (candidate) => candidate.criterion_id === next.criterion_id && candidate.surface === next.surface
17642
+ );
17643
+ if (index === -1) return { assessments: [...assessments, next] };
17644
+ const updated = [...assessments];
17645
+ const replaced = updated[index];
17646
+ updated[index] = next;
17647
+ return { assessments: updated, replaced };
17648
+ }
17649
+ function domainCodeOf(criterionId, library) {
17650
+ const criterion = (library?.criteria ?? []).find((candidate) => candidate.id === criterionId);
17651
+ if (typeof criterion?.domain === "string" && criterion.domain !== "") return criterion.domain;
17652
+ const dash = criterionId.indexOf("-");
17653
+ return dash > 0 ? criterionId.slice(0, dash) : criterionId;
17654
+ }
17655
+ function mintFindingId(auditId, criterionId, surface, taken, library) {
17656
+ const prefix = `F-${auditId}-${domainCodeOf(criterionId, library)}-${surface}-`;
17657
+ const used = new Set(taken);
17658
+ for (let n = 1; n < 1e3; n++) {
17659
+ const candidate = `${prefix}${String(n).padStart(2, "0")}`;
17660
+ if (!used.has(candidate)) return candidate;
17661
+ }
17662
+ throw new Error(`Kritik: exhausted finding ids for ${prefix}NN \u2014 999 findings on one cell is a data problem, not a numbering one`);
17663
+ }
17664
+ function upsertFinding(findings, next) {
17665
+ const index = findings.findIndex((candidate) => candidate.id === next.id);
17666
+ if (index === -1) return { findings: [...findings, next] };
17667
+ const updated = [...findings];
17668
+ const replaced = updated[index];
17669
+ updated[index] = next;
17670
+ return { findings: updated, replaced };
17671
+ }
17672
+ function patchFinding(findings, id, patch) {
17673
+ const index = findings.findIndex((candidate) => candidate.id === id);
17674
+ if (index === -1) return { findings: [...findings] };
17675
+ const updated = [...findings];
17676
+ const previous = updated[index];
17677
+ const finding = { ...previous, ...patch };
17678
+ updated[index] = finding;
17679
+ return { findings: updated, finding, previous };
17680
+ }
17681
+ function resolveFinding(findings, id, resolvedBy) {
17682
+ return patchFinding(findings, id, {
17683
+ status: "resolved",
17684
+ ...resolvedBy !== void 0 ? { resolved_by: resolvedBy } : {}
17685
+ });
17686
+ }
17687
+ function acceptedDetail(detail, note) {
17688
+ return `${detail}
17689
+
17690
+ Accepted risk: ${note}`.trim();
17691
+ }
17692
+ function acceptFinding(findings, id, note) {
17693
+ const existing = findings.find((candidate) => candidate.id === id);
17694
+ const detail = existing === void 0 ? note : acceptedDetail(existing.detail, note);
17695
+ return patchFinding(findings, id, { status: "accepted-risk", detail });
17696
+ }
17697
+ function fillTemplate(text, values) {
17698
+ return text.replace(/\{(\w+)\}/g, (whole, key) => values[key] ?? whole);
17699
+ }
17700
+ function renderIssue(criterion, options) {
17701
+ const { surface, finding, library } = options;
17702
+ const anchors = criterion.level_anchors ?? {};
17703
+ const level = options.level === void 0 || options.level === "" ? "" : String(options.level);
17704
+ const observed = level === "" ? "{observed_level}" : level;
17705
+ const target = options.targetLevel !== void 0 && options.targetLevel !== "" ? String(options.targetLevel) : level === "" ? "{target_level}" : String(Math.min(Number(level) + 1, 4));
17706
+ const values = {
17707
+ surface,
17708
+ observed_level: observed,
17709
+ target_level: target,
17710
+ observed_level_name: anchors[`l${observed}`] ?? "{observed_level_name}",
17711
+ target_level_name: anchors[`l${target}`] ?? "{target_level_name}",
17712
+ target_anchor_text: anchors[`l${target}`] ?? "{target_anchor_text}",
17713
+ impact: String(finding?.impact ?? criterion.default_impact ?? 3)
17714
+ };
17715
+ if (finding !== void 0) {
17716
+ values.likelihood = String(finding.likelihood);
17717
+ values.evidence_bullets_with_file_paths = finding.evidence;
17718
+ values.risk_narrative = finding.detail;
17719
+ if (typeof finding.remediation === "string" && finding.remediation !== "") {
17720
+ values.remediation_step_1 = finding.remediation;
17721
+ }
17722
+ }
17723
+ const issue2 = criterion.issue ?? {};
17724
+ const labels = [.../* @__PURE__ */ new Set([...issue2.labels ?? ["quality"], surface])];
17725
+ const body = fillTemplate(issue2.body_skeleton ?? "", values);
17117
17726
  return {
17118
- loaded: graph.loaded,
17119
- nodes: graph.nodes,
17120
- edges: graph.edges,
17121
- project: graph.project,
17122
- journal: graph.journal
17123
- };
17727
+ title: fillTemplate(issue2.title_template ?? `[Quality] ${criterion.id} on {surface}`, values),
17728
+ labels,
17729
+ body: finding === void 0 ? body : `${body}
17730
+ ${findingFooter(finding, library)}`,
17731
+ ...typeof criterion.remediation === "string" && criterion.remediation !== "" ? { remediation: criterion.remediation } : {}
17732
+ };
17733
+ }
17734
+ function findingFooter(finding, library) {
17735
+ const lines = [
17736
+ ``,
17737
+ `---`,
17738
+ `<sub>Kritik finding \`${finding.id}\` \u2014 **${severityOf(finding, library)} / ${priorityOf(finding, library)}** (impact ${finding.impact} x likelihood ${finding.likelihood}, cost ${finding.cost})</sub>`,
17739
+ ``,
17740
+ `**Evidence**`,
17741
+ finding.evidence
17742
+ ];
17743
+ if (typeof finding.remediation === "string" && finding.remediation !== "") {
17744
+ lines.push(``, `**Remediation**`, finding.remediation);
17745
+ }
17746
+ return lines.join("\n");
17124
17747
  }
17125
- function requireString(args, key) {
17126
- const value = args[key];
17127
- if (typeof value !== "string" || value.length === 0) {
17128
- throw new ToolError(`\`${key}\` is required and must be a non-empty string.`);
17748
+ function signalRunSheet(library, surfaces, filter = {}) {
17749
+ const surfaceIds = surfaces.map((surface) => surface.id).filter((id) => id !== CROSS_SURFACE_ID);
17750
+ const rows = [];
17751
+ for (const criterion of library.criteria ?? []) {
17752
+ if (criterion.superseded_by !== void 0) continue;
17753
+ if (filter.criterion !== void 0 && criterion.id !== filter.criterion) continue;
17754
+ if (filter.domain !== void 0 && criterion.domain !== filter.domain) continue;
17755
+ const signals = criterion.signals ?? [];
17756
+ if (signals.length === 0) continue;
17757
+ const appliesTo = criterion.applies_to;
17758
+ for (const surfaceId of surfaceIds) {
17759
+ if (Array.isArray(appliesTo) && !appliesTo.includes(surfaceId)) continue;
17760
+ if (filter.surface !== void 0 && surfaceId !== filter.surface) continue;
17761
+ signals.forEach((signal, index) => {
17762
+ rows.push({ criterion_id: criterion.id, surface: surfaceId, index, signal });
17763
+ });
17764
+ }
17129
17765
  }
17130
- return value;
17766
+ return rows;
17131
17767
  }
17132
- function normalizeStatusArg(value) {
17133
- const normalized = normalizeStatus(value);
17134
- if (normalized === void 0) {
17135
- throw new ToolError(`"${value}" is not a status (expected one of: ${STATUS_IDS.join(", ")}).`);
17768
+ function auditCompletedInput(matrix, meta3) {
17769
+ const scores = {};
17770
+ for (const surface of matrix.surfaces) {
17771
+ const bySurface = {};
17772
+ for (const domain2 of matrix.domains) {
17773
+ const cell = matrix.matrix[domain2]?.[surface];
17774
+ if (cell) bySurface[domain2] = cell.score;
17775
+ }
17776
+ scores[surface] = bySurface;
17136
17777
  }
17137
- return normalized;
17778
+ return {
17779
+ type: "quality.audit.completed",
17780
+ payload: {
17781
+ audit_id: meta3.audit_id,
17782
+ framework_version: meta3.framework_version,
17783
+ ...meta3.commit !== void 0 ? { commit: meta3.commit } : {},
17784
+ scores,
17785
+ counts: matrix.finding_counts
17786
+ }
17787
+ };
17138
17788
  }
17139
- function findNode(nodes, nodeId) {
17140
- const node = nodes.find((candidate) => candidate.id === nodeId);
17141
- if (!node) throw new ToolError(`No node with id "${nodeId}".`);
17142
- return node;
17789
+ function findingOpenedInput(finding, library) {
17790
+ return {
17791
+ type: "quality.finding.opened",
17792
+ payload: {
17793
+ finding_id: finding.id,
17794
+ criterion_id: finding.criterion_id,
17795
+ surface: finding.surface,
17796
+ severity: severityOf(finding, library),
17797
+ priority: priorityOf(finding, library),
17798
+ title: finding.title,
17799
+ ...finding.node_ids !== void 0 ? { node_ids: finding.node_ids } : {},
17800
+ ...finding.issue_url !== void 0 ? { issue_url: finding.issue_url } : {}
17801
+ }
17802
+ };
17143
17803
  }
17144
- function nodeSummary(node) {
17145
- const base = { id: node.id, title: node.title, species: node.species, status: node.status, platforms: node.platforms };
17146
- if (node.species !== "acceptance") return base;
17147
- const platform_statuses = Object.fromEntries(
17148
- node.platforms.map((platform) => [platform, resolvePlatformStatus(node, platform)])
17149
- );
17150
- return { ...base, platform_statuses, values: node.metadata?.values ?? [] };
17804
+ function findingResolvedInput(finding, resolvedBy) {
17805
+ return {
17806
+ type: "quality.finding.resolved",
17807
+ payload: {
17808
+ finding_id: finding.id,
17809
+ ...resolvedBy !== void 0 ? { resolved_by: resolvedBy } : {},
17810
+ ...finding.node_ids !== void 0 ? { node_ids: finding.node_ids } : {}
17811
+ }
17812
+ };
17151
17813
  }
17152
- function unwrap(result) {
17153
- if (!result.ok) {
17154
- throw new ToolError("Mutation refused by validateBundle \u2014 nothing was written.", {
17155
- findings: result.errors,
17156
- warnings: result.warnings
17814
+ function signalTrippedInput(trip) {
17815
+ return {
17816
+ type: "quality.signal.tripped",
17817
+ payload: {
17818
+ criterion_id: trip.criterion_id,
17819
+ surface: trip.surface,
17820
+ signal: trip.signal,
17821
+ ...trip.detail !== void 0 ? { detail: trip.detail } : {}
17822
+ }
17823
+ };
17824
+ }
17825
+
17826
+ // ../schema/src/quality-regressions.ts
17827
+ var REGRESSION_SIGNALS = {
17828
+ "level-drop": "maturity on this cell does not regress",
17829
+ "new-severe-finding": "no open Critical or High finding on this cell",
17830
+ "reopened-finding": "a resolved finding stays resolved"
17831
+ };
17832
+ var cellKey = (criterionId, surface) => `${criterionId}::${surface}`;
17833
+ var rowsOf = (value) => Array.isArray(value) ? value : [];
17834
+ function assessmentsByCell(state) {
17835
+ const cells = /* @__PURE__ */ new Map();
17836
+ for (const assessment of rowsOf(state?.assessments)) {
17837
+ if (typeof assessment?.criterion_id !== "string" || typeof assessment?.surface !== "string") continue;
17838
+ cells.set(cellKey(assessment.criterion_id, assessment.surface), assessment);
17839
+ }
17840
+ return cells;
17841
+ }
17842
+ function severeByCell(state, library) {
17843
+ const cells = /* @__PURE__ */ new Map();
17844
+ for (const finding of rowsOf(state?.findings)) {
17845
+ if (typeof finding?.criterion_id !== "string" || typeof finding?.surface !== "string") continue;
17846
+ if (!isOpenFinding(finding)) continue;
17847
+ const severity = severityOf(finding, library);
17848
+ if (severity !== "critical" && severity !== "high") continue;
17849
+ const key = cellKey(finding.criterion_id, finding.surface);
17850
+ const existing = cells.get(key);
17851
+ if (existing === void 0) cells.set(key, [finding]);
17852
+ else existing.push(finding);
17853
+ }
17854
+ return cells;
17855
+ }
17856
+ function detectRegressions(previous, next, library) {
17857
+ const before = assessmentsByCell(previous);
17858
+ const after = assessmentsByCell(next);
17859
+ const comparable = (key) => before.has(key) && after.has(key);
17860
+ const regressions = [];
17861
+ for (const [key, current] of after) {
17862
+ const earlier = before.get(key);
17863
+ if (earlier === void 0) continue;
17864
+ if (!(Number(current.level) < Number(earlier.level))) continue;
17865
+ regressions.push({
17866
+ kind: "level-drop",
17867
+ criterion_id: current.criterion_id,
17868
+ surface: current.surface,
17869
+ signal: REGRESSION_SIGNALS["level-drop"],
17870
+ detail: `level ${earlier.level} \u2192 ${current.level} (${earlier.audit_id} \u2192 ${current.audit_id})`
17157
17871
  });
17158
17872
  }
17159
- return { warnings: result.warnings, events: result.events };
17873
+ const severeBefore = severeByCell(previous, library);
17874
+ for (const [key, findings] of severeByCell(next, library)) {
17875
+ if (!comparable(key)) continue;
17876
+ if ((severeBefore.get(key) ?? []).length > 0) continue;
17877
+ for (const finding of findings) {
17878
+ regressions.push({
17879
+ kind: "new-severe-finding",
17880
+ criterion_id: finding.criterion_id,
17881
+ surface: finding.surface,
17882
+ signal: REGRESSION_SIGNALS["new-severe-finding"],
17883
+ detail: `${finding.id} \u2014 ${severityOf(finding, library)} (impact ${finding.impact} \xD7 likelihood ${finding.likelihood})`
17884
+ });
17885
+ }
17886
+ }
17887
+ const resolvedBefore = new Set(
17888
+ rowsOf(previous?.findings).filter((finding) => finding?.status === "resolved").map((finding) => finding.id)
17889
+ );
17890
+ for (const finding of rowsOf(next?.findings)) {
17891
+ if (!isOpenFinding(finding) || !resolvedBefore.has(finding.id)) continue;
17892
+ regressions.push({
17893
+ kind: "reopened-finding",
17894
+ criterion_id: finding.criterion_id,
17895
+ surface: finding.surface,
17896
+ signal: REGRESSION_SIGNALS["reopened-finding"],
17897
+ detail: `${finding.id} \u2014 "${finding.title}"`
17898
+ });
17899
+ }
17900
+ return regressions;
17160
17901
  }
17161
- var UPDATABLE_NODE_FIELDS = /* @__PURE__ */ new Set(["title", "description", "status", "platforms", "metadata"]);
17162
- function mutate(graph, ops) {
17902
+
17903
+ // ../schema/src/cli/kritik-audit.ts
17904
+ import { existsSync as existsSync2, readdirSync, statSync } from "node:fs";
17905
+ import { join as join2 } from "node:path";
17906
+
17907
+ // ../schema/src/cli/kritik-paths.ts
17908
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
17909
+ import { dirname, join, resolve } from "node:path";
17910
+ var QUALITY_DIR = "docs/quality";
17911
+ var PROFILE_FILE = "profile.json";
17912
+ var OVERLAY_FILE = "criteria.custom.json";
17913
+ var AUDITS_DIR = "audits";
17914
+ var PACK_FILE = "library.json";
17915
+ function readJson(path) {
17916
+ const text = readFileSync(path, "utf8");
17163
17917
  try {
17164
- return applyOps({ projectId: graph.project.id, nodes: graph.nodes, edges: graph.edges }, ops);
17165
- } catch (err) {
17166
- if (err instanceof MutationError) throw new ToolError(err.message);
17167
- throw err;
17918
+ return JSON.parse(text);
17919
+ } catch (e) {
17920
+ throw new Error(`${path}: not valid JSON \u2014 ${e.message}`);
17168
17921
  }
17169
17922
  }
17170
- function listReleases(journal, nodesById) {
17171
- const latestByVersion = /* @__PURE__ */ new Map();
17172
- for (const event of orderEvents(journal)) {
17173
- if (event.type !== "release.tagged") continue;
17174
- const tag = event;
17175
- latestByVersion.set(tag.version, tag);
17923
+ function writeJson(path, value) {
17924
+ mkdirSync(dirname(path), { recursive: true });
17925
+ writeFileSync(path, JSON.stringify(value, null, 2) + "\n");
17926
+ }
17927
+ var profilePath = (root) => join(root, QUALITY_DIR, PROFILE_FILE);
17928
+ var overlayPath = (root) => join(root, QUALITY_DIR, OVERLAY_FILE);
17929
+ var auditsDir = (root) => join(root, QUALITY_DIR, AUDITS_DIR);
17930
+ var auditDir = (root, auditId) => join(auditsDir(root), auditId);
17931
+ function loadProfile(root) {
17932
+ const path = profilePath(root);
17933
+ return existsSync(path) ? readJson(path) : null;
17934
+ }
17935
+ function loadOverlay(root) {
17936
+ const path = overlayPath(root);
17937
+ return existsSync(path) ? readJson(path) : null;
17938
+ }
17939
+
17940
+ // ../schema/src/cli/kritik-audit.ts
17941
+ var SCORES_FILE = "scores.json";
17942
+ var FINDINGS_FILE = "findings.json";
17943
+ var MATRIX_FILE = "matrix.json";
17944
+ var scoresPath = (root, auditId) => join2(auditDir(root, auditId), SCORES_FILE);
17945
+ var findingsPath = (root, auditId) => join2(auditDir(root, auditId), FINDINGS_FILE);
17946
+ var matrixPath = (root, auditId) => join2(auditDir(root, auditId), MATRIX_FILE);
17947
+ function listAuditIds(root) {
17948
+ const dir = auditsDir(root);
17949
+ if (!existsSync2(dir)) return [];
17950
+ return readdirSync(dir).filter((name) => statSync(join2(dir, name)).isDirectory()).sort();
17951
+ }
17952
+ function newestAuditId(root) {
17953
+ const dir = auditsDir(root);
17954
+ if (!existsSync2(dir)) throw new Error(`no audits directory at ${dir}`);
17955
+ const ids = listAuditIds(root);
17956
+ if (ids.length === 0) throw new Error(`no audits found under ${dir}`);
17957
+ return ids[ids.length - 1];
17958
+ }
17959
+ function loadScores(root, auditId) {
17960
+ const path = scoresPath(root, auditId);
17961
+ if (!existsSync2(path)) throw new Error(`no ${SCORES_FILE} at ${path}`);
17962
+ const file2 = readJson(path);
17963
+ return { ...file2, assessments: Array.isArray(file2.assessments) ? file2.assessments : [] };
17964
+ }
17965
+ function loadScoresOrEmpty(root, auditId) {
17966
+ return existsSync2(scoresPath(root, auditId)) ? loadScores(root, auditId) : { audit_id: auditId, assessments: [] };
17967
+ }
17968
+ function loadFindings(root, auditId) {
17969
+ const path = findingsPath(root, auditId);
17970
+ if (!existsSync2(path)) return { audit_id: auditId, findings: [] };
17971
+ const file2 = readJson(path);
17972
+ return { ...file2, findings: Array.isArray(file2.findings) ? file2.findings : [] };
17973
+ }
17974
+ function saveScores(root, auditId, file2) {
17975
+ writeJson(scoresPath(root, auditId), file2);
17976
+ }
17977
+ function saveFindings(root, auditId, file2) {
17978
+ writeJson(findingsPath(root, auditId), file2);
17979
+ }
17980
+ function requireProfile(root) {
17981
+ const profile = loadProfile(root);
17982
+ if (!profile) {
17983
+ throw new Error(
17984
+ `no profile at ${join2(root, QUALITY_DIR, "profile.json")} \u2014 pick this project's surfaces first (\`arkaik kritik profile\`, or the plugin's init-profile.js).`
17985
+ );
17176
17986
  }
17177
- return [...latestByVersion.values()].sort((a, b) => a.ts === b.ts ? a.id < b.id ? 1 : -1 : a.ts < b.ts ? 1 : -1).map((tag) => ({
17178
- version: tag.version,
17179
- ts: tag.ts,
17180
- ...tag.platform !== void 0 ? { platform: tag.platform } : {},
17181
- ...tag.notes !== void 0 ? { notes: tag.notes } : {},
17182
- eventCount: computeChangelog(journal, tag.version, { nodesById }).events.length
17183
- }));
17987
+ return profile;
17184
17988
  }
17185
- function buildCatalog(ctx) {
17186
- const tools2 = [];
17187
- const handlers2 = {};
17188
- const tool = (definition, handler) => {
17189
- tools2.push(definition);
17190
- handlers2[definition.name] = handler;
17989
+ function loadQualitySection(root, auditId, library, scores = loadScores(root, auditId)) {
17990
+ const findings = loadFindings(root, auditId);
17991
+ return {
17992
+ framework_version: scores.framework_version ?? library.version,
17993
+ profile: requireProfile(root),
17994
+ assessments: scores.assessments,
17995
+ findings: findings.findings
17191
17996
  };
17192
- tool(
17193
- {
17194
- name: "list_nodes",
17195
- description: "List nodes in the product graph, filtered by species, status, platform, value element, covers-anchor, parity gap, and/or a case-insensitive title/description substring. Returns summaries (acceptances include platform_statuses + values).",
17196
- inputSchema: {
17197
- type: "object",
17198
- properties: {
17199
- species: { type: "string", enum: [...SPECIES_IDS] },
17200
- status: { type: "string", enum: [...STATUS_IDS] },
17201
- platform: { type: "string", enum: [...PLATFORM_IDS] },
17202
- value: {
17203
- type: "string",
17204
- enum: [...VALUE_IDS],
17205
- description: "Only acceptances tagged with this value element."
17206
- },
17207
- anchor: {
17208
- type: "string",
17209
- description: "Node id \u2014 only acceptances covering it via a covers edge."
17210
- },
17211
- parity_gap: {
17212
- type: "boolean",
17213
- description: "Only acceptances delivered (live) on \u22651 applicable platform but not all."
17214
- },
17215
- query: { type: "string", description: "Case-insensitive substring over title + description." },
17216
- limit: { type: "integer", minimum: 1, description: "Default 50." }
17217
- },
17218
- additionalProperties: false
17219
- }
17220
- },
17221
- async (args) => {
17222
- const { nodes, edges } = await load(ctx);
17223
- const query = typeof args.query === "string" ? args.query.toLowerCase() : void 0;
17224
- const limit = typeof args.limit === "number" && args.limit >= 1 ? Math.floor(args.limit) : 50;
17225
- const status = typeof args.status === "string" ? normalizeStatusArg(args.status) : void 0;
17226
- const anchorCoveringIds = typeof args.anchor === "string" ? new Set(acceptancesCovering(args.anchor, nodes, edges).map((node) => node.id)) : void 0;
17227
- const matches = nodes.filter((node) => {
17228
- if (typeof args.species === "string" && node.species !== args.species) return false;
17229
- if (status !== void 0 && node.status !== status) return false;
17230
- if (typeof args.platform === "string" && !node.platforms.includes(args.platform))
17231
- return false;
17232
- if (typeof args.value === "string" && (node.species !== "acceptance" || !(node.metadata?.values ?? []).includes(args.value))) return false;
17233
- if (anchorCoveringIds !== void 0 && !anchorCoveringIds.has(node.id)) return false;
17234
- if (args.parity_gap === true && (node.species !== "acceptance" || !hasParityGap(node))) return false;
17235
- if (query !== void 0) {
17236
- const haystack = `${node.title}
17237
- ${node.description ?? ""}`.toLowerCase();
17238
- if (!haystack.includes(query)) return false;
17997
+ }
17998
+ function computeAuditMatrix(root, auditId, library) {
17999
+ const scores = loadScores(root, auditId);
18000
+ const section = loadQualitySection(root, auditId, library, scores);
18001
+ const matrix = deriveQualityMatrix({ quality: section }, library);
18002
+ const file2 = {
18003
+ audit_id: auditId,
18004
+ commit: scores.commit,
18005
+ framework_version: section.framework_version,
18006
+ matrix: matrix.matrix,
18007
+ overall: matrix.overall,
18008
+ finding_counts: matrix.finding_counts
18009
+ };
18010
+ writeJson(matrixPath(root, auditId), file2);
18011
+ return { section, matrix, file: file2 };
18012
+ }
18013
+ function locateFinding(root, id) {
18014
+ for (const auditId of [...listAuditIds(root)].reverse()) {
18015
+ const file2 = loadFindings(root, auditId);
18016
+ const finding = file2.findings.find((candidate) => candidate.id === id);
18017
+ if (finding) return { auditId, file: file2, finding };
18018
+ }
18019
+ return void 0;
18020
+ }
18021
+
18022
+ // ../cli/src/lib/bundle-io.ts
18023
+ import { existsSync as existsSync3, readFileSync as readFileSync2 } from "node:fs";
18024
+ function readBundle(filePath) {
18025
+ if (!existsSync3(filePath)) throw new Error(`File not found: ${filePath}`);
18026
+ let parsed;
18027
+ try {
18028
+ parsed = JSON.parse(readFileSync2(filePath, "utf8"));
18029
+ } catch (e) {
18030
+ throw new Error(`Cannot parse JSON \u2014 ${e.message}`);
18031
+ }
18032
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
18033
+ throw new Error("Bundle must be a JSON object.");
18034
+ }
18035
+ const record2 = parsed;
18036
+ if (!Array.isArray(record2.nodes)) return record2;
18037
+ return migrateStatusVocabulary(record2);
18038
+ }
18039
+
18040
+ // ../cli/src/lib/journal-io.ts
18041
+ import { appendFileSync, existsSync as existsSync4, mkdirSync as mkdirSync2, readdirSync as readdirSync2, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "node:fs";
18042
+ import { dirname as dirname2, join as join3 } from "node:path";
18043
+ var JOURNAL_SIDECAR = "journal.jsonl";
18044
+ function journalPathFor(bundlePath) {
18045
+ return join3(dirname2(bundlePath), JOURNAL_SIDECAR);
18046
+ }
18047
+ function archivePathsFor(journalPath) {
18048
+ const dir = join3(dirname2(journalPath), "journal");
18049
+ if (!existsSync4(dir)) return [];
18050
+ return readdirSync2(dir).filter((name) => name.startsWith("archive-") && name.endsWith(".jsonl")).sort().map((name) => join3(dir, name));
18051
+ }
18052
+ function readJournalEvents(journalPath) {
18053
+ if (!existsSync4(journalPath)) return [];
18054
+ return parseJournalLines(readFileSync3(journalPath, "utf8")).events;
18055
+ }
18056
+ function readFullJournalEvents(journalPath) {
18057
+ const events = readJournalEvents(journalPath);
18058
+ for (const archivePath of archivePathsFor(journalPath)) {
18059
+ events.push(...readJournalEvents(archivePath));
18060
+ }
18061
+ return events;
18062
+ }
18063
+ function toLine(event) {
18064
+ return JSON.stringify(event) + "\n";
18065
+ }
18066
+ function appendJournalEvent(journalPath, event) {
18067
+ const line = toLine(event);
18068
+ if (!existsSync4(journalPath)) {
18069
+ mkdirSync2(dirname2(journalPath), { recursive: true });
18070
+ writeFileSync2(journalPath, line);
18071
+ return;
18072
+ }
18073
+ const existing = readFileSync3(journalPath, "utf8");
18074
+ const prefix = existing.length > 0 && !existing.endsWith("\n") ? "\n" : "";
18075
+ appendFileSync(journalPath, prefix + line);
18076
+ }
18077
+
18078
+ // ../cli/src/lib/kritik-io.ts
18079
+ import { existsSync as existsSync5 } from "node:fs";
18080
+ import { basename, dirname as dirname3, join as join4, resolve as resolve2 } from "node:path";
18081
+ import { fileURLToPath } from "node:url";
18082
+ var DEFAULT_BUNDLE_PATH = join4("docs", "arkaik", "bundle.json");
18083
+ var VENDORED_PACK = join4(QUALITY_DIR, PACK_FILE);
18084
+ var BUNDLED_PACK = join4(dirname3(fileURLToPath(import.meta.url)), "assets", "kritik", "library.json");
18085
+ function resolvePack(root) {
18086
+ const vendored = join4(root, VENDORED_PACK);
18087
+ if (existsSync5(vendored)) return { library: readJson(vendored), path: vendored, vendored: true };
18088
+ if (!existsSync5(BUNDLED_PACK)) {
18089
+ throw new Error(
18090
+ `no criteria pack found. Looked in:
18091
+ ${vendored}
18092
+ ${BUNDLED_PACK}
18093
+ The second is shipped with this CLI, so its absence means a broken install \u2014 reinstall \`arkaik\`.`
18094
+ );
18095
+ }
18096
+ return { library: readJson(BUNDLED_PACK), path: BUNDLED_PACK, vendored: false };
18097
+ }
18098
+ function loadKritikLibrary(root) {
18099
+ const pack = resolvePack(root);
18100
+ return { library: mergeKritikLibrary(pack.library, loadOverlay(root)), pack };
18101
+ }
18102
+ function resolveJournal(root, bundlePath) {
18103
+ const resolved = bundlePath ?? join4(root, DEFAULT_BUNDLE_PATH);
18104
+ return { bundlePath: resolved, journalPath: journalPathFor(resolved), present: existsSync5(resolved) };
18105
+ }
18106
+ function resolveQualityRoot(options) {
18107
+ if (options.root !== void 0) return resolve2(options.fallback, options.root);
18108
+ const envRoot = (options.env ?? process.env).ARKAIK_QUALITY_ROOT;
18109
+ if (envRoot) return resolve2(envRoot);
18110
+ const dir = dirname3(options.bundlePath);
18111
+ if (basename(dir) === "arkaik" && basename(dirname3(dir)) === "docs") return resolve2(dir, "..", "..");
18112
+ return options.fallback;
18113
+ }
18114
+
18115
+ // ../cli/src/lib/bundle-validate.ts
18116
+ import { existsSync as existsSync6, readFileSync as readFileSync4 } from "node:fs";
18117
+ import { basename as basename2 } from "node:path";
18118
+ function validateBundleAt(filePath) {
18119
+ const bundle = readBundle(filePath);
18120
+ const loose = bundle;
18121
+ if (!loose.project || !loose.nodes || !loose.edges) {
18122
+ throw new Error("Missing top-level keys (project, nodes, edges).");
18123
+ }
18124
+ let sidecarFindings = [];
18125
+ let sidecarLoaded = false;
18126
+ const archiveFindings = [];
18127
+ const archivesLoaded = [];
18128
+ if (loose.journal === void 0) {
18129
+ const sidecarPath = journalPathFor(filePath);
18130
+ const folded = [];
18131
+ if (existsSync6(sidecarPath)) {
18132
+ const { events, findings } = parseJournalLines(readFileSync4(sidecarPath, "utf8"));
18133
+ sidecarFindings = findings;
18134
+ sidecarLoaded = true;
18135
+ folded.push(...events);
18136
+ }
18137
+ for (const archivePath of archivePathsFor(sidecarPath)) {
18138
+ const { events, findings } = parseJournalLines(readFileSync4(archivePath, "utf8"));
18139
+ const file2 = basename2(archivePath);
18140
+ for (const finding of findings) archiveFindings.push({ ...finding, file: file2 });
18141
+ archivesLoaded.push(file2);
18142
+ folded.push(...events);
18143
+ }
18144
+ if (sidecarLoaded || archivesLoaded.length > 0) loose.journal = folded;
18145
+ }
18146
+ const nodes = Array.isArray(loose.nodes) ? loose.nodes : [];
18147
+ const edges = Array.isArray(loose.edges) ? loose.edges : [];
18148
+ const journal = Array.isArray(loose.journal) ? loose.journal : [];
18149
+ const result = validateBundle(bundle);
18150
+ const valid = sidecarFindings.length === 0 && archiveFindings.length === 0 && result.errors.length === 0;
18151
+ return {
18152
+ bundle,
18153
+ nodes,
18154
+ edges,
18155
+ journal,
18156
+ sidecarLoaded,
18157
+ sidecarFindings,
18158
+ archivesLoaded,
18159
+ archiveFindings,
18160
+ result,
18161
+ valid
18162
+ };
18163
+ }
18164
+
18165
+ // src/kritik-tools.ts
18166
+ function repoRootOf(ctx, needs) {
18167
+ if (ctx.qualityRoot === void 0) {
18168
+ throw new ToolError(
18169
+ `${needs} This session is connected to a hosted project (${ctx.store.describe()}); run it where the checkout is \u2014 \`arkaik-mcp --bundle <path>\`.`
18170
+ );
18171
+ }
18172
+ return ctx.qualityRoot;
18173
+ }
18174
+ var REPO_MODE_ONLY = "Repo-mode reads come from docs/quality/ files.";
18175
+ async function appendHosted(store2, inputs) {
18176
+ if (store2.appendQualityEvents === void 0) {
18177
+ throw new ToolError(`${store2.describe()} cannot append quality events.`);
18178
+ }
18179
+ try {
18180
+ return await store2.appendQualityEvents(inputs);
18181
+ } catch (error51) {
18182
+ throw new ToolError(error51.message);
18183
+ }
18184
+ }
18185
+ function hostedSection(graph) {
18186
+ const section = graph.loaded.bundle.quality;
18187
+ if (section === void 0 || !Array.isArray(section.findings) || !Array.isArray(section.assessments)) {
18188
+ throw new ToolError(
18189
+ "This hosted project has no quality section yet. Run an audit in the repository and `arkaik restore` it \u2014 hosted Kritik reads what an audit stored."
18190
+ );
18191
+ }
18192
+ return { section, library: resolveKritikLibrary(section) };
18193
+ }
18194
+ function refuseHostedRecord(eventType) {
18195
+ throw new ToolError(`Recording ${eventType} belongs to the audit run, which reads code. Run the audit where the checkout is.`);
18196
+ }
18197
+ function openFindingsSummary(findings, library) {
18198
+ const open = findings.filter(isOpenFinding);
18199
+ const lanes = { P0: 0, P1: 0, P2: 0, P3: 0 };
18200
+ for (const finding of open) lanes[priorityOf(finding, library)]++;
18201
+ const p0 = open.filter((finding) => priorityOf(finding, library) === "P0").map((finding) => ({
18202
+ id: finding.id,
18203
+ surface: finding.surface,
18204
+ criterion_id: finding.criterion_id,
18205
+ title: finding.title,
18206
+ severity: severityOf(finding, library)
18207
+ }));
18208
+ return { open, lanes, p0 };
18209
+ }
18210
+ function resolveAuditPair(audits, args, notFoundHint) {
18211
+ if (audits.length < 2) {
18212
+ throw new ToolError(
18213
+ `regressions needs two audits to compare \u2014 ${audits.length === 0 ? `${notFoundHint} holds none` : `only "${audits[0]}" exists`}. A regression is the difference between two readings; one reading is a baseline.`
18214
+ );
18215
+ }
18216
+ const known = (id) => {
18217
+ if (!audits.includes(id)) throw new ToolError(`no audit "${id}" ${notFoundHint} (have: ${audits.join(", ")})`);
18218
+ return id;
18219
+ };
18220
+ const to = typeof args.to === "string" && args.to !== "" ? known(args.to) : audits[audits.length - 1];
18221
+ const from = typeof args.from === "string" && args.from !== "" ? known(args.from) : audits[audits.indexOf(to) - 1];
18222
+ if (from === void 0) throw new ToolError(`"${to}" is the oldest audit \u2014 there is nothing before it to compare against.`);
18223
+ if (from === to) throw new ToolError(`from and to name the same audit ("${to}") \u2014 a regression needs two readings.`);
18224
+ if (audits.indexOf(from) > audits.indexOf(to)) {
18225
+ throw new ToolError(`from "${from}" is newer than to "${to}" \u2014 swap them, or the comparison inverts.`);
18226
+ }
18227
+ return { from, to };
18228
+ }
18229
+ function matchesFindingArgs(row, args) {
18230
+ if (typeof args.surface === "string" && row.surface !== args.surface) return false;
18231
+ if (typeof args.status === "string" && (row.status ?? "open") !== args.status) return false;
18232
+ if (typeof args.priority === "string" && row.priority !== args.priority) return false;
18233
+ if (typeof args.criterion_id === "string" && row.criterion_id !== args.criterion_id) return false;
18234
+ if (typeof args.finding_id === "string" && row.id !== args.finding_id) return false;
18235
+ return true;
18236
+ }
18237
+ function libraryOf(root) {
18238
+ try {
18239
+ return loadKritikLibrary(root).library;
18240
+ } catch (error51) {
18241
+ throw new ToolError(error51.message);
18242
+ }
18243
+ }
18244
+ function profileOf(root) {
18245
+ try {
18246
+ return requireProfile(root);
18247
+ } catch (error51) {
18248
+ throw new ToolError(error51.message);
18249
+ }
18250
+ }
18251
+ function criterionOf(library, criterionId) {
18252
+ const criterion = (library.criteria ?? []).find((candidate) => candidate.id === criterionId);
18253
+ if (!criterion) {
18254
+ const domain2 = criterionId.split("-")[0];
18255
+ const siblings = (library.criteria ?? []).filter((c) => c.domain === domain2).map((c) => c.id);
18256
+ throw new ToolError(
18257
+ `No criterion "${criterionId}" in the pack or this project's overlay.` + (siblings.length > 0 ? ` Criteria in ${domain2}: ${siblings.join(", ")}.` : ` Domains: ${(library.domains ?? []).map((d) => d.code).join(", ")}.`)
18258
+ );
18259
+ }
18260
+ if (typeof criterion.superseded_by === "string") {
18261
+ throw new ToolError(
18262
+ `Criterion "${criterionId}" is retired \u2014 superseded by "${criterion.superseded_by}". Score that one instead; the old id is kept only so past audits still mean what they meant.`
18263
+ );
18264
+ }
18265
+ return criterion;
18266
+ }
18267
+ function surfaceOf(profile, surface, allowCrossSurface = false) {
18268
+ if (surface === CROSS_SURFACE_ID) {
18269
+ if (allowCrossSurface) return surface;
18270
+ throw new ToolError(
18271
+ `"${CROSS_SURFACE_ID}" is a findings-only lens \u2014 it carries no matrix column, so a score there would render nowhere.`
18272
+ );
18273
+ }
18274
+ const declared2 = (profile.surfaces ?? []).map((candidate) => candidate.id);
18275
+ if (!declared2.includes(surface)) {
18276
+ throw new ToolError(`Surface "${surface}" is not declared in this project's profile. Declared: ${declared2.join(", ")}.`);
18277
+ }
18278
+ return surface;
18279
+ }
18280
+ function requireString(args, key) {
18281
+ const value = args[key];
18282
+ if (typeof value !== "string" || value.length === 0) {
18283
+ throw new ToolError(`\`${key}\` is required and must be a non-empty string.`);
18284
+ }
18285
+ return value;
18286
+ }
18287
+ function requireInt(args, key, min, max) {
18288
+ const value = args[key];
18289
+ if (typeof value !== "number" || !Number.isInteger(value) || value < min || value > max) {
18290
+ throw new ToolError(`\`${key}\` is required and must be an integer ${min}-${max}.`);
18291
+ }
18292
+ return value;
18293
+ }
18294
+ function currentAuditId() {
18295
+ const now = /* @__PURE__ */ new Date();
18296
+ return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}`;
18297
+ }
18298
+ function auditForWrite(root, requested) {
18299
+ if (typeof requested === "string" && requested !== "") return requested;
18300
+ const existing = listAuditIds(root);
18301
+ return existing.length > 0 ? existing[existing.length - 1] : currentAuditId();
18302
+ }
18303
+ function buildKritikCatalog(ctx) {
18304
+ const tools2 = [];
18305
+ const handlers2 = {};
18306
+ const tool = (definition, handler) => {
18307
+ tools2.push(definition);
18308
+ handlers2[definition.name] = handler;
18309
+ };
18310
+ const record2 = async (graph, inputs) => {
18311
+ if (inputs.length === 0) return [];
18312
+ const result = await ctx.store.persist(graph, {}, inputs);
18313
+ if (!result.ok) {
18314
+ throw new ToolError("Quality event refused by validateBundle \u2014 nothing was written.", {
18315
+ findings: result.errors,
18316
+ warnings: result.warnings
18317
+ });
18318
+ }
18319
+ return result.events;
18320
+ };
18321
+ const load2 = async () => {
18322
+ try {
18323
+ return await ctx.store.load();
18324
+ } catch (error51) {
18325
+ throw new ToolError(`Cannot load ${ctx.store.describe()}: ${error51.message}`);
18326
+ }
18327
+ };
18328
+ tool(
18329
+ {
18330
+ name: "kritik_matrix",
18331
+ description: "The comparative quality matrix: a score and grade per (domain x surface), the weighted roll-up per surface, and open findings by priority lane. Anti-averaging caps are applied \u2014 one open Critical caps its cell at D, one open High at B \u2014 so a cell full of 3s cannot absorb a live defect. In repo mode this refreshes the audit's matrix.json, and with record=true appends quality.audit.completed; in hosted mode it is a read of the stored quality section (no audit_id/commit \u2014 hosted has no audit file) and record is refused \u2014 recording belongs to the audit run, which reads code.",
18332
+ inputSchema: {
18333
+ type: "object",
18334
+ properties: {
18335
+ audit_id: { type: "string", description: "Default: the newest audit on disk." },
18336
+ record: {
18337
+ type: "boolean",
18338
+ description: "Append quality.audit.completed carrying these scores and counts. Once per finished audit."
18339
+ }
18340
+ },
18341
+ additionalProperties: false
18342
+ }
18343
+ },
18344
+ async (args) => {
18345
+ const hosted = ctx.qualityRoot === void 0;
18346
+ if (hosted) {
18347
+ if (args.record === true) refuseHostedRecord("quality.audit.completed");
18348
+ if (typeof args.audit_id === "string" && args.audit_id !== "") {
18349
+ throw new ToolError("The hosted matrix is the current state, not one audit \u2014 audit_id does not partition it (issue #400 decision 3).");
18350
+ }
18351
+ const graph = await load2();
18352
+ const { section: section2, library: library2 } = hostedSection(graph);
18353
+ const m = deriveQualityMatrix({ quality: section2 }, library2);
18354
+ const { open: open2, lanes: lanes2, p0: p02 } = openFindingsSummary(section2.findings, library2);
18355
+ return {
18356
+ ...m.framework_version !== void 0 ? { framework_version: m.framework_version } : {},
18357
+ matrix: m.matrix,
18358
+ overall: m.overall,
18359
+ finding_counts: m.finding_counts,
18360
+ assessment_count: section2.assessments.length,
18361
+ open_findings: open2.length,
18362
+ lanes: lanes2,
18363
+ p0: p02,
18364
+ events: []
18365
+ };
18366
+ }
18367
+ const root = repoRootOf(ctx, REPO_MODE_ONLY);
18368
+ const library = libraryOf(root);
18369
+ let auditId;
18370
+ try {
18371
+ auditId = typeof args.audit_id === "string" && args.audit_id !== "" ? args.audit_id : newestAuditId(root);
18372
+ } catch (error51) {
18373
+ throw new ToolError(error51.message);
18374
+ }
18375
+ let computed;
18376
+ try {
18377
+ computed = computeAuditMatrix(root, auditId, library);
18378
+ } catch (error51) {
18379
+ throw new ToolError(error51.message);
18380
+ }
18381
+ const { section, matrix, file: file2 } = computed;
18382
+ const { open, lanes, p0 } = openFindingsSummary(section.findings, library);
18383
+ let events = [];
18384
+ if (args.record === true) {
18385
+ const graph = await load2();
18386
+ events = await record2(graph, [
18387
+ auditCompletedInput(matrix, {
18388
+ audit_id: auditId,
18389
+ framework_version: file2.framework_version,
18390
+ ...file2.commit !== void 0 ? { commit: file2.commit } : {}
18391
+ })
18392
+ ]);
18393
+ }
18394
+ return {
18395
+ ...file2,
18396
+ assessment_count: section.assessments.length,
18397
+ open_findings: open.length,
18398
+ lanes,
18399
+ p0,
18400
+ events
18401
+ };
18402
+ }
18403
+ );
18404
+ tool(
18405
+ {
18406
+ name: "kritik_findings",
18407
+ description: "Findings, with their derived severity and priority. Filter by surface, status, priority, criterion, or finding id. Severity and priority are computed from impact x likelihood and cost on every read \u2014 they are never stored, so they cannot drift from the numbers behind them. Repo mode reads across every audit under docs/quality/audits/, filterable by audit_id; hosted findings are a single living pool with no audit_id partition.",
18408
+ inputSchema: {
18409
+ type: "object",
18410
+ properties: {
18411
+ surface: { type: "string" },
18412
+ status: { type: "string", enum: [...FINDING_STATUSES] },
18413
+ priority: { type: "string", enum: ["P0", "P1", "P2", "P3"] },
18414
+ criterion_id: { type: "string" },
18415
+ finding_id: { type: "string" },
18416
+ audit_id: { type: "string", description: "Default: every audit. Not valid in hosted mode." }
18417
+ },
18418
+ additionalProperties: false
18419
+ }
18420
+ },
18421
+ async (args) => {
18422
+ const hosted = ctx.qualityRoot === void 0;
18423
+ if (hosted) {
18424
+ if (typeof args.audit_id === "string" && args.audit_id !== "") {
18425
+ throw new ToolError("Hosted findings are a living pool \u2014 audit_id does not partition them (issue #400 decision 3).");
18426
+ }
18427
+ const graph = await load2();
18428
+ const { section, library: library2 } = hostedSection(graph);
18429
+ const rows2 = section.findings.map((finding) => ({
18430
+ ...finding,
18431
+ severity: severityOf(finding, library2),
18432
+ priority: priorityOf(finding, library2)
18433
+ }));
18434
+ const matches2 = rows2.filter((row) => matchesFindingArgs(row, args));
18435
+ return { total: matches2.length, findings: matches2 };
18436
+ }
18437
+ const root = repoRootOf(ctx, REPO_MODE_ONLY);
18438
+ const library = libraryOf(root);
18439
+ const auditIds = typeof args.audit_id === "string" && args.audit_id !== "" ? [args.audit_id] : listAuditIds(root);
18440
+ const rows = auditIds.flatMap(
18441
+ (auditId) => loadFindings(root, auditId).findings.map((finding) => ({
18442
+ ...finding,
18443
+ audit_id: auditId,
18444
+ severity: severityOf(finding, library),
18445
+ priority: priorityOf(finding, library)
18446
+ }))
18447
+ );
18448
+ const matches = rows.filter((row) => matchesFindingArgs(row, args));
18449
+ return { total: matches.length, findings: matches };
18450
+ }
18451
+ );
18452
+ tool(
18453
+ {
18454
+ name: "kritik_signals",
18455
+ description: "The signal pack: every applicable criterion's mechanically checkable statements, expanded across the surfaces it applies to, plus anything that has tripped since the last recorded audit. These are statements to CHECK, not commands to run \u2014 a grep that must return nothing, a CI job that must exist \u2014 so run them yourself and report what failed with kritik_trip_signal. Repo sessions only: the pack and its run sheet live with the code.",
18456
+ inputSchema: {
18457
+ type: "object",
18458
+ properties: {
18459
+ surface: { type: "string" },
18460
+ criterion_id: { type: "string" },
18461
+ domain: { type: "string", description: "Domain code, e.g. SEC." }
18462
+ },
18463
+ additionalProperties: false
18464
+ }
18465
+ },
18466
+ async (args) => {
18467
+ const root = repoRootOf(
18468
+ ctx,
18469
+ "Signals are statements checked against the repository \u2014 the pack and its run sheet live with the code."
18470
+ );
18471
+ const library = libraryOf(root);
18472
+ const profile = profileOf(root);
18473
+ const filter = {
18474
+ ...typeof args.surface === "string" ? { surface: surfaceOf(profile, args.surface) } : {},
18475
+ ...typeof args.criterion_id === "string" ? { criterion: criterionOf(library, args.criterion_id).id } : {},
18476
+ ...typeof args.domain === "string" ? { domain: args.domain } : {}
18477
+ };
18478
+ const rows = signalRunSheet(library, profile.surfaces ?? [], filter);
18479
+ const journal = resolveJournal(root);
18480
+ const events = journal.present ? orderEvents(readFullJournalEvents(journal.journalPath)) : [];
18481
+ const lastAudit = events.map((event) => event.type).lastIndexOf("quality.audit.completed");
18482
+ const tripped = events.slice(lastAudit + 1).filter((event) => event.type === "quality.signal.tripped");
18483
+ return { library_version: library.version, total: rows.length, signals: rows, tripped_since_last_audit: tripped };
18484
+ }
18485
+ );
18486
+ tool(
18487
+ {
18488
+ name: "kritik_regressions",
18489
+ description: "What got worse between two audits: a cell whose maturity level dropped, a cell that gained an open Critical or High finding, and a finding that was resolved and is open again. Cells scored in only one of the two audits are not compared \u2014 a half-finished audit is not a regression. With record=true, appends one quality.signal.tripped per regression (repo mode only \u2014 hosted comparisons are read-only and cover assessment-level drops, since hosted findings are a living pool rather than per-audit snapshots). A tripped signal is NOT a finding; it is the prompt to go look.",
18490
+ inputSchema: {
18491
+ type: "object",
18492
+ properties: {
18493
+ from: { type: "string", description: "The older audit. Default: the audit before `to`." },
18494
+ to: { type: "string", description: "The newer audit. Default: the newest on disk." },
18495
+ record: { type: "boolean", description: "Append one quality.signal.tripped per regression." }
18496
+ },
18497
+ additionalProperties: false
18498
+ }
18499
+ },
18500
+ async (args) => {
18501
+ const hosted = ctx.qualityRoot === void 0;
18502
+ if (hosted) {
18503
+ if (args.record === true) refuseHostedRecord("quality.signal.tripped");
18504
+ const graph = await load2();
18505
+ const { section, library: library2 } = hostedSection(graph);
18506
+ const grouped = /* @__PURE__ */ new Map();
18507
+ for (const assessment of section.assessments) {
18508
+ if (typeof assessment.audit_id !== "string" || assessment.audit_id === "") continue;
18509
+ const bucket = grouped.get(assessment.audit_id);
18510
+ if (bucket) bucket.push(assessment);
18511
+ else grouped.set(assessment.audit_id, [assessment]);
18512
+ }
18513
+ const audits2 = [...grouped.keys()].sort();
18514
+ const { from: from2, to: to2 } = resolveAuditPair(audits2, args, "in this project's assessments");
18515
+ const fromState = { assessments: grouped.get(from2) ?? [], findings: section.findings };
18516
+ const toState = { assessments: grouped.get(to2) ?? [], findings: section.findings };
18517
+ let regressions2;
18518
+ try {
18519
+ regressions2 = detectRegressions(fromState, toState, library2);
18520
+ } catch (error51) {
18521
+ throw new ToolError(error51.message);
18522
+ }
18523
+ return {
18524
+ from: from2,
18525
+ to: to2,
18526
+ total: regressions2.length,
18527
+ regressions: regressions2,
18528
+ events: [],
18529
+ note: "hosted comparison covers assessment level drops only \u2014 findings are a living pool (issue #400 decision 3)"
18530
+ };
18531
+ }
18532
+ const root = repoRootOf(ctx, REPO_MODE_ONLY);
18533
+ const library = libraryOf(root);
18534
+ const audits = listAuditIds(root);
18535
+ const { from, to } = resolveAuditPair(audits, args, "under docs/quality/audits/");
18536
+ let regressions;
18537
+ try {
18538
+ regressions = detectRegressions(
18539
+ loadQualitySection(root, from, library),
18540
+ loadQualitySection(root, to, library),
18541
+ library
18542
+ );
18543
+ } catch (error51) {
18544
+ throw new ToolError(error51.message);
18545
+ }
18546
+ let events = [];
18547
+ if (args.record === true && regressions.length > 0) {
18548
+ const graph = await load2();
18549
+ events = await record2(
18550
+ graph,
18551
+ regressions.map(
18552
+ (regression) => signalTrippedInput({
18553
+ criterion_id: regression.criterion_id,
18554
+ surface: regression.surface,
18555
+ signal: regression.signal,
18556
+ detail: regression.detail
18557
+ })
18558
+ )
18559
+ );
18560
+ }
18561
+ return { from, to, total: regressions.length, regressions, events };
18562
+ }
18563
+ );
18564
+ tool(
18565
+ {
18566
+ name: "kritik_issue",
18567
+ description: "The criterion's GitHub issue skeleton, filled as far as what is known allows. Placeholders that cannot be filled are left standing \u2014 a skeleton is a form to finish, and an empty '### Risk' reads as 'no risk'. Pass finding_id for the P0/P1 path: the risk numbers, evidence and narrative come from the finding.",
18568
+ inputSchema: {
18569
+ type: "object",
18570
+ properties: {
18571
+ criterion_id: { type: "string" },
18572
+ surface: { type: "string" },
18573
+ level: { type: "integer", minimum: 0, maximum: 4, description: "The observed maturity, so the anchors fill in." },
18574
+ finding_id: { type: "string" }
18575
+ },
18576
+ required: ["criterion_id", "surface"],
18577
+ additionalProperties: false
18578
+ }
18579
+ },
18580
+ async (args) => {
18581
+ const hosted = ctx.qualityRoot === void 0;
18582
+ if (hosted) {
18583
+ const graph = await load2();
18584
+ const { section, library: library2 } = hostedSection(graph);
18585
+ if (library2 === void 0) {
18586
+ throw new ToolError("This hosted project's quality section carries no criteria vocabulary \u2014 no embedded library and no scored criteria to synthesize one from.");
18587
+ }
18588
+ const criterion2 = criterionOf(library2, requireString(args, "criterion_id"));
18589
+ const surface2 = requireString(args, "surface");
18590
+ if (section.profile) surfaceOf(section.profile, surface2, true);
18591
+ let finding2;
18592
+ if (typeof args.finding_id === "string" && args.finding_id !== "") {
18593
+ finding2 = section.findings.find((candidate) => candidate.id === args.finding_id);
18594
+ if (!finding2) throw new ToolError(`No finding "${args.finding_id}" in this hosted project's quality section.`);
18595
+ }
18596
+ return renderIssue(criterion2, {
18597
+ surface: surface2,
18598
+ ...typeof args.level === "number" ? { level: args.level } : {},
18599
+ ...finding2 !== void 0 ? { finding: finding2, library: library2 } : {}
18600
+ });
18601
+ }
18602
+ const root = repoRootOf(ctx, REPO_MODE_ONLY);
18603
+ const library = libraryOf(root);
18604
+ const criterion = criterionOf(library, requireString(args, "criterion_id"));
18605
+ const surface = requireString(args, "surface");
18606
+ const declared2 = loadProfile(root);
18607
+ if (declared2) surfaceOf(declared2, surface, true);
18608
+ let finding;
18609
+ if (typeof args.finding_id === "string" && args.finding_id !== "") {
18610
+ const located = locateFinding(root, args.finding_id);
18611
+ if (!located) throw new ToolError(`No finding "${args.finding_id}" in any audit.`);
18612
+ finding = located.finding;
18613
+ }
18614
+ return renderIssue(criterion, {
18615
+ surface,
18616
+ ...typeof args.level === "number" ? { level: args.level } : {},
18617
+ ...finding !== void 0 ? { finding, library } : {}
18618
+ });
18619
+ }
18620
+ );
18621
+ tool(
18622
+ {
18623
+ name: "kritik_score",
18624
+ description: "Record one (criterion x surface) maturity level with the evidence behind it. A cell holds exactly one level, so re-scoring replaces in place. Evidence is required: a score without a citation is an opinion, not an assessment. Score what the code IS, never what an open PR promises \u2014 that is what makes a trend real. Repo sessions only: scoring reads the code, so a hosted session refuses.",
18625
+ inputSchema: {
18626
+ type: "object",
18627
+ properties: {
18628
+ criterion_id: { type: "string" },
18629
+ surface: { type: "string" },
18630
+ level: {
18631
+ type: "integer",
18632
+ enum: [...MATURITY_LEVELS],
18633
+ description: "0 Absent \xB7 1 Ad-hoc \xB7 2 Defined \xB7 3 Managed \xB7 4 Verified. N/A is the absence of the row, not a level."
18634
+ },
18635
+ evidence: { type: "string", description: "file:line / config citations, markdown." },
18636
+ audit_id: { type: "string", description: "Default: the newest audit, or the current YYYY-MM." },
18637
+ commit: { type: "string" }
18638
+ },
18639
+ required: ["criterion_id", "surface", "level", "evidence"],
18640
+ additionalProperties: false
18641
+ }
18642
+ },
18643
+ async (args) => {
18644
+ const root = repoRootOf(ctx, "Scoring reads the code \u2014 evidence is file:line against a working tree.");
18645
+ const library = libraryOf(root);
18646
+ const profile = profileOf(root);
18647
+ const criterionId = requireString(args, "criterion_id");
18648
+ const criterion = criterionOf(library, criterionId);
18649
+ const surface = surfaceOf(profile, requireString(args, "surface"));
18650
+ const level = requireInt(args, "level", 0, 4);
18651
+ const evidence = requireString(args, "evidence");
18652
+ const appliesTo = criterion.applies_to;
18653
+ if (Array.isArray(appliesTo) && !appliesTo.includes(surface)) {
18654
+ throw new ToolError(
18655
+ `${criterionId} does not apply to "${surface}" (applies to: ${appliesTo.join(", ")}). Scoring it there would produce a cell nothing rolls up.`
18656
+ );
18657
+ }
18658
+ const auditId = auditForWrite(root, args.audit_id);
18659
+ const file2 = loadScoresOrEmpty(root, auditId);
18660
+ const assessment = {
18661
+ criterion_id: criterionId,
18662
+ surface,
18663
+ level,
18664
+ evidence,
18665
+ audit_id: auditId,
18666
+ ...typeof args.commit === "string" ? { commit: args.commit } : {},
18667
+ ts: (/* @__PURE__ */ new Date()).toISOString()
18668
+ };
18669
+ const { assessments, replaced } = upsertAssessment(file2.assessments, assessment);
18670
+ saveScores(root, auditId, {
18671
+ ...file2,
18672
+ audit_id: auditId,
18673
+ framework_version: file2.framework_version ?? library.version,
18674
+ ...typeof args.commit === "string" ? { commit: args.commit } : {},
18675
+ assessments
18676
+ });
18677
+ return {
18678
+ assessment,
18679
+ audit_id: auditId,
18680
+ assessment_count: assessments.length,
18681
+ ...replaced !== void 0 ? { replaced_level: replaced.level } : {},
18682
+ anchor: criterion.level_anchors?.[`l${level}`]
18683
+ };
18684
+ }
18685
+ );
18686
+ tool(
18687
+ {
18688
+ name: "kritik_open_finding",
18689
+ description: "Open a finding on a (criterion x surface) cell and append quality.finding.opened. One finding is one defect \u2014 not one criterion, and not one surface's worth of grumbling. Verify Critical and High adversarially BEFORE opening: try to refute them against the repo, and record the verdict. Severity and priority come back derived; they are never stored. Repo sessions only: a new finding cites code, so a hosted session refuses.",
18690
+ inputSchema: {
18691
+ type: "object",
18692
+ properties: {
18693
+ criterion_id: { type: "string" },
18694
+ surface: { type: "string", description: `A profile surface, or "${CROSS_SURFACE_ID}" for a defect belonging to the contract between surfaces.` },
18695
+ title: { type: "string", description: "One line naming the actual defect, not the category." },
18696
+ detail: { type: "string", description: "What breaks, for whom, and the path that gets there. Defaults to the title." },
18697
+ evidence: { type: "string", description: "file:line citations someone can check." },
18698
+ impact: { type: "integer", minimum: 1, maximum: 5, description: "Worst plausible consequence." },
18699
+ likelihood: { type: "integer", minimum: 1, maximum: 5, description: "Probability it materializes." },
18700
+ cost: { type: "string", enum: [...REMEDIATION_COSTS], description: "S <= half day \xB7 M <= 2 days \xB7 L <= 1 week \xB7 XL beyond." },
18701
+ remediation: { type: "string" },
18702
+ node_ids: { type: "array", items: { type: "string" }, description: "Product-graph nodes this is about." },
18703
+ issue_url: { type: "string" },
18704
+ verification: {
18705
+ type: "object",
18706
+ properties: {
18707
+ verdict: { type: "string", enum: ["CONFIRMED", "REFUTED", "DOWNGRADED"] },
18708
+ note: { type: "string" }
18709
+ },
18710
+ required: ["verdict"],
18711
+ additionalProperties: false,
18712
+ description: "The adversarial pass. A refuted finding is disclosed, not deleted \u2014 open it with status refuted."
18713
+ },
18714
+ audit_id: { type: "string" },
18715
+ finding_id: { type: "string", description: "Default: minted as F-<audit>-<DOMAIN>-<surface>-NN." }
18716
+ },
18717
+ required: ["criterion_id", "surface", "title", "evidence", "impact", "likelihood", "cost"],
18718
+ additionalProperties: false
18719
+ }
18720
+ },
18721
+ async (args) => {
18722
+ const root = repoRootOf(ctx, "A new finding cites code: evidence is file:line, verified adversarially against the checkout.");
18723
+ const library = libraryOf(root);
18724
+ const profile = profileOf(root);
18725
+ const criterionId = requireString(args, "criterion_id");
18726
+ criterionOf(library, criterionId);
18727
+ const surface = surfaceOf(profile, requireString(args, "surface"), true);
18728
+ const title = requireString(args, "title");
18729
+ const evidence = requireString(args, "evidence");
18730
+ const impact = requireInt(args, "impact", 1, 5);
18731
+ const likelihood = requireInt(args, "likelihood", 1, 5);
18732
+ const cost = requireString(args, "cost");
18733
+ if (!REMEDIATION_COSTS.includes(cost)) {
18734
+ throw new ToolError(`\`cost\` must be one of ${REMEDIATION_COSTS.join(", ")} \u2014 it decides priority.`);
18735
+ }
18736
+ const auditId = auditForWrite(root, args.audit_id);
18737
+ const file2 = loadFindings(root, auditId);
18738
+ const taken = new Set(file2.findings.map((candidate) => candidate.id));
18739
+ const requestedId = typeof args.finding_id === "string" && args.finding_id !== "" ? args.finding_id : void 0;
18740
+ if (requestedId !== void 0 && taken.has(requestedId)) {
18741
+ throw new ToolError(`Finding "${requestedId}" already exists in ${auditId} \u2014 resolve or accept it rather than reopening the id.`);
18742
+ }
18743
+ const id = requestedId ?? mintFindingId(auditId, criterionId, surface, taken, library);
18744
+ const nodeIds = Array.isArray(args.node_ids) ? args.node_ids.filter((value) => typeof value === "string") : void 0;
18745
+ const verification = args.verification;
18746
+ const finding = {
18747
+ id,
18748
+ criterion_id: criterionId,
18749
+ surface,
18750
+ title,
18751
+ detail: typeof args.detail === "string" && args.detail !== "" ? args.detail : title,
18752
+ evidence,
18753
+ impact,
18754
+ likelihood,
18755
+ cost,
18756
+ status: verification?.verdict === "REFUTED" ? "refuted" : "open",
18757
+ ...typeof args.remediation === "string" ? { remediation: args.remediation } : {},
18758
+ ...nodeIds !== void 0 && nodeIds.length > 0 ? { node_ids: nodeIds } : {},
18759
+ ...typeof args.issue_url === "string" ? { issue_url: args.issue_url } : {},
18760
+ ...verification !== void 0 ? { verification } : {}
18761
+ };
18762
+ const graph = await load2();
18763
+ const events = await record2(graph, finding.status === "refuted" ? [] : [findingOpenedInput(finding, library)]);
18764
+ const { findings } = upsertFinding(file2.findings, finding);
18765
+ saveFindings(root, auditId, {
18766
+ ...file2,
18767
+ audit_id: auditId,
18768
+ framework_version: file2.framework_version ?? library.version,
18769
+ findings
18770
+ });
18771
+ return {
18772
+ finding,
18773
+ audit_id: auditId,
18774
+ severity: severityOf(finding, library),
18775
+ priority: priorityOf(finding, library),
18776
+ finding_count: findings.length,
18777
+ events
18778
+ };
18779
+ }
18780
+ );
18781
+ tool(
18782
+ {
18783
+ name: "kritik_resolve_finding",
18784
+ description: "Close a finding because the fix merged, and append quality.finding.resolved. `resolved_by` is the PR or commit URL \u2014 the evidence it is actually gone, which is the only thing separating 'resolved' from 'we stopped looking'. Idempotent: resolving an already-resolved finding writes nothing.",
18785
+ inputSchema: {
18786
+ type: "object",
18787
+ properties: {
18788
+ finding_id: { type: "string" },
18789
+ resolved_by: { type: "string", description: "The PR or commit URL that closed it." }
18790
+ },
18791
+ required: ["finding_id"],
18792
+ additionalProperties: false
18793
+ }
18794
+ },
18795
+ async (args) => {
18796
+ const id = requireString(args, "finding_id");
18797
+ const resolvedBy = typeof args.resolved_by === "string" && args.resolved_by !== "" ? args.resolved_by : void 0;
18798
+ if (ctx.qualityRoot === void 0) {
18799
+ const graph2 = await load2();
18800
+ const { section } = hostedSection(graph2);
18801
+ const finding2 = section.findings.find((candidate) => candidate.id === id);
18802
+ if (!finding2) throw new ToolError(`No finding "${id}" in this hosted project's quality section.`);
18803
+ if (finding2.status === "resolved") {
18804
+ return { finding: finding2, events: [], note: "Already resolved \u2014 nothing written." };
18805
+ }
18806
+ const events2 = await appendHosted(ctx.store, [
18807
+ { type: "quality.finding.resolved", finding_id: finding2.id, ...resolvedBy !== void 0 ? { resolved_by: resolvedBy } : {} }
18808
+ ]);
18809
+ return {
18810
+ finding: { ...finding2, status: "resolved", ...resolvedBy !== void 0 ? { resolved_by: resolvedBy } : {} },
18811
+ events: events2
18812
+ };
18813
+ }
18814
+ const root = repoRootOf(ctx, REPO_MODE_ONLY);
18815
+ const located = locateFinding(root, id);
18816
+ if (!located) throw new ToolError(`No finding "${id}" in any audit under docs/quality/audits/.`);
18817
+ if (located.finding.status === "resolved") {
18818
+ return { finding: located.finding, audit_id: located.auditId, events: [], note: "Already resolved \u2014 nothing written." };
18819
+ }
18820
+ const graph = await load2();
18821
+ const events = await record2(graph, [findingResolvedInput(located.finding, resolvedBy)]);
18822
+ const { findings, finding } = resolveFinding(located.file.findings, id, resolvedBy);
18823
+ saveFindings(root, located.auditId, { ...located.file, findings });
18824
+ return { finding, audit_id: located.auditId, events };
18825
+ }
18826
+ );
18827
+ tool(
18828
+ {
18829
+ name: "kritik_accept_finding",
18830
+ description: "Record a finding as a known, owned risk. The note is required \u2014 an accepted risk is a decision and reads like one, and the findings board renders it as a decision-log entry. In repo mode acceptance is a state of the finding, written straight to the findings file with no journal event; a hosted session has no findings file to hold that state, so it appends quality.finding.accepted instead, and the read derives status accepted-risk from it.",
18831
+ inputSchema: {
18832
+ type: "object",
18833
+ properties: {
18834
+ finding_id: { type: "string" },
18835
+ note: { type: "string", description: "Why this risk is accepted, and by what reasoning." }
18836
+ },
18837
+ required: ["finding_id", "note"],
18838
+ additionalProperties: false
18839
+ }
18840
+ },
18841
+ async (args) => {
18842
+ const id = requireString(args, "finding_id");
18843
+ const note = requireString(args, "note");
18844
+ if (ctx.qualityRoot === void 0) {
18845
+ const graph = await load2();
18846
+ const { section } = hostedSection(graph);
18847
+ const finding2 = section.findings.find((candidate) => candidate.id === id);
18848
+ if (!finding2) throw new ToolError(`No finding "${id}" in this hosted project's quality section.`);
18849
+ const events = await appendHosted(ctx.store, [{ type: "quality.finding.accepted", finding_id: finding2.id, reason: note }]);
18850
+ return {
18851
+ finding: { ...finding2, status: "accepted-risk", detail: acceptedDetail(finding2.detail, note) },
18852
+ events
18853
+ };
18854
+ }
18855
+ const root = repoRootOf(ctx, REPO_MODE_ONLY);
18856
+ const located = locateFinding(root, id);
18857
+ if (!located) throw new ToolError(`No finding "${id}" in any audit under docs/quality/audits/.`);
18858
+ const { findings, finding } = acceptFinding(located.file.findings, id, note);
18859
+ saveFindings(root, located.auditId, { ...located.file, findings });
18860
+ return { finding, audit_id: located.auditId, events: [] };
18861
+ }
18862
+ );
18863
+ tool(
18864
+ {
18865
+ name: "kritik_trip_signal",
18866
+ description: "Record that a monitoring signal failed between audits: appends quality.signal.tripped. A tripped signal is NOT a finding \u2014 it is the prompt to go look. Cheap, frequent, and allowed to be wrong, where a finding is expensive, rare, and has survived an adversarial pass. Repo sessions only: signals are checked against the repository.",
18867
+ inputSchema: {
18868
+ type: "object",
18869
+ properties: {
18870
+ criterion_id: { type: "string" },
18871
+ surface: { type: "string" },
18872
+ signal: { type: "string", description: "The statement that failed, or its index in the criterion's signals[]." },
18873
+ detail: { type: "string", description: "What you actually observed." }
18874
+ },
18875
+ required: ["criterion_id", "surface", "signal"],
18876
+ additionalProperties: false
18877
+ }
18878
+ },
18879
+ async (args) => {
18880
+ const root = repoRootOf(
18881
+ ctx,
18882
+ "Signals are statements checked against the repository \u2014 the pack and its run sheet live with the code."
18883
+ );
18884
+ const library = libraryOf(root);
18885
+ const profile = profileOf(root);
18886
+ const criterion = criterionOf(library, requireString(args, "criterion_id"));
18887
+ const surface = surfaceOf(profile, requireString(args, "surface"));
18888
+ const raw = requireString(args, "signal");
18889
+ const signals = criterion.signals ?? [];
18890
+ const index = Number(raw);
18891
+ const signal = Number.isInteger(index) && index >= 0 && index < signals.length ? signals[index] : raw;
18892
+ const graph = await load2();
18893
+ const events = await record2(graph, [
18894
+ signalTrippedInput({
18895
+ criterion_id: criterion.id,
18896
+ surface,
18897
+ signal,
18898
+ ...typeof args.detail === "string" ? { detail: args.detail } : {}
18899
+ })
18900
+ ]);
18901
+ return { criterion_id: criterion.id, surface, signal, events };
18902
+ }
18903
+ );
18904
+ return { tools: tools2, handlers: handlers2 };
18905
+ }
18906
+
18907
+ // src/tools.ts
18908
+ async function load(ctx) {
18909
+ let graph;
18910
+ try {
18911
+ graph = await ctx.store.load();
18912
+ } catch (error51) {
18913
+ throw new ToolError(`Cannot load ${ctx.store.describe()}: ${error51.message}`);
18914
+ }
18915
+ return {
18916
+ loaded: graph.loaded,
18917
+ nodes: graph.nodes,
18918
+ edges: graph.edges,
18919
+ project: graph.project,
18920
+ journal: graph.journal
18921
+ };
18922
+ }
18923
+ function requireString2(args, key) {
18924
+ const value = args[key];
18925
+ if (typeof value !== "string" || value.length === 0) {
18926
+ throw new ToolError(`\`${key}\` is required and must be a non-empty string.`);
18927
+ }
18928
+ return value;
18929
+ }
18930
+ function normalizeStatusArg(value) {
18931
+ const normalized = normalizeStatus(value);
18932
+ if (normalized === void 0) {
18933
+ throw new ToolError(`"${value}" is not a status (expected one of: ${STATUS_IDS.join(", ")}).`);
18934
+ }
18935
+ return normalized;
18936
+ }
18937
+ function findNode(nodes, nodeId) {
18938
+ const node = nodes.find((candidate) => candidate.id === nodeId);
18939
+ if (!node) throw new ToolError(`No node with id "${nodeId}".`);
18940
+ return node;
18941
+ }
18942
+ function nodeSummary(node) {
18943
+ const base = { id: node.id, title: node.title, species: node.species, status: node.status, platforms: node.platforms };
18944
+ if (node.species !== "acceptance") return base;
18945
+ const platform_statuses = Object.fromEntries(
18946
+ node.platforms.map((platform) => [platform, resolvePlatformStatus(node, platform)])
18947
+ );
18948
+ return { ...base, platform_statuses, values: node.metadata?.values ?? [] };
18949
+ }
18950
+ function unwrap(result) {
18951
+ if (!result.ok) {
18952
+ throw new ToolError("Mutation refused by validateBundle \u2014 nothing was written.", {
18953
+ findings: result.errors,
18954
+ warnings: result.warnings
18955
+ });
18956
+ }
18957
+ return { warnings: result.warnings, events: result.events };
18958
+ }
18959
+ var UPDATABLE_NODE_FIELDS = /* @__PURE__ */ new Set(["title", "description", "status", "platforms", "metadata"]);
18960
+ function mutate(graph, ops) {
18961
+ try {
18962
+ return applyOps({ projectId: graph.project.id, nodes: graph.nodes, edges: graph.edges }, ops);
18963
+ } catch (err) {
18964
+ if (err instanceof MutationError) throw new ToolError(err.message);
18965
+ throw err;
18966
+ }
18967
+ }
18968
+ function listReleases(journal, nodesById) {
18969
+ const latestByVersion = /* @__PURE__ */ new Map();
18970
+ for (const event of orderEvents(journal)) {
18971
+ if (event.type !== "release.tagged") continue;
18972
+ const tag = event;
18973
+ latestByVersion.set(tag.version, tag);
18974
+ }
18975
+ return [...latestByVersion.values()].sort((a, b) => a.ts === b.ts ? a.id < b.id ? 1 : -1 : a.ts < b.ts ? 1 : -1).map((tag) => ({
18976
+ version: tag.version,
18977
+ ts: tag.ts,
18978
+ ...tag.platform !== void 0 ? { platform: tag.platform } : {},
18979
+ ...tag.notes !== void 0 ? { notes: tag.notes } : {},
18980
+ eventCount: computeChangelog(journal, tag.version, { nodesById }).events.length
18981
+ }));
18982
+ }
18983
+ function buildCatalog(ctx) {
18984
+ const tools2 = [];
18985
+ const handlers2 = {};
18986
+ const tool = (definition, handler) => {
18987
+ tools2.push(definition);
18988
+ handlers2[definition.name] = handler;
18989
+ };
18990
+ tool(
18991
+ {
18992
+ name: "list_nodes",
18993
+ description: "List nodes in the product graph, filtered by species, status, platform, value element, covers-anchor, parity gap, and/or a case-insensitive title/description substring. Returns summaries (acceptances include platform_statuses + values).",
18994
+ inputSchema: {
18995
+ type: "object",
18996
+ properties: {
18997
+ species: { type: "string", enum: [...SPECIES_IDS] },
18998
+ status: { type: "string", enum: [...STATUS_IDS] },
18999
+ platform: { type: "string", enum: [...PLATFORM_IDS] },
19000
+ value: {
19001
+ type: "string",
19002
+ enum: [...VALUE_IDS],
19003
+ description: "Only acceptances tagged with this value element."
19004
+ },
19005
+ anchor: {
19006
+ type: "string",
19007
+ description: "Node id \u2014 only acceptances covering it via a covers edge."
19008
+ },
19009
+ parity_gap: {
19010
+ type: "boolean",
19011
+ description: "Only acceptances delivered (live) on \u22651 applicable platform but not all."
19012
+ },
19013
+ query: { type: "string", description: "Case-insensitive substring over title + description." },
19014
+ limit: { type: "integer", minimum: 1, description: "Default 50." }
19015
+ },
19016
+ additionalProperties: false
19017
+ }
19018
+ },
19019
+ async (args) => {
19020
+ const { nodes, edges } = await load(ctx);
19021
+ const query = typeof args.query === "string" ? args.query.toLowerCase() : void 0;
19022
+ const limit = typeof args.limit === "number" && args.limit >= 1 ? Math.floor(args.limit) : 50;
19023
+ const status = typeof args.status === "string" ? normalizeStatusArg(args.status) : void 0;
19024
+ const anchorCoveringIds = typeof args.anchor === "string" ? new Set(acceptancesCovering(args.anchor, nodes, edges).map((node) => node.id)) : void 0;
19025
+ const matches = nodes.filter((node) => {
19026
+ if (typeof args.species === "string" && node.species !== args.species) return false;
19027
+ if (status !== void 0 && node.status !== status) return false;
19028
+ if (typeof args.platform === "string" && !node.platforms.includes(args.platform))
19029
+ return false;
19030
+ if (typeof args.value === "string" && (node.species !== "acceptance" || !(node.metadata?.values ?? []).includes(args.value))) return false;
19031
+ if (anchorCoveringIds !== void 0 && !anchorCoveringIds.has(node.id)) return false;
19032
+ if (args.parity_gap === true && (node.species !== "acceptance" || !hasParityGap(node))) return false;
19033
+ if (query !== void 0) {
19034
+ const haystack = `${node.title}
19035
+ ${node.description ?? ""}`.toLowerCase();
19036
+ if (!haystack.includes(query)) return false;
17239
19037
  }
17240
19038
  return true;
17241
19039
  });
@@ -17254,7 +19052,7 @@ ${node.description ?? ""}`.toLowerCase();
17254
19052
  }
17255
19053
  },
17256
19054
  async (args) => {
17257
- const nodeId = requireString(args, "node_id");
19055
+ const nodeId = requireString2(args, "node_id");
17258
19056
  const { nodes, edges, journal } = await load(ctx);
17259
19057
  const node = findNode(nodes, nodeId);
17260
19058
  const nodesById = new Map(nodes.map((candidate) => [candidate.id, candidate]));
@@ -17348,7 +19146,7 @@ ${node.description ?? ""}`.toLowerCase();
17348
19146
  }
17349
19147
  },
17350
19148
  async (args) => {
17351
- const mapId = requireString(args, "map_id");
19149
+ const mapId = requireString2(args, "map_id");
17352
19150
  const { nodes, edges, project } = await load(ctx);
17353
19151
  const definition = listMaps(project).find((candidate) => candidate.id === mapId);
17354
19152
  if (!definition) throw new ToolError(`No map with id "${mapId}".`);
@@ -17392,8 +19190,8 @@ ${node.description ?? ""}`.toLowerCase();
17392
19190
  },
17393
19191
  async (args) => {
17394
19192
  const graph = await load(ctx);
17395
- const species = requireString(args, "species");
17396
- const title = requireString(args, "title");
19193
+ const species = requireString2(args, "species");
19194
+ const title = requireString2(args, "title");
17397
19195
  const platforms = Array.isArray(args.platforms) ? args.platforms : [];
17398
19196
  const node = {
17399
19197
  id: deriveNodeId(species, title, graph.nodes.map((candidate) => candidate.id)),
@@ -17441,7 +19239,7 @@ ${node.description ?? ""}`.toLowerCase();
17441
19239
  }
17442
19240
  },
17443
19241
  async (args) => {
17444
- const nodeId = requireString(args, "node_id");
19242
+ const nodeId = requireString2(args, "node_id");
17445
19243
  if (typeof args.patch !== "object" || args.patch === null || Array.isArray(args.patch)) {
17446
19244
  throw new ToolError("`patch` is required and must be an object.");
17447
19245
  }
@@ -17481,7 +19279,7 @@ ${node.description ?? ""}`.toLowerCase();
17481
19279
  }
17482
19280
  },
17483
19281
  async (args) => {
17484
- const nodeId = requireString(args, "node_id");
19282
+ const nodeId = requireString2(args, "node_id");
17485
19283
  const graph = await load(ctx);
17486
19284
  const node = findNode(graph.nodes, nodeId);
17487
19285
  const ops = [{ op: "delete_node", node_id: nodeId }];
@@ -17511,9 +19309,9 @@ ${node.description ?? ""}`.toLowerCase();
17511
19309
  }
17512
19310
  },
17513
19311
  async (args) => {
17514
- const sourceId = requireString(args, "source_id");
17515
- const targetId = requireString(args, "target_id");
17516
- const edgeType = requireString(args, "edge_type");
19312
+ const sourceId = requireString2(args, "source_id");
19313
+ const targetId = requireString2(args, "target_id");
19314
+ const edgeType = requireString2(args, "edge_type");
17517
19315
  const graph = await load(ctx);
17518
19316
  const edge = {
17519
19317
  id: edgeId(sourceId, targetId),
@@ -17548,7 +19346,7 @@ ${node.description ?? ""}`.toLowerCase();
17548
19346
  }
17549
19347
  },
17550
19348
  async (args) => {
17551
- const edgeIdArg = requireString(args, "edge_id");
19349
+ const edgeIdArg = requireString2(args, "edge_id");
17552
19350
  const graph = await load(ctx);
17553
19351
  const edge = graph.edges.find((candidate) => candidate.id === edgeIdArg);
17554
19352
  if (!edge) throw new ToolError(`No edge with id "${edgeIdArg}".`);
@@ -17564,7 +19362,7 @@ ${node.description ?? ""}`.toLowerCase();
17564
19362
  }
17565
19363
  );
17566
19364
  const journalOnly = (type) => async (args) => {
17567
- const title = requireString(args, "title");
19365
+ const title = requireString2(args, "title");
17568
19366
  const graph = await load(ctx);
17569
19367
  const payload = { title };
17570
19368
  if (typeof args.description === "string") payload.description = args.description;
@@ -17610,117 +19408,23 @@ ${node.description ?? ""}`.toLowerCase();
17610
19408
  },
17611
19409
  journalOnly("request.filed")
17612
19410
  );
19411
+ const kritik = buildKritikCatalog(ctx);
19412
+ tools2.push(...kritik.tools);
19413
+ Object.assign(handlers2, kritik.handlers);
17613
19414
  return { tools: tools2, handlers: handlers2 };
17614
19415
  }
17615
19416
 
17616
19417
  // src/store.ts
17617
- import { writeFileSync as writeFileSync2 } from "node:fs";
17618
- import { resolve } from "node:path";
17619
-
17620
- // ../cli/src/lib/bundle-io.ts
17621
- import { existsSync, readFileSync } from "node:fs";
17622
- function readBundle(filePath) {
17623
- if (!existsSync(filePath)) throw new Error(`File not found: ${filePath}`);
17624
- let parsed;
17625
- try {
17626
- parsed = JSON.parse(readFileSync(filePath, "utf8"));
17627
- } catch (e) {
17628
- throw new Error(`Cannot parse JSON \u2014 ${e.message}`);
17629
- }
17630
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
17631
- throw new Error("Bundle must be a JSON object.");
17632
- }
17633
- const record2 = parsed;
17634
- if (!Array.isArray(record2.nodes)) return record2;
17635
- return migrateStatusVocabulary(record2);
17636
- }
17637
-
17638
- // ../cli/src/lib/journal-io.ts
17639
- import { appendFileSync, existsSync as existsSync2, mkdirSync, readdirSync, readFileSync as readFileSync2, writeFileSync } from "node:fs";
17640
- import { dirname, join } from "node:path";
17641
- var JOURNAL_SIDECAR = "journal.jsonl";
17642
- function journalPathFor(bundlePath) {
17643
- return join(dirname(bundlePath), JOURNAL_SIDECAR);
17644
- }
17645
- function archivePathsFor(journalPath) {
17646
- const dir = join(dirname(journalPath), "journal");
17647
- if (!existsSync2(dir)) return [];
17648
- return readdirSync(dir).filter((name) => name.startsWith("archive-") && name.endsWith(".jsonl")).sort().map((name) => join(dir, name));
17649
- }
17650
- function toLine(event) {
17651
- return JSON.stringify(event) + "\n";
17652
- }
17653
- function appendJournalEvent(journalPath, event) {
17654
- const line = toLine(event);
17655
- if (!existsSync2(journalPath)) {
17656
- mkdirSync(dirname(journalPath), { recursive: true });
17657
- writeFileSync(journalPath, line);
17658
- return;
17659
- }
17660
- const existing = readFileSync2(journalPath, "utf8");
17661
- const prefix = existing.length > 0 && !existing.endsWith("\n") ? "\n" : "";
17662
- appendFileSync(journalPath, prefix + line);
17663
- }
17664
-
17665
- // ../cli/src/lib/bundle-validate.ts
17666
- import { existsSync as existsSync3, readFileSync as readFileSync3 } from "node:fs";
17667
- import { basename } from "node:path";
17668
- function validateBundleAt(filePath) {
17669
- const bundle = readBundle(filePath);
17670
- const loose = bundle;
17671
- if (!loose.project || !loose.nodes || !loose.edges) {
17672
- throw new Error("Missing top-level keys (project, nodes, edges).");
17673
- }
17674
- let sidecarFindings = [];
17675
- let sidecarLoaded = false;
17676
- const archiveFindings = [];
17677
- const archivesLoaded = [];
17678
- if (loose.journal === void 0) {
17679
- const sidecarPath = journalPathFor(filePath);
17680
- const folded = [];
17681
- if (existsSync3(sidecarPath)) {
17682
- const { events, findings } = parseJournalLines(readFileSync3(sidecarPath, "utf8"));
17683
- sidecarFindings = findings;
17684
- sidecarLoaded = true;
17685
- folded.push(...events);
17686
- }
17687
- for (const archivePath of archivePathsFor(sidecarPath)) {
17688
- const { events, findings } = parseJournalLines(readFileSync3(archivePath, "utf8"));
17689
- const file2 = basename(archivePath);
17690
- for (const finding of findings) archiveFindings.push({ ...finding, file: file2 });
17691
- archivesLoaded.push(file2);
17692
- folded.push(...events);
17693
- }
17694
- if (sidecarLoaded || archivesLoaded.length > 0) loose.journal = folded;
17695
- }
17696
- const nodes = Array.isArray(loose.nodes) ? loose.nodes : [];
17697
- const edges = Array.isArray(loose.edges) ? loose.edges : [];
17698
- const journal = Array.isArray(loose.journal) ? loose.journal : [];
17699
- const result = validateBundle(bundle);
17700
- const valid = sidecarFindings.length === 0 && archiveFindings.length === 0 && result.errors.length === 0;
17701
- return {
17702
- bundle,
17703
- nodes,
17704
- edges,
17705
- journal,
17706
- sidecarLoaded,
17707
- sidecarFindings,
17708
- archivesLoaded,
17709
- archiveFindings,
17710
- result,
17711
- valid
17712
- };
17713
- }
17714
-
17715
- // src/store.ts
19418
+ import { writeFileSync as writeFileSync3 } from "node:fs";
19419
+ import { resolve as resolve3 } from "node:path";
17716
19420
  var MCP_ACTOR = "arkaik-mcp";
17717
- var DEFAULT_BUNDLE_PATH = "docs/arkaik/bundle.json";
19421
+ var DEFAULT_BUNDLE_PATH2 = "docs/arkaik/bundle.json";
17718
19422
  function resolveBundlePath(argv2, env) {
17719
19423
  const flagIndex = argv2.indexOf("--bundle");
17720
19424
  const flagValue2 = flagIndex !== -1 ? argv2[flagIndex + 1] : void 0;
17721
- if (flagValue2) return resolve(flagValue2);
17722
- if (env.ARKAIK_BUNDLE) return resolve(env.ARKAIK_BUNDLE);
17723
- return resolve(DEFAULT_BUNDLE_PATH);
19425
+ if (flagValue2) return resolve3(flagValue2);
19426
+ if (env.ARKAIK_BUNDLE) return resolve3(env.ARKAIK_BUNDLE);
19427
+ return resolve3(DEFAULT_BUNDLE_PATH2);
17724
19428
  }
17725
19429
  function loadBundle(bundlePath) {
17726
19430
  return validateBundleAt(bundlePath);
@@ -17749,7 +19453,7 @@ function persistMutation(bundlePath, loaded, next, inputs) {
17749
19453
  const journalOnDisk = loaded.sidecarLoaded || loaded.archivesLoaded.length > 0;
17750
19454
  const embeddedJournal = !journalOnDisk && loaded.bundle.journal !== void 0;
17751
19455
  if (embeddedJournal) {
17752
- writeFileSync2(bundlePath, serializeBundle(candidate));
19456
+ writeFileSync3(bundlePath, serializeBundle(candidate));
17753
19457
  } else {
17754
19458
  const journalPath = journalPathFor(bundlePath);
17755
19459
  for (const event of events) {
@@ -17758,7 +19462,7 @@ function persistMutation(bundlePath, loaded, next, inputs) {
17758
19462
  if (next.nodes !== void 0 || next.edges !== void 0) {
17759
19463
  const snapshot = { ...loaded.bundle, nodes: nextNodes, edges: nextEdges };
17760
19464
  delete snapshot.journal;
17761
- writeFileSync2(bundlePath, serializeBundle(snapshot));
19465
+ writeFileSync3(bundlePath, serializeBundle(snapshot));
17762
19466
  }
17763
19467
  }
17764
19468
  return { ok: true, warnings: result.warnings, events };
@@ -17888,6 +19592,30 @@ function createRemoteStore(options) {
17888
19592
  },
17889
19593
  describe() {
17890
19594
  return `hosted project: ${options.projectId} at ${base}`;
19595
+ },
19596
+ // `quality.finding.*` events do not fold through `applyOps` — a finding
19597
+ // isn't a node or edge — so they get their own endpoint rather than riding
19598
+ // `/mutations`. And unlike `persist`, there is no client-side gate at all:
19599
+ // whether a finding is still open is a post-fold read of the journal, and
19600
+ // the server holds that journal. Sending an "open" guess from here could
19601
+ // only be stale the moment two sessions race, so this method does no
19602
+ // checking of its own — it forwards the inputs and lets the server's
19603
+ // verdict (post-fold, under its row lock) be the only one that counts.
19604
+ async appendQualityEvents(inputs) {
19605
+ try {
19606
+ const result = await request("/quality/events", {
19607
+ method: "POST",
19608
+ body: JSON.stringify({ events: inputs })
19609
+ });
19610
+ return result.events;
19611
+ } catch (err) {
19612
+ const e = err;
19613
+ if (e.status === 422 && e.body?.error === "refused") {
19614
+ const detail = e.body.refusals ? e.body.refusals.map((r) => `${r.finding_id}: ${r.reason}`).join(", ") : e.body.reason ?? "refused";
19615
+ throw new Error(`Quality events refused \u2014 ${detail}`);
19616
+ }
19617
+ throw err;
19618
+ }
17891
19619
  }
17892
19620
  };
17893
19621
  }
@@ -17900,13 +19628,13 @@ function describeFailure(status, body) {
17900
19628
  }
17901
19629
 
17902
19630
  // src/config.ts
17903
- import { readFileSync as readFileSync4 } from "node:fs";
17904
- import { join as join2 } from "node:path";
19631
+ import { readFileSync as readFileSync5 } from "node:fs";
19632
+ import { join as join5 } from "node:path";
17905
19633
  var LINK_FILE = "docs/arkaik/arkaik.json";
17906
19634
  var DEFAULT_BASE_URL = "https://arkaik.app";
17907
19635
  function readLinkFile(cwd) {
17908
19636
  try {
17909
- const parsed = JSON.parse(readFileSync4(join2(cwd, LINK_FILE), "utf8"));
19637
+ const parsed = JSON.parse(readFileSync5(join5(cwd, LINK_FILE), "utf8"));
17910
19638
  if (typeof parsed !== "object" || parsed === null) return null;
17911
19639
  return parsed;
17912
19640
  } catch {
@@ -17947,7 +19675,7 @@ function resolveRemoteConfig(argv2, env, cwd) {
17947
19675
  }
17948
19676
 
17949
19677
  // src/index.ts
17950
- var VERSION = "0.2.3";
19678
+ var VERSION = "0.4.0";
17951
19679
  var argv = process.argv.slice(2);
17952
19680
  if (argv.includes("--help") || argv.includes("-h")) {
17953
19681
  process.stdout.write(
@@ -17975,23 +19703,28 @@ if (argv.includes("--help") || argv.includes("-h")) {
17975
19703
  function resolveStore() {
17976
19704
  const remote = resolveRemoteConfig(argv, process.env, process.cwd());
17977
19705
  if (remote.mode === "remote") {
17978
- return createRemoteStore({
17979
- baseUrl: remote.baseUrl,
17980
- projectId: remote.projectId,
17981
- token: remote.token
17982
- });
19706
+ return {
19707
+ store: createRemoteStore({
19708
+ baseUrl: remote.baseUrl,
19709
+ projectId: remote.projectId,
19710
+ token: remote.token
19711
+ })
19712
+ };
17983
19713
  }
17984
- return createFileStore(resolveBundlePath(argv, process.env));
19714
+ const bundlePath = resolveBundlePath(argv, process.env);
19715
+ const qualityRoot2 = resolveQualityRoot({ bundlePath, fallback: dirname4(bundlePath) });
19716
+ return { store: createFileStore(bundlePath), qualityRoot: qualityRoot2 };
17985
19717
  }
17986
19718
  var store;
19719
+ var qualityRoot;
17987
19720
  try {
17988
- store = resolveStore();
19721
+ ({ store, qualityRoot } = resolveStore());
17989
19722
  } catch (error51) {
17990
19723
  process.stderr.write(`arkaik-mcp: ${error51.message}
17991
19724
  `);
17992
19725
  process.exit(1);
17993
19726
  }
17994
- var { tools, handlers } = buildCatalog({ store });
19727
+ var { tools, handlers } = buildCatalog({ store, qualityRoot });
17995
19728
  process.stderr.write(`arkaik-mcp v${VERSION} \u2014 ${store.describe()}
17996
19729
  `);
17997
19730
  startServer({