arkaik-mcp 0.9.0 → 0.10.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.
Files changed (2) hide show
  1. package/dist/index.js +2084 -802
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -14943,7 +14943,79 @@ var FlowPlaylistSchema = external_exports.object({
14943
14943
  entries: external_exports.array(PlaylistEntrySchema)
14944
14944
  }).meta({ id: "FlowPlaylist" });
14945
14945
 
14946
+ // ../schema/src/screenshots.ts
14947
+ var SHOT_BEARING_SPECIES = ["view", "acceptance"];
14948
+ var HTTPS = /^https:\/\/\S+$/;
14949
+ var HAS_SCHEME = /^[a-z][a-z0-9+.-]*:/i;
14950
+ var IMAGE_DATA_URI = /^data:image\/[a-z0-9.+-]+[;,]/i;
14951
+ function isValidScreenshotValue(form, value) {
14952
+ if (value === "" || /[\u0000-\u001f\u007f]/.test(value)) return false;
14953
+ switch (form) {
14954
+ case "url":
14955
+ return HTTPS.test(value);
14956
+ case "path":
14957
+ return !value.startsWith("/") && !HAS_SCHEME.test(value) && !/(^|\/)\.\.(\/|$)/.test(value);
14958
+ case "data":
14959
+ return IMAGE_DATA_URI.test(value);
14960
+ }
14961
+ }
14962
+ function isRecord(value) {
14963
+ return typeof value === "object" && value !== null && !Array.isArray(value);
14964
+ }
14965
+ function readSlot(node, platform) {
14966
+ const md = isRecord(node.metadata) ? node.metadata : {};
14967
+ const shots = isRecord(md.platformScreenshots) ? md.platformScreenshots : {};
14968
+ const metas = isRecord(md.platformScreenshotMeta) ? md.platformScreenshotMeta : {};
14969
+ const meta3 = isRecord(metas[platform]) ? metas[platform] : {};
14970
+ const rawValue = shots[platform];
14971
+ const value = typeof rawValue === "string" ? rawValue : void 0;
14972
+ const rawOrder = meta3.ci_order;
14973
+ const ciOrder = typeof rawOrder === "number" ? rawOrder : void 0;
14974
+ return { value, ciOrder };
14975
+ }
14976
+ function decideScreenshot(node, input) {
14977
+ if (!node) return { kind: "refuse", code: "node_not_found", message: `Node ${input.node_id} not found` };
14978
+ if (!SHOT_BEARING_SPECIES.includes(node.species)) {
14979
+ return { kind: "refuse", code: "not_shot_bearing", message: `${node.id} is a ${node.species}; only views and acceptances carry screenshots` };
14980
+ }
14981
+ if (!node.platforms.includes(input.platform)) {
14982
+ return {
14983
+ kind: "refuse",
14984
+ code: "platform_not_applicable",
14985
+ message: `${input.platform} is not a platform of ${node.id} (${node.platforms.length > 0 ? `lists: ${node.platforms.join(", ")}` : "lists none"})`
14986
+ };
14987
+ }
14988
+ if (!isValidScreenshotValue(input.form, input.value)) {
14989
+ return { kind: "refuse", code: "invalid_screenshot", message: `value is not a well-formed ${input.form} screenshot` };
14990
+ }
14991
+ if (input.source === "ci" && (typeof input.order !== "number" || !Number.isInteger(input.order) || input.order < 0)) {
14992
+ return { kind: "refuse", code: "invalid_screenshot", message: "a ci screenshot needs a non-negative integer order" };
14993
+ }
14994
+ const slot = readSlot(node, input.platform);
14995
+ if (input.source === "ci" && slot.ciOrder !== void 0 && typeof input.order === "number" && input.order < slot.ciOrder) {
14996
+ return { kind: "skip", reason: "stale_order" };
14997
+ }
14998
+ if (slot.value === input.value) return { kind: "skip", reason: "unchanged" };
14999
+ return { kind: "apply" };
15000
+ }
15001
+ function reduceScreenshotSlots(ordered) {
15002
+ const slots = /* @__PURE__ */ new Map();
15003
+ for (const ev of ordered) {
15004
+ if (ev.type !== "screenshot.recorded" && ev.type !== "screenshot.removed") continue;
15005
+ if (typeof ev.node_id !== "string" || typeof ev.platform !== "string") continue;
15006
+ let byPlatform = slots.get(ev.node_id);
15007
+ if (!byPlatform) {
15008
+ byPlatform = /* @__PURE__ */ new Map();
15009
+ slots.set(ev.node_id, byPlatform);
15010
+ }
15011
+ byPlatform.set(ev.platform, ev.type === "screenshot.removed" ? null : ev);
15012
+ }
15013
+ return slots;
15014
+ }
15015
+
14946
15016
  // ../schema/src/journal.ts
15017
+ var SCREENSHOT_SOURCES = ["ci", "manual"];
15018
+ var SCREENSHOT_FORMS = ["url", "path", "data"];
14947
15019
  function orderEvents(events) {
14948
15020
  const key = (v) => typeof v === "string" ? v : "";
14949
15021
  return [...events].sort((a, b) => {
@@ -15013,9 +15085,14 @@ var NODE_REF_FIELDS = {
15013
15085
  "ref.added": ["node_id"],
15014
15086
  "ref.removed": ["node_id"],
15015
15087
  "ref.status_changed": ["node_id"],
15088
+ "screenshot.recorded": ["node_id"],
15089
+ "screenshot.removed": ["node_id"],
15016
15090
  "idea.proposed": ["node_id"],
15017
15091
  "request.filed": ["node_id"]
15018
15092
  };
15093
+ function isRecord2(value) {
15094
+ return typeof value === "object" && value !== null && !Array.isArray(value);
15095
+ }
15019
15096
  function statusesAgree(last, snapshot) {
15020
15097
  if (last === snapshot) return true;
15021
15098
  if (typeof snapshot !== "string") return false;
@@ -15196,6 +15273,41 @@ function crossCheckJournal(bundle) {
15196
15273
  });
15197
15274
  }
15198
15275
  }
15276
+ const slots = reduceScreenshotSlots(ordered);
15277
+ nodesRaw.forEach((n, index) => {
15278
+ const nodeId = str(n?.id);
15279
+ if (nodeId === void 0) return;
15280
+ const metadata = isRecord2(n.metadata) ? n.metadata : {};
15281
+ const shots = isRecord2(metadata.platformScreenshots) ? metadata.platformScreenshots : {};
15282
+ const eventSlots = slots.get(nodeId);
15283
+ const platforms = /* @__PURE__ */ new Set([...Object.keys(shots), ...eventSlots ? eventSlots.keys() : []]);
15284
+ for (const platform of platforms) {
15285
+ const last = eventSlots?.get(platform);
15286
+ if (last === void 0) continue;
15287
+ const slot = typeof shots[platform] === "string" ? shots[platform] : void 0;
15288
+ let says;
15289
+ let agrees;
15290
+ if (last === null) {
15291
+ agrees = slot === void 0;
15292
+ says = "it was removed";
15293
+ } else if (last.form === "data") {
15294
+ agrees = slot !== void 0;
15295
+ says = "a data URI was recorded";
15296
+ } else {
15297
+ const url2 = str(last.url);
15298
+ agrees = slot === url2;
15299
+ says = url2 === void 0 ? "an unknown value was recorded" : `"${url2}" was recorded`;
15300
+ }
15301
+ if (!agrees) {
15302
+ findings.push({
15303
+ path: `nodes[${index}].metadata.platformScreenshots.${platform}`,
15304
+ rule: "screenshot-untracked",
15305
+ message: `Node "${nodeId}": platformScreenshots.${platform} is ${slot === void 0 ? "empty" : `"${slot}"`} but the journal's last screenshot event says ${says} \u2014 write screenshots through record_screenshot, not update_node.`,
15306
+ severity: "warning"
15307
+ });
15308
+ }
15309
+ }
15310
+ });
15199
15311
  return findings;
15200
15312
  }
15201
15313
  function missingProvenanceNodeIds(snapshotNodeIds, events) {
@@ -15325,6 +15437,19 @@ var RefStatusChangedEventSchema = external_exports.object({
15325
15437
  to: external_exports.string(),
15326
15438
  synced_at: external_exports.string()
15327
15439
  }).catchall(external_exports.unknown());
15440
+ var ScreenshotRecordedEventSchema = external_exports.object({
15441
+ ...envelope,
15442
+ type: external_exports.literal("screenshot.recorded"),
15443
+ node_id: external_exports.string(),
15444
+ platform: PlatformSchema,
15445
+ source: external_exports.enum(SCREENSHOT_SOURCES),
15446
+ form: external_exports.enum(SCREENSHOT_FORMS),
15447
+ url: external_exports.string().optional(),
15448
+ commit: external_exports.string().optional(),
15449
+ order: external_exports.number().int().nonnegative().optional(),
15450
+ detail: external_exports.string().optional()
15451
+ }).catchall(external_exports.unknown());
15452
+ var ScreenshotRemovedEventSchema = external_exports.object({ ...envelope, type: external_exports.literal("screenshot.removed"), node_id: external_exports.string(), platform: PlatformSchema }).catchall(external_exports.unknown());
15328
15453
  var JournalBaselineEventSchema = external_exports.object({ ...envelope, type: external_exports.literal("journal.baseline"), node_ids: external_exports.array(external_exports.string()) }).catchall(external_exports.unknown());
15329
15454
  var QualityAuditCompletedEventSchema = external_exports.object({
15330
15455
  ...envelope,
@@ -15411,6 +15536,8 @@ var JOURNAL_EVENT_SCHEMAS = {
15411
15536
  "ref.added": RefAddedEventSchema,
15412
15537
  "ref.removed": RefRemovedEventSchema,
15413
15538
  "ref.status_changed": RefStatusChangedEventSchema,
15539
+ "screenshot.recorded": ScreenshotRecordedEventSchema,
15540
+ "screenshot.removed": ScreenshotRemovedEventSchema,
15414
15541
  "journal.baseline": JournalBaselineEventSchema,
15415
15542
  "quality.audit.completed": QualityAuditCompletedEventSchema,
15416
15543
  "quality.assessment.scored": QualityAssessmentScoredEventSchema,
@@ -15434,6 +15561,8 @@ var KnownJournalEventSchema = external_exports.union([
15434
15561
  RefAddedEventSchema,
15435
15562
  RefRemovedEventSchema,
15436
15563
  RefStatusChangedEventSchema,
15564
+ ScreenshotRecordedEventSchema,
15565
+ ScreenshotRemovedEventSchema,
15437
15566
  JournalBaselineEventSchema,
15438
15567
  QualityAuditCompletedEventSchema,
15439
15568
  QualityAssessmentScoredEventSchema,
@@ -15443,234 +15572,1160 @@ var KnownJournalEventSchema = external_exports.union([
15443
15572
  QualitySignalTrippedEventSchema
15444
15573
  ]);
15445
15574
 
15446
- // ../schema/src/quality-schemas.ts
15447
- var GradeSchema = external_exports.enum(["A", "B", "C", "D", "E"]);
15448
- var KritikScalesSchema = external_exports.object({
15449
- grades: external_exports.partialRecord(GradeSchema, external_exports.number()).optional(),
15450
- severity_buckets: external_exports.partialRecord(external_exports.enum(["critical", "high", "medium", "low", "info"]), external_exports.tuple([external_exports.number(), external_exports.number()])).optional(),
15451
- caps: external_exports.object({ critical_open: GradeSchema.optional(), high_open: GradeSchema.optional() }).catchall(external_exports.unknown()).optional()
15452
- }).catchall(external_exports.unknown()).meta({
15453
- id: "KritikScales",
15454
- 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)."
15455
- });
15456
- 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)." });
15457
- var KritikIssueTemplateSchema = external_exports.object({
15458
- title_template: external_exports.string().optional(),
15459
- labels: external_exports.array(external_exports.string()).optional(),
15460
- body_skeleton: external_exports.string().optional()
15461
- }).catchall(external_exports.unknown()).meta({ id: "KritikIssueTemplate", description: "Per-criterion issue skeleton \u2014 what `arkaik kritik issue` prefills." });
15462
- 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." });
15463
- var KritikCriterionSchema = external_exports.object({
15464
- id: external_exports.string().meta({ description: "Stable identifier, `<DOMAIN>-NN`. Never redefined \u2014 retired via superseded_by." }),
15465
- domain: external_exports.string(),
15466
- subcategory: external_exports.string().optional(),
15467
- name: external_exports.string().optional(),
15468
- question: external_exports.string().optional(),
15469
- definition: external_exports.string().optional(),
15470
- rationale: external_exports.string().optional(),
15471
- applies_to: external_exports.array(external_exports.string()).optional().meta({ description: "Surface ids where the criterion is meaningful; absence means N/A." }),
15472
- level_anchors: external_exports.record(external_exports.string(), external_exports.string()).optional().meta({ description: "Observable descriptions per maturity level, keyed l0\u2026l4." }),
15473
- default_impact: external_exports.number().optional(),
15474
- weight: external_exports.number().optional().meta({ description: "Weight in the domain roll-up (1\u20133; 3 = load-bearing). Absent means 1." }),
15475
- references: external_exports.array(KritikReferenceSchema).optional(),
15476
- checklist: external_exports.array(external_exports.string()).optional(),
15477
- signals: external_exports.array(external_exports.string()).optional().meta({ description: "Mechanically checkable monitoring hooks run between audits." }),
15478
- remediation: external_exports.string().optional(),
15479
- issue: KritikIssueTemplateSchema.optional(),
15480
- superseded_by: external_exports.string().optional()
15481
- }).catchall(external_exports.unknown()).meta({ id: "KritikCriterion", description: "The atomic auditable unit (packages/kritik-library/SPEC.md \xA7 5)." });
15482
- var KritikLibrarySchema = external_exports.object({
15483
- version: external_exports.string().meta({ description: "Semver of the pack; matrices are comparable only within a major." }),
15484
- domains: external_exports.array(KritikDomainSchema),
15485
- criteria: external_exports.array(KritikCriterionSchema),
15486
- scales: KritikScalesSchema.optional()
15487
- }).catchall(external_exports.unknown()).meta({
15488
- id: "KritikLibrary",
15489
- description: "A versioned criteria pack. Embedded on export; repos may instead pin it as a sidecar file."
15490
- });
15491
- var SurfaceDefSchema = external_exports.object({
15492
- id: external_exports.string(),
15493
- title: external_exports.string(),
15494
- platform: PlatformSchema.optional().meta({
15495
- description: "Optional bridge to PLATFORM_IDS where a surface is also a view-shipping platform. Surfaces are not platforms (RFC \xA7 2)."
15496
- }),
15497
- path: external_exports.string().optional()
15498
- }).catchall(external_exports.unknown()).meta({ id: "SurfaceDef", description: "One independently assessable body of code \u2014 an audit target, chosen at install." });
15499
- var QualityProfileSchema = external_exports.object({
15500
- surfaces: external_exports.array(SurfaceDefSchema),
15501
- domain_weights: external_exports.record(external_exports.string(), external_exports.number()).optional().meta({
15502
- description: "Per-domain weight in the surface roll-up, keyed by domain code. A missing weight is 1."
15503
- })
15504
- }).catchall(external_exports.unknown()).meta({ id: "QualityProfile", description: "The project's parameterization of the pack (RFC \xA7 6)." });
15505
- var QualityAssessmentSchema = external_exports.object({
15506
- criterion_id: external_exports.string(),
15507
- surface: external_exports.string(),
15508
- 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({
15509
- description: "Maturity 0\u20134. N/A is the absence of the row, never a level."
15510
- }),
15511
- evidence: external_exports.string().meta({ description: "file:line / config citations. A score without evidence is an opinion, not an assessment." }),
15512
- audit_id: external_exports.string(),
15513
- commit: external_exports.string().optional(),
15514
- ts: external_exports.string()
15515
- }).catchall(external_exports.unknown()).meta({ id: "QualityAssessment", description: "One (criterion \xD7 surface) score \u2014 latest wins; history lives in the journal." });
15516
- var QualityFindingSchema = external_exports.object({
15517
- id: external_exports.string(),
15518
- criterion_id: external_exports.string(),
15519
- surface: external_exports.string(),
15520
- title: external_exports.string(),
15521
- detail: external_exports.string(),
15522
- evidence: external_exports.string(),
15523
- impact: external_exports.number().meta({ description: "Worst plausible consequence, 1\u20135." }),
15524
- likelihood: external_exports.number().meta({ description: "Probability it materializes, 1\u20135." }),
15525
- cost: external_exports.enum(["S", "M", "L", "XL"]),
15526
- status: external_exports.enum(["open", "resolved", "refuted", "accepted-risk"]),
15527
- remediation: external_exports.string().optional(),
15528
- node_ids: external_exports.array(external_exports.string()).optional().meta({ description: "Graph nodes this finding is about \u2014 the tie deliverable.shipped already uses." }),
15529
- issue_url: external_exports.string().optional(),
15530
- commit: external_exports.string().optional().meta({
15531
- 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."
15532
- }),
15533
- 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." })
15534
- }).catchall(external_exports.unknown()).meta({
15535
- id: "QualityFinding",
15536
- 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."
15537
- });
15538
- var QualitySectionSchema = external_exports.object({
15539
- framework_version: external_exports.string(),
15540
- library: KritikLibrarySchema.optional(),
15541
- profile: QualityProfileSchema,
15542
- assessments: external_exports.array(QualityAssessmentSchema),
15543
- findings: external_exports.array(QualityFindingSchema)
15544
- }).catchall(external_exports.unknown()).meta({
15545
- id: "QualitySection",
15546
- 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."
15547
- });
15548
-
15549
- // ../schema/src/bundle.ts
15550
- var PlatformStatusMapSchema = external_exports.partialRecord(
15551
- PlatformSchema,
15552
- // legacy-tolerant: migrateStatusVocabulary normalizes on load
15553
- AnyStatusSchema
15554
- ).meta({ id: "PlatformStatusMap", description: "Per-platform status overrides for view nodes." });
15555
- var PlatformNotesMapSchema = external_exports.partialRecord(
15556
- PlatformSchema,
15557
- external_exports.string()
15558
- ).meta({ id: "PlatformNotesMap", description: "Freeform per-platform notes." });
15559
- var PlatformScreenshotsMapSchema = external_exports.partialRecord(
15560
- PlatformSchema,
15561
- external_exports.string()
15562
- ).meta({
15563
- id: "PlatformScreenshotsMap",
15564
- description: "Per-platform screenshot: a relative path, an absolute URL, or a data URI (see docs/spec/bundle-format.md \xA7 Asset Values)."
15565
- });
15566
- var RefSchema = external_exports.object({
15567
- id: external_exports.string().meta({ description: 'Unique within the node, kebab-case (e.g. "gh-142").' }),
15568
- type: external_exports.string().meta({
15569
- description: "Ref type: figma | github-issue | gitlab-issue | linear-issue | github-pr | gitlab-mr | url. Unrecognized values are preserved and render as generic links."
15570
- }),
15571
- url: external_exports.string().meta({ description: "Canonical external URL." }),
15572
- title: external_exports.string().optional().meta({ description: "Display label." }),
15573
- external_status: external_exports.string().optional().meta({
15574
- description: 'Mirrored external state, verbatim (e.g. "open", "merged", "In Progress").'
15575
- }),
15576
- // legacy-tolerant: migrateStatusVocabulary normalizes on load
15577
- status_mapped: AnyStatusSchema.optional().meta({
15578
- description: "Optional mapping of external_status into the arkaik lifecycle. Advisory display data \u2014 never mutates node.status."
15579
- }),
15580
- platform: PlatformSchema.optional().meta({ description: "Optional scoping to one platform variant." }),
15581
- synced_at: external_exports.string().optional().meta({ description: "ISO 8601 \u2014 when external_status was last mirrored." })
15582
- }).meta({ id: "Ref", description: "A typed external reference on a node (docs/spec/bundle-format.md \xA7 References)." });
15583
- var NodeMetadataSchema = external_exports.object({
15584
- stage: external_exports.string().optional(),
15585
- blocked_by: external_exports.string().optional().meta({
15586
- description: "Non-empty = blocked at the current status. A node id (rendered as a link) or free text naming the dependency."
15587
- }),
15588
- playlist: FlowPlaylistSchema.optional(),
15589
- platformNotes: PlatformNotesMapSchema.optional(),
15590
- platformStatuses: PlatformStatusMapSchema.optional(),
15591
- platformScreenshots: PlatformScreenshotsMapSchema.optional(),
15592
- refs: external_exports.array(RefSchema).optional().meta({ description: "Typed external references on the node." }),
15593
- gherkin: external_exports.string().optional().meta({
15594
- description: "Acceptance nodes only: exactly one Given/When/Then scenario (the How). A second scenario is a second acceptance node."
15595
- }),
15596
- values: external_exports.array(ValueSchema).optional().meta({
15597
- description: "Acceptance nodes only: 1..n Bain value elements served (the Why)."
15598
- }),
15599
- product: external_exports.string().optional().meta({
15600
- description: "Product membership (docs/spec/bundle-format.md \xA7 Products); flow, view, and acceptance only."
15601
- }),
15602
- decision_status: DecisionStatusSchema.optional().meta({
15603
- description: "Decision nodes only: proposed | approved | enacted | rejected | deprecated | superseded. The node's lifecycle status is kept in sync (spec \xA72)."
15604
- }),
15605
- context: external_exports.string().optional().meta({
15606
- description: "Decision nodes only: Context \u2014 the Why (markdown)."
15607
- }),
15608
- consequences: external_exports.string().optional().meta({
15609
- description: "Decision nodes only: Consequences \u2014 the How (markdown)."
15610
- }),
15611
- decided_at: external_exports.string().optional().meta({
15612
- description: "Decision nodes only: ISO 8601 date the decision was made."
15613
- })
15614
- }).catchall(external_exports.unknown()).meta({ id: "NodeMetadata", description: "Optional metadata for a node." });
15615
- var NodeSchema = external_exports.object({
15616
- id: external_exports.string().meta({ description: "Unique node ID. Convention: prefix with species \u2014 F- (flow), V- (view), DM- (data-model), API- (api-endpoint)." }),
15617
- project_id: external_exports.string().meta({ description: "Must match project.id." }),
15618
- species: SpeciesSchema,
15619
- title: external_exports.string().meta({ description: "Human-readable node title." }),
15620
- description: external_exports.string().optional().meta({ description: "Optional description of the node's purpose." }),
15621
- // legacy-tolerant: migrateStatusVocabulary normalizes on load
15622
- status: AnyStatusSchema,
15623
- platforms: external_exports.array(PlatformSchema).meta({ description: "One or more target platforms." }),
15624
- metadata: NodeMetadataSchema.optional()
15625
- }).meta({ id: "Node" });
15626
- var EdgeSchema = external_exports.object({
15627
- id: external_exports.string().meta({ description: "Unique edge ID. Convention: e-{source_id}-{target_id}." }),
15628
- project_id: external_exports.string().meta({ description: "Must match project.id." }),
15629
- source_id: external_exports.string().meta({ description: "ID of the source node." }),
15630
- target_id: external_exports.string().meta({ description: "ID of the target node." }),
15631
- edge_type: EdgeTypeSchema,
15632
- metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().meta({ description: "Optional edge metadata." })
15633
- }).meta({ id: "Edge" });
15634
- var MapDisplayOptionsSchema = external_exports.object({
15635
- images: external_exports.boolean().optional().meta({ description: "Screenshot (or cover) art on view cards." }),
15636
- flow_platforms: external_exports.string().optional().meta({
15637
- description: "A flow card's platform delivery: rings (default) | bars."
15638
- }),
15639
- view_platforms: external_exports.string().optional().meta({
15640
- description: "A view card's platform availability: chips (default) | rows."
15641
- }),
15642
- minimap_color: external_exports.string().optional().meta({
15643
- description: "What a minimap node's fill encodes: status (default) | species."
15644
- })
15645
- }).catchall(external_exports.unknown()).meta({ id: "MapDisplayOptions", description: "How a map draws its cards (docs/spec/maps.md \xA7 Display Options)." });
15646
- var MapDefinitionSchema = external_exports.object({
15647
- id: external_exports.string().meta({
15648
- description: "Kebab-case, unique within the project; built-in ids (journey, system) are reserved."
15649
- }),
15650
- title: external_exports.string().meta({ description: "Display title." }),
15651
- description: external_exports.string().optional().meta({ description: "What this map is for." }),
15652
- kind: external_exports.string().meta({
15653
- description: "Map kind: journey | system. Selects the renderer and selection defaults; unrecognized kinds are preserved and listed as unrenderable."
15654
- }),
15655
- species: external_exports.array(external_exports.string()).optional().meta({
15656
- description: "Node filter; defaults by kind (journey: flow+view; system: view+api-endpoint+data-model)."
15657
- }),
15658
- edge_types: external_exports.array(external_exports.string()).optional().meta({
15659
- description: "Edge filter; defaults by kind (journey: composes; system: calls+displays+queries)."
15660
- }),
15661
- root_node_id: external_exports.string().optional().meta({
15662
- description: "Scope anchor: the subgraph is the undirected neighborhood reachable from this node."
15663
- }),
15664
- product: external_exports.string().optional().meta({ description: "Product scope; absent = every product." }),
15665
- depth: external_exports.number().optional().meta({ description: "Traversal bound from the root; absent = unbounded." }),
15666
- layout: external_exports.object({ direction: external_exports.string().optional() }).catchall(external_exports.unknown()).optional().meta({ description: "Renderer layout hints (e.g. direction: DOWN | RIGHT)." }),
15667
- display: MapDisplayOptionsSchema.optional().meta({
15668
- description: "Card rendering; the human twin is project.metadata.map_display[id]."
15669
- })
15670
- }).catchall(external_exports.unknown()).meta({ id: "MapDefinition", description: "A stored map definition (docs/spec/maps.md \xA7 MapDefinition)." });
15671
- var ProductDefinitionSchema = external_exports.object({
15672
- id: external_exports.string().meta({ description: "Kebab-case, unique within the project." }),
15673
- title: external_exports.string().meta({ description: "Display title." }),
15575
+ // ../schema/src/quality.ts
15576
+ var asArray = (value) => Array.isArray(value) ? value : [];
15577
+ var MATURITY_LEVELS = [0, 1, 2, 3, 4];
15578
+ var FINDING_SEVERITIES = ["critical", "high", "medium", "low", "info"];
15579
+ var REMEDIATION_COSTS = ["S", "M", "L", "XL"];
15580
+ var FINDING_STATUSES = ["open", "resolved", "refuted", "accepted-risk"];
15581
+ var QUALITY_GRADES = ["A", "B", "C", "D", "E"];
15582
+ var DEFAULT_GRADE_BANDS = { A: 85, B: 70, C: 55, D: 40, E: 0 };
15583
+ var DEFAULT_SEVERITY_BUCKETS = {
15584
+ critical: [20, 25],
15585
+ high: [12, 19],
15586
+ medium: [6, 11],
15587
+ low: [2, 5],
15588
+ info: [1, 1]
15589
+ };
15590
+ var DEFAULT_CAPS = {
15591
+ critical_open: "D",
15592
+ high_open: "B"
15593
+ };
15594
+ var CROSS_SURFACE_ID = "cross-surface";
15595
+ function mergeKritikLibrary(pack, overlay) {
15596
+ if (!overlay || typeof overlay !== "object") return pack;
15597
+ const domains = [...asArray(pack.domains)];
15598
+ for (const domain2 of asArray(overlay.domains)) {
15599
+ if (typeof domain2?.code !== "string" || domain2.code === "") continue;
15600
+ const at = domains.findIndex((existing) => existing?.code === domain2.code);
15601
+ if (at >= 0) domains[at] = domain2;
15602
+ else domains.push(domain2);
15603
+ }
15604
+ const criteria = [...asArray(pack.criteria)];
15605
+ for (const criterion of asArray(overlay.criteria)) {
15606
+ if (typeof criterion?.id !== "string" || criterion.id === "") continue;
15607
+ const at = criteria.findIndex((existing) => existing?.id === criterion.id);
15608
+ if (at >= 0) criteria[at] = criterion;
15609
+ else criteria.push(criterion);
15610
+ }
15611
+ const scales = pack.scales || overlay.scales ? { ...pack.scales ?? {}, ...overlay.scales ?? {} } : void 0;
15612
+ return { ...pack, domains, criteria, ...scales ? { scales } : {} };
15613
+ }
15614
+ function applicableCells(library, surfaces) {
15615
+ const selected = surfaces.filter((id) => id !== CROSS_SURFACE_ID);
15616
+ const cells = [];
15617
+ for (const criterion of asArray(library.criteria)) {
15618
+ if (typeof criterion?.id !== "string" || criterion.id === "") continue;
15619
+ if (typeof criterion.superseded_by === "string" && criterion.superseded_by !== "") continue;
15620
+ const appliesTo = Array.isArray(criterion.applies_to) ? criterion.applies_to : void 0;
15621
+ const matched = appliesTo === void 0 ? [...selected] : selected.filter((id) => appliesTo.includes(id));
15622
+ if (matched.length > 0) cells.push({ criterion_id: criterion.id, surfaces: matched });
15623
+ }
15624
+ return cells;
15625
+ }
15626
+ function bucketsOf(library) {
15627
+ const stored = library?.scales?.severity_buckets;
15628
+ const out = { ...DEFAULT_SEVERITY_BUCKETS };
15629
+ if (!stored || typeof stored !== "object") return out;
15630
+ for (const severity of FINDING_SEVERITIES) {
15631
+ const band = stored[severity];
15632
+ if (Array.isArray(band) && typeof band[0] === "number" && typeof band[1] === "number") {
15633
+ out[severity] = [band[0], band[1]];
15634
+ }
15635
+ }
15636
+ return out;
15637
+ }
15638
+ function bandsOf(library) {
15639
+ const stored = library?.scales?.grades;
15640
+ const out = { ...DEFAULT_GRADE_BANDS };
15641
+ if (!stored || typeof stored !== "object") return out;
15642
+ for (const grade of QUALITY_GRADES) {
15643
+ const min = stored[grade];
15644
+ if (typeof min === "number" && Number.isFinite(min)) out[grade] = min;
15645
+ }
15646
+ return out;
15647
+ }
15648
+ function capsOf(library) {
15649
+ const stored = library?.scales?.caps;
15650
+ const pick2 = (value, fallback) => typeof value === "string" && QUALITY_GRADES.includes(value) ? value : fallback;
15651
+ return {
15652
+ critical_open: pick2(stored?.critical_open, DEFAULT_CAPS.critical_open),
15653
+ high_open: pick2(stored?.high_open, DEFAULT_CAPS.high_open)
15654
+ };
15655
+ }
15656
+ function severityOf(finding, library) {
15657
+ const impact = typeof finding.impact === "number" ? finding.impact : 0;
15658
+ const likelihood = typeof finding.likelihood === "number" ? finding.likelihood : 0;
15659
+ const score = impact * likelihood;
15660
+ const buckets = bucketsOf(library);
15661
+ const worstFirst = [...FINDING_SEVERITIES].sort((a, b) => buckets[b][0] - buckets[a][0]);
15662
+ for (const severity of worstFirst) {
15663
+ if (score >= buckets[severity][0]) return severity;
15664
+ }
15665
+ return "info";
15666
+ }
15667
+ function priorityOf(finding, library) {
15668
+ const severity = severityOf(finding, library);
15669
+ const cheap = finding.cost === "S";
15670
+ if (severity === "critical") return "P0";
15671
+ if (severity === "high") return cheap ? "P0" : "P1";
15672
+ if (severity === "medium") return cheap ? "P1" : "P2";
15673
+ if (severity === "low") return cheap ? "P2" : "P3";
15674
+ return "P3";
15675
+ }
15676
+ function gradeOf(score, library) {
15677
+ const bands = bandsOf(library);
15678
+ const bestFirst = [...QUALITY_GRADES].sort((a, b) => bands[b] - bands[a]);
15679
+ for (const grade of bestFirst) {
15680
+ if (score >= bands[grade]) return grade;
15681
+ }
15682
+ return "E";
15683
+ }
15684
+ function capGrade(grade, cap) {
15685
+ return QUALITY_GRADES[Math.max(QUALITY_GRADES.indexOf(grade), QUALITY_GRADES.indexOf(cap))];
15686
+ }
15687
+ function isOpenFinding(finding) {
15688
+ return (finding.status ?? "open") === "open";
15689
+ }
15690
+ function rollUpSurface(scores, weights) {
15691
+ let weighted = 0;
15692
+ let total = 0;
15693
+ for (const domain2 of Object.keys(scores)) {
15694
+ const score = scores[domain2];
15695
+ if (typeof score !== "number" || !Number.isFinite(score)) continue;
15696
+ const weight = typeof weights?.[domain2] === "number" ? weights[domain2] : 1;
15697
+ weighted += score * weight;
15698
+ total += weight;
15699
+ }
15700
+ return total > 0 ? Math.round(weighted / total) : null;
15701
+ }
15702
+ function resolveKritikLibrary(section, library) {
15703
+ const explicit = library ?? section?.library;
15704
+ if (explicit && Array.isArray(explicit.criteria) && Array.isArray(explicit.domains)) return explicit;
15705
+ if (!section) return void 0;
15706
+ const ids = /* @__PURE__ */ new Set();
15707
+ for (const row of [...asArray(section.assessments), ...asArray(section.findings)]) {
15708
+ if (typeof row?.criterion_id === "string" && row.criterion_id !== "") ids.add(row.criterion_id);
15709
+ }
15710
+ if (ids.size === 0) return void 0;
15711
+ const domainOf = (id) => id.includes("-") ? id.slice(0, id.lastIndexOf("-")) : id;
15712
+ const criteria = [...ids].sort().map((id) => ({ id, domain: domainOf(id), weight: 1 }));
15713
+ const domains = [...new Set(criteria.map((c) => c.domain))].sort().map((code) => ({ code, name: code }));
15714
+ return { version: explicit?.version ?? "unknown", domains, criteria, scales: explicit?.scales };
15715
+ }
15716
+ function deriveQualityMatrix(bundle, library) {
15717
+ const section = bundle.quality;
15718
+ const pack = resolveKritikLibrary(section, library);
15719
+ const assessments = asArray(section?.assessments);
15720
+ const findings = asArray(section?.findings);
15721
+ const openFindings = findings.filter((finding) => isOpenFinding(finding));
15722
+ const declared2 = asArray(section?.profile?.surfaces).map((surface) => surface?.id).filter((id) => typeof id === "string" && id !== "");
15723
+ const surfaces = declared2.length > 0 ? [...new Set(declared2)] : [...new Set(assessments.map((a) => a.surface).filter((id) => typeof id === "string" && id !== ""))].sort();
15724
+ const domains = asArray(pack?.domains).map((domain2) => domain2?.code).filter((code) => typeof code === "string" && code !== "");
15725
+ const domainOfCriterion = /* @__PURE__ */ new Map();
15726
+ const weightOfCriterion = /* @__PURE__ */ new Map();
15727
+ for (const criterion of asArray(pack?.criteria)) {
15728
+ if (typeof criterion?.id !== "string") continue;
15729
+ if (typeof criterion.domain === "string") domainOfCriterion.set(criterion.id, criterion.domain);
15730
+ weightOfCriterion.set(criterion.id, typeof criterion.weight === "number" && criterion.weight > 0 ? criterion.weight : 1);
15731
+ }
15732
+ const caps = capsOf(pack);
15733
+ const weights = section?.profile?.domain_weights;
15734
+ const matrix = {};
15735
+ for (const domain2 of domains) {
15736
+ matrix[domain2] = {};
15737
+ for (const surface of surfaces) {
15738
+ const rows = assessments.filter((a) => a.surface === surface && domainOfCriterion.get(a.criterion_id) === domain2);
15739
+ if (rows.length === 0) {
15740
+ matrix[domain2][surface] = null;
15741
+ continue;
15742
+ }
15743
+ let earned = 0;
15744
+ let available = 0;
15745
+ for (const row of rows) {
15746
+ const weight = weightOfCriterion.get(row.criterion_id) ?? 1;
15747
+ const level = typeof row.level === "number" ? Math.min(Math.max(row.level, 0), 4) : 0;
15748
+ earned += level * weight;
15749
+ available += 4 * weight;
15750
+ }
15751
+ if (available === 0) {
15752
+ matrix[domain2][surface] = null;
15753
+ continue;
15754
+ }
15755
+ const score = Math.round(earned / available * 100);
15756
+ const cellSeverities = openFindings.filter((finding) => finding.surface === surface && domainOfCriterion.get(finding.criterion_id) === domain2).map((finding) => severityOf(finding, pack));
15757
+ const banded = gradeOf(score, pack);
15758
+ let grade = banded;
15759
+ if (cellSeverities.includes("critical")) grade = capGrade(grade, caps.critical_open);
15760
+ else if (cellSeverities.includes("high")) grade = capGrade(grade, caps.high_open);
15761
+ matrix[domain2][surface] = {
15762
+ score,
15763
+ grade,
15764
+ capped: grade !== banded,
15765
+ criteria: rows.length,
15766
+ findings: {
15767
+ critical: cellSeverities.filter((s) => s === "critical").length,
15768
+ high: cellSeverities.filter((s) => s === "high").length,
15769
+ medium: cellSeverities.filter((s) => s === "medium").length,
15770
+ low: cellSeverities.filter((s) => s === "low").length
15771
+ }
15772
+ };
15773
+ }
15774
+ }
15775
+ const overall = {};
15776
+ for (const surface of surfaces) {
15777
+ const bySurface = {};
15778
+ for (const domain2 of domains) {
15779
+ const cell = matrix[domain2]?.[surface];
15780
+ if (cell) bySurface[domain2] = cell.score;
15781
+ }
15782
+ overall[surface] = rollUpSurface(bySurface, weights);
15783
+ }
15784
+ const finding_counts = { critical: 0, high: 0, medium: 0, low: 0, info: 0 };
15785
+ for (const finding of openFindings) finding_counts[severityOf(finding, pack)]++;
15786
+ return {
15787
+ framework_version: section?.framework_version,
15788
+ surfaces,
15789
+ domains,
15790
+ matrix,
15791
+ overall,
15792
+ finding_counts
15793
+ };
15794
+ }
15795
+
15796
+ // ../schema/src/quality-ops.ts
15797
+ function upsertAssessment(assessments, next) {
15798
+ const index = assessments.findIndex(
15799
+ (candidate) => candidate.criterion_id === next.criterion_id && candidate.surface === next.surface
15800
+ );
15801
+ if (index === -1) return { assessments: [...assessments, next] };
15802
+ const updated = [...assessments];
15803
+ const replaced = updated[index];
15804
+ updated[index] = next;
15805
+ return { assessments: updated, replaced };
15806
+ }
15807
+ function domainCodeOf(criterionId, library) {
15808
+ const criterion = (library?.criteria ?? []).find((candidate) => candidate.id === criterionId);
15809
+ if (typeof criterion?.domain === "string" && criterion.domain !== "") return criterion.domain;
15810
+ const dash = criterionId.indexOf("-");
15811
+ return dash > 0 ? criterionId.slice(0, dash) : criterionId;
15812
+ }
15813
+ function mintFindingId(auditId, criterionId, surface, taken, library) {
15814
+ const prefix = `F-${auditId}-${domainCodeOf(criterionId, library)}-${surface}-`;
15815
+ const used = new Set(taken);
15816
+ for (let n = 1; n < 1e3; n++) {
15817
+ const candidate = `${prefix}${String(n).padStart(2, "0")}`;
15818
+ if (!used.has(candidate)) return candidate;
15819
+ }
15820
+ throw new Error(`Kritik: exhausted finding ids for ${prefix}NN \u2014 999 findings on one cell is a data problem, not a numbering one`);
15821
+ }
15822
+ function upsertFinding(findings, next) {
15823
+ const index = findings.findIndex((candidate) => candidate.id === next.id);
15824
+ if (index === -1) return { findings: [...findings, next] };
15825
+ const updated = [...findings];
15826
+ const replaced = updated[index];
15827
+ updated[index] = next;
15828
+ return { findings: updated, replaced };
15829
+ }
15830
+ function patchFinding(findings, id, patch) {
15831
+ const index = findings.findIndex((candidate) => candidate.id === id);
15832
+ if (index === -1) return { findings: [...findings] };
15833
+ const updated = [...findings];
15834
+ const previous = updated[index];
15835
+ const finding = { ...previous, ...patch };
15836
+ updated[index] = finding;
15837
+ return { findings: updated, finding, previous };
15838
+ }
15839
+ function resolveFinding(findings, id, resolvedBy) {
15840
+ return patchFinding(findings, id, {
15841
+ status: "resolved",
15842
+ ...resolvedBy !== void 0 ? { resolved_by: resolvedBy } : {}
15843
+ });
15844
+ }
15845
+ function acceptedDetail(detail, note) {
15846
+ return `${detail}
15847
+
15848
+ Accepted risk: ${note}`.trim();
15849
+ }
15850
+ function acceptFinding(findings, id, note) {
15851
+ const existing = findings.find((candidate) => candidate.id === id);
15852
+ const detail = existing === void 0 ? note : acceptedDetail(existing.detail, note);
15853
+ return patchFinding(findings, id, { status: "accepted-risk", detail });
15854
+ }
15855
+ function fillTemplate(text, values) {
15856
+ return text.replace(/\{(\w+)\}/g, (whole, key) => values[key] ?? whole);
15857
+ }
15858
+ function renderIssue(criterion, options) {
15859
+ const { surface, finding, library } = options;
15860
+ const anchors = criterion.level_anchors ?? {};
15861
+ const level = options.level === void 0 || options.level === "" ? "" : String(options.level);
15862
+ const observed = level === "" ? "{observed_level}" : level;
15863
+ const target = options.targetLevel !== void 0 && options.targetLevel !== "" ? String(options.targetLevel) : level === "" ? "{target_level}" : String(Math.min(Number(level) + 1, 4));
15864
+ const values = {
15865
+ surface,
15866
+ observed_level: observed,
15867
+ target_level: target,
15868
+ observed_level_name: anchors[`l${observed}`] ?? "{observed_level_name}",
15869
+ target_level_name: anchors[`l${target}`] ?? "{target_level_name}",
15870
+ target_anchor_text: anchors[`l${target}`] ?? "{target_anchor_text}",
15871
+ impact: String(finding?.impact ?? criterion.default_impact ?? 3)
15872
+ };
15873
+ if (finding !== void 0) {
15874
+ values.likelihood = String(finding.likelihood);
15875
+ values.evidence_bullets_with_file_paths = finding.evidence;
15876
+ values.risk_narrative = finding.detail;
15877
+ if (typeof finding.remediation === "string" && finding.remediation !== "") {
15878
+ values.remediation_step_1 = finding.remediation;
15879
+ }
15880
+ }
15881
+ const issue2 = criterion.issue ?? {};
15882
+ const labels = [.../* @__PURE__ */ new Set([...issue2.labels ?? ["quality"], surface])];
15883
+ const body = fillTemplate(issue2.body_skeleton ?? "", values);
15884
+ return {
15885
+ title: fillTemplate(issue2.title_template ?? `[Quality] ${criterion.id} on {surface}`, values),
15886
+ labels,
15887
+ body: finding === void 0 ? body : `${body}
15888
+ ${findingFooter(finding, library)}`,
15889
+ ...typeof criterion.remediation === "string" && criterion.remediation !== "" ? { remediation: criterion.remediation } : {}
15890
+ };
15891
+ }
15892
+ function findingFooter(finding, library) {
15893
+ const lines = [
15894
+ ``,
15895
+ `---`,
15896
+ `<sub>Kritik finding \`${finding.id}\` \u2014 **${severityOf(finding, library)} / ${priorityOf(finding, library)}** (impact ${finding.impact} x likelihood ${finding.likelihood}, cost ${finding.cost})</sub>`,
15897
+ ``,
15898
+ `**Evidence**`,
15899
+ finding.evidence
15900
+ ];
15901
+ if (typeof finding.remediation === "string" && finding.remediation !== "") {
15902
+ lines.push(``, `**Remediation**`, finding.remediation);
15903
+ }
15904
+ return lines.join("\n");
15905
+ }
15906
+ function signalRunSheet(library, surfaces, filter = {}) {
15907
+ const surfaceIds = surfaces.map((surface) => surface.id).filter((id) => id !== CROSS_SURFACE_ID);
15908
+ const rows = [];
15909
+ for (const criterion of library.criteria ?? []) {
15910
+ if (criterion.superseded_by !== void 0) continue;
15911
+ if (filter.criterion !== void 0 && criterion.id !== filter.criterion) continue;
15912
+ if (filter.domain !== void 0 && criterion.domain !== filter.domain) continue;
15913
+ const signals = criterion.signals ?? [];
15914
+ if (signals.length === 0) continue;
15915
+ const appliesTo = criterion.applies_to;
15916
+ for (const surfaceId of surfaceIds) {
15917
+ if (Array.isArray(appliesTo) && !appliesTo.includes(surfaceId)) continue;
15918
+ if (filter.surface !== void 0 && surfaceId !== filter.surface) continue;
15919
+ signals.forEach((signal, index) => {
15920
+ rows.push({ criterion_id: criterion.id, surface: surfaceId, index, signal });
15921
+ });
15922
+ }
15923
+ }
15924
+ return rows;
15925
+ }
15926
+ function auditCompletedInput(matrix, meta3) {
15927
+ const scores = {};
15928
+ for (const surface of matrix.surfaces) {
15929
+ const bySurface = {};
15930
+ for (const domain2 of matrix.domains) {
15931
+ const cell = matrix.matrix[domain2]?.[surface];
15932
+ if (cell) bySurface[domain2] = cell.score;
15933
+ }
15934
+ scores[surface] = bySurface;
15935
+ }
15936
+ return {
15937
+ type: "quality.audit.completed",
15938
+ payload: {
15939
+ audit_id: meta3.audit_id,
15940
+ framework_version: meta3.framework_version,
15941
+ ...meta3.commit !== void 0 ? { commit: meta3.commit } : {},
15942
+ scores,
15943
+ counts: matrix.finding_counts,
15944
+ ...meta3.scope !== void 0 ? { scope: meta3.scope } : {}
15945
+ }
15946
+ };
15947
+ }
15948
+ function findingOpenedInput(finding, library) {
15949
+ return {
15950
+ type: "quality.finding.opened",
15951
+ payload: {
15952
+ finding_id: finding.id,
15953
+ criterion_id: finding.criterion_id,
15954
+ surface: finding.surface,
15955
+ severity: severityOf(finding, library),
15956
+ priority: priorityOf(finding, library),
15957
+ title: finding.title,
15958
+ ...finding.node_ids !== void 0 ? { node_ids: finding.node_ids } : {},
15959
+ ...finding.issue_url !== void 0 ? { issue_url: finding.issue_url } : {}
15960
+ }
15961
+ };
15962
+ }
15963
+ function findingResolvedInput(finding, resolvedBy) {
15964
+ return {
15965
+ type: "quality.finding.resolved",
15966
+ payload: {
15967
+ finding_id: finding.id,
15968
+ ...resolvedBy !== void 0 ? { resolved_by: resolvedBy } : {},
15969
+ ...finding.node_ids !== void 0 ? { node_ids: finding.node_ids } : {}
15970
+ }
15971
+ };
15972
+ }
15973
+ function signalTrippedInput(trip) {
15974
+ return {
15975
+ type: "quality.signal.tripped",
15976
+ payload: {
15977
+ criterion_id: trip.criterion_id,
15978
+ surface: trip.surface,
15979
+ signal: trip.signal,
15980
+ ...trip.commit !== void 0 ? { commit: trip.commit } : {},
15981
+ ...trip.detail !== void 0 ? { detail: trip.detail } : {}
15982
+ }
15983
+ };
15984
+ }
15985
+
15986
+ // ../schema/src/kritik-plan-prompt.ts
15987
+ var THOUSANDS = /\B(?=(\d{3})+(?!\d))/g;
15988
+ var SKILL_STEP = 'Follow the Kritik skill (SKILL.md), section "A planned partial audit". Run it in the repository checkout: a hosted session cannot score a plan part.';
15989
+ var USAGE_READOUT = "this session's usage readout: model, tokens in and out, duration, number of agents.";
15990
+ var SIGNALS_EXIT = "It exits 1 when a signal has tripped since the last recorded audit: that is information for this audit, not an error.";
15991
+ var FINDING_FLAGS = '--title "<one line>" --impact <1-5> --likelihood <1-5> --cost <S|M|L|XL> --evidence "<file:line \u2026>"';
15992
+ function planRecordCommand(planId2) {
15993
+ return `arkaik kritik matrix ${planId2} --record --plan`;
15994
+ }
15995
+ function plural(count, noun) {
15996
+ return `${count} ${noun}${count === 1 ? "" : "s"}`;
15997
+ }
15998
+ function tokenCount(value) {
15999
+ return String(Math.round(value)).replace(THOUSANDS, ",");
16000
+ }
16001
+ function dollars(value) {
16002
+ return `$${value.toFixed(2)}`;
16003
+ }
16004
+ function where(commit) {
16005
+ return commit === null ? "not a git checkout" : `commit ${commit}`;
16006
+ }
16007
+ function estimateSentence(tokens, usd, calibrated) {
16008
+ if (tokens === null) return "";
16009
+ const cost = usd === null ? "" : ` (${dollars(usd.low)}\u2013${dollars(usd.high)})`;
16010
+ return ` Estimate: ${tokenCount(tokens.low)}\u2013${tokenCount(tokens.high)} tokens${cost}${calibrated ? "" : ", uncalibrated"}.`;
16011
+ }
16012
+ function scopeSentence(cells, steps) {
16013
+ return `${plural(cells, "cell")}, ${plural(steps, "checklist step")}`;
16014
+ }
16015
+ function partSteps(part, first) {
16016
+ const audit = `--audit ${part.auditId}`;
16017
+ return [
16018
+ `${first}. Get the run sheet: \`arkaik kritik signals --domain ${part.domain} --surface ${part.surface}\`. ${SIGNALS_EXIT}`,
16019
+ `${first + 1}. Score exactly these cells and no others:`,
16020
+ ...part.cells.map(
16021
+ (cell) => ` - ${cell.criterion_id} on ${cell.surface}: \`arkaik kritik score ${cell.criterion_id} ${cell.surface} <level> --evidence "<file:line \u2026>" ${audit}\``
16022
+ ),
16023
+ `${first + 2}. Open every finding on this part's audit: \`arkaik kritik finding open <criterion> ${part.surface} ${FINDING_FLAGS} ${audit}\`. Give file-and-line evidence, and verify every Critical and High finding adversarially before you open it.`
16024
+ ];
16025
+ }
16026
+ function renderPartPrompt(plan, part) {
16027
+ const estimate = part.estimate === null ? "" : estimateSentence(part.estimate.tokens, part.estimate.usd, part.estimate.calibrated);
16028
+ return [
16029
+ `Run part ${part.domain}:${part.surface} of Kritik plan ${plan.planId} in this repo (${where(plan.commit)}).`,
16030
+ `Scope: ${scopeSentence(part.cells.length, part.steps)}.${estimate}`,
16031
+ `Audit id for this part: ${part.auditId}`,
16032
+ "",
16033
+ `1. ${SKILL_STEP}`,
16034
+ ...partSteps(part, 2),
16035
+ "5. Do not record this part. The plan is recorded once, after every part is scored, with the plan's own command.",
16036
+ `6. Finish by printing ${USAGE_READOUT}`
16037
+ ].join("\n");
16038
+ }
16039
+ function renderPlanPrompt(plan) {
16040
+ const included = plan.parts.filter((part) => part.status === "included");
16041
+ const deferred = plan.parts.filter((part) => part.status === "deferred");
16042
+ const calibrated = included.every((part) => part.estimate?.calibrated === true);
16043
+ const lines = [
16044
+ `Run Kritik plan ${plan.planId} in this repo (${where(plan.commit)}): ${plural(included.length, "part")}, one after the other, in this session.`,
16045
+ `Scope: ${scopeSentence(plan.totals.cells, plan.totals.steps)}, of ${plan.totals.applicableCells} applicable cells.` + estimateSentence(plan.totals.tokens, plan.totals.usd, calibrated),
16046
+ "",
16047
+ `1. ${SKILL_STEP} Do not record a part on its own.`
16048
+ ];
16049
+ let step = 2;
16050
+ for (const part of included) {
16051
+ lines.push(
16052
+ "",
16053
+ `Part ${part.domain}:${part.surface}, audit id ${part.auditId} (${scopeSentence(part.cells.length, part.steps)}):`,
16054
+ ...partSteps(part, step)
16055
+ );
16056
+ step += 3;
16057
+ }
16058
+ lines.push(
16059
+ "",
16060
+ `${step}. Check that every part is scored: \`arkaik kritik plan --status ${plan.planId}\``,
16061
+ `${step + 1}. Print ${USAGE_READOUT}`,
16062
+ `${step + 2}. When every part is scored, run \`${plan.recordCommand}\``
16063
+ );
16064
+ if (deferred.length > 0) {
16065
+ lines.push(
16066
+ "",
16067
+ "Not in this run (over budget):",
16068
+ ...deferred.map((part) => ` - ${part.domain}:${part.surface} (${part.auditId}). Do not score it.`)
16069
+ );
16070
+ }
16071
+ return lines.join("\n");
16072
+ }
16073
+
16074
+ // ../schema/src/quality-plan.ts
16075
+ var KRITIK_PLAN_SCHEMA = "arkaik.kritik.plan/1";
16076
+ var PLAN_PLANS_DIR = "plans";
16077
+ var SCOPED_AUDIT_ID = /-scoped(-\d+)?$/;
16078
+ var PLAN_ID = /^\d{4}-\d{2}-zplan-\d{4}$/;
16079
+ var PLAN_PART_ID = /^\d{4}-\d{2}-zplan-\d{4}-[a-z0-9]{2,5}-.+$/;
16080
+ var PLAN_ID_LENGTH = 18;
16081
+ function planCellKey(criterionId, surface) {
16082
+ return `${criterionId}::${surface}`;
16083
+ }
16084
+ function isScopedAuditId(id) {
16085
+ return typeof id === "string" && SCOPED_AUDIT_ID.test(id);
16086
+ }
16087
+ function isPlanId(id) {
16088
+ return typeof id === "string" && PLAN_ID.test(id);
16089
+ }
16090
+ function isPlanPartId(id) {
16091
+ return typeof id === "string" && PLAN_PART_ID.test(id) && !isScopedAuditId(id);
16092
+ }
16093
+ function isPartialAuditId(id) {
16094
+ return isScopedAuditId(id) || isPlanId(id) || isPlanPartId(id);
16095
+ }
16096
+ function planIdOfPartId(id) {
16097
+ return isPlanPartId(id) ? id.slice(0, PLAN_ID_LENGTH) : null;
16098
+ }
16099
+ var RUN_TOKEN = /^([A-Za-z0-9]{2,5}):([A-Za-z0-9_-]+)$/;
16100
+ var PLANNABLE_DOMAIN = /^[A-Z0-9]{2,5}$/;
16101
+ function parseRun(tokens, vocabulary) {
16102
+ if (tokens.length === 0) throw new Error("at least one --run DOMAIN:SURFACE is required");
16103
+ const surfaces = vocabulary.surfaces.filter((id) => id !== CROSS_SURFACE_ID);
16104
+ const plannable = vocabulary.domains.filter((code) => PLANNABLE_DOMAIN.test(code));
16105
+ const unplannable = vocabulary.domains.filter((code) => !PLANNABLE_DOMAIN.test(code));
16106
+ const runs = [];
16107
+ const warnings = [];
16108
+ const tokenBySuffix = /* @__PURE__ */ new Map();
16109
+ for (const token of tokens) {
16110
+ const match = RUN_TOKEN.exec(token);
16111
+ if (match === null) {
16112
+ throw new Error(
16113
+ `--run "${token}" is not DOMAIN:SURFACE \u2014 a domain code of 2 to 5 letters or digits, a colon, then a surface id of letters, digits, "-" or "_" (for example SEC:web).`
16114
+ );
16115
+ }
16116
+ const domain2 = match[1].toUpperCase();
16117
+ const surface = match[2];
16118
+ if (!plannable.includes(domain2)) {
16119
+ throw new Error(
16120
+ `--run "${token}": ${domain2} is not a domain of this library. Domain codes: ${plannable.length > 0 ? plannable.join(", ") : "none that can be planned"}.` + (unplannable.length > 0 ? ` ${unplannable.join(", ")} cannot be planned: a domain code must be 2 to 5 upper-case letters or digits.` : "")
16121
+ );
16122
+ }
16123
+ if (surface === CROSS_SURFACE_ID) {
16124
+ throw new Error(
16125
+ `--run "${token}": ${CROSS_SURFACE_ID} is a lens for findings, not a surface anything is scored on. Plan the surfaces it connects instead.`
16126
+ );
16127
+ }
16128
+ if (!surfaces.includes(surface)) {
16129
+ throw new Error(
16130
+ `--run "${token}": "${surface}" is not a surface of this project's profile. Surfaces: ${surfaces.length > 0 ? surfaces.join(", ") : "none declared"}. A surface must match its id exactly, case included.`
16131
+ );
16132
+ }
16133
+ if (runs.some((run) => run.domain === domain2 && run.surface === surface)) {
16134
+ warnings.push(`--run ${token} repeats ${domain2}:${surface}; the two are one part.`);
16135
+ continue;
16136
+ }
16137
+ const suffix = `${domain2.toLowerCase()}-${surface.toLowerCase()}`;
16138
+ const other = tokenBySuffix.get(suffix);
16139
+ if (other !== void 0) {
16140
+ throw new Error(
16141
+ `--run "${other}" and --run "${token}" name surfaces that differ only by case, so both would score into the one part id "<planId>-${suffix}". Plan one of them, or give the profile's surfaces ids that differ by more than case.`
16142
+ );
16143
+ }
16144
+ tokenBySuffix.set(suffix, token);
16145
+ runs.push({ domain: domain2, surface });
16146
+ }
16147
+ return { runs, warnings };
16148
+ }
16149
+ function planCells(library, surfaces, run) {
16150
+ const byId = /* @__PURE__ */ new Map();
16151
+ for (const criterion of Array.isArray(library.criteria) ? library.criteria : []) {
16152
+ if (typeof criterion?.id === "string" && !byId.has(criterion.id)) byId.set(criterion.id, criterion);
16153
+ }
16154
+ const cells = [];
16155
+ let steps = 0;
16156
+ for (const entry of applicableCells(library, surfaces)) {
16157
+ if (!entry.surfaces.includes(run.surface)) continue;
16158
+ if (domainCodeOf(entry.criterion_id, library) !== run.domain) continue;
16159
+ cells.push({ criterion_id: entry.criterion_id, surface: run.surface });
16160
+ const checklist = byId.get(entry.criterion_id)?.checklist;
16161
+ steps += Array.isArray(checklist) ? checklist.length : 0;
16162
+ }
16163
+ return { cells, steps };
16164
+ }
16165
+ function applicableCellCount(library, surfaces) {
16166
+ let count = 0;
16167
+ for (const entry of applicableCells(library, surfaces)) count += entry.surfaces.length;
16168
+ return count;
16169
+ }
16170
+ function planPartId(planId2, domain2, surface) {
16171
+ const id = `${planId2}-${domain2.toLowerCase()}-${surface.toLowerCase()}`;
16172
+ if (isScopedAuditId(id)) {
16173
+ throw new Error(
16174
+ `the part ${domain2}:${surface} would be named "${id}", which reads as a scoped re-audit. A surface named "scoped", or ending in "-scoped" or "-scoped-NN", cannot be planned.`
16175
+ );
16176
+ }
16177
+ return id;
16178
+ }
16179
+ function planId(input) {
16180
+ const { now, known, runs } = input;
16181
+ if (runs.length === 0) throw new Error("a plan id needs at least one run: with none, no part is checked to sort last");
16182
+ const ids = known.filter((id) => typeof id === "string" && id !== "");
16183
+ const greatest = [...ids].sort().at(-1);
16184
+ const year = String(now.getFullYear()).padStart(4, "0");
16185
+ const month = String(now.getMonth() + 1).padStart(2, "0");
16186
+ const day = String(now.getDate()).padStart(2, "0");
16187
+ for (let n = 0; n < 100; n++) {
16188
+ const candidate = `${year}-${month}-zplan-${day}${String(n).padStart(2, "0")}`;
16189
+ if (ids.some((id) => id === candidate || id.startsWith(`${candidate}-`))) continue;
16190
+ if (greatest !== void 0 && !runs.every((run) => planPartId(candidate, run.domain, run.surface) > greatest)) continue;
16191
+ return candidate;
16192
+ }
16193
+ throw new Error(`no plan id on ${year}-${month}-${day} sorts after "${greatest}"`);
16194
+ }
16195
+ function outsortedBy(partId, known) {
16196
+ const plan = planIdOfPartId(partId);
16197
+ if (plan === null) return [];
16198
+ const after = /* @__PURE__ */ new Set();
16199
+ for (const id of known) {
16200
+ if (typeof id !== "string" || !(id > partId)) continue;
16201
+ if (planIdOfPartId(id) === plan) continue;
16202
+ after.add(id);
16203
+ }
16204
+ return [...after].sort();
16205
+ }
16206
+ var isCount = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0;
16207
+ var nonEmptyStrings = (value) => Array.isArray(value) ? value.filter((item) => typeof item === "string" && item !== "") : [];
16208
+ function readCoverage(value) {
16209
+ if (typeof value !== "object" || value === null) return null;
16210
+ const row = value;
16211
+ if (!isCount(row.scored) || !isCount(row.assessed) || !isCount(row.applicable)) return null;
16212
+ const surfaces = {};
16213
+ if (typeof row.surfaces === "object" && row.surfaces !== null && !Array.isArray(row.surfaces)) {
16214
+ for (const [surface, entry] of Object.entries(row.surfaces)) {
16215
+ if (surface === "__proto__") continue;
16216
+ if (typeof entry !== "object" || entry === null) continue;
16217
+ const { assessed, applicable } = entry;
16218
+ if (isCount(assessed) && isCount(applicable)) surfaces[surface] = { assessed, applicable };
16219
+ }
16220
+ }
16221
+ return { scored: row.scored, assessed: row.assessed, applicable: row.applicable, surfaces };
16222
+ }
16223
+ function readPlanScope(scope) {
16224
+ if (typeof scope !== "object" || scope === null) return null;
16225
+ const row = scope;
16226
+ if (typeof row.plan !== "string" || row.plan === "") return null;
16227
+ return {
16228
+ plan: row.plan,
16229
+ parts: nonEmptyStrings(row.parts),
16230
+ scored: nonEmptyStrings(row.scored),
16231
+ cells: isCount(row.cells) ? row.cells : null,
16232
+ since: typeof row.since === "string" && row.since !== "" ? row.since : null,
16233
+ coverage: readCoverage(row.coverage)
16234
+ };
16235
+ }
16236
+ function buildKritikPlan(input) {
16237
+ const { library, surfaces, runs, known, now, commit } = input;
16238
+ const counted = runs.map((run) => {
16239
+ const { cells, steps } = planCells(library, surfaces, run);
16240
+ if (cells.length === 0) {
16241
+ throw new Error(
16242
+ `no ${run.domain} criterion applies to "${run.surface}" \u2014 every ${run.domain} criterion's applies_to leaves it out, so this part would score nothing.`
16243
+ );
16244
+ }
16245
+ return { run, cells, steps };
16246
+ });
16247
+ const id = planId({ now, known, runs });
16248
+ const parts = counted.map(({ run, cells, steps }) => ({
16249
+ domain: run.domain,
16250
+ surface: run.surface,
16251
+ auditId: planPartId(id, run.domain, run.surface),
16252
+ cells,
16253
+ steps,
16254
+ estimate: null,
16255
+ status: "included"
16256
+ }));
16257
+ const included = parts.filter((part) => part.status === "included");
16258
+ const head = {
16259
+ schema: KRITIK_PLAN_SCHEMA,
16260
+ planId: id,
16261
+ createdAt: now.toISOString(),
16262
+ commit,
16263
+ frameworkVersion: library.version,
16264
+ tier: null,
16265
+ budgetTokens: null,
16266
+ budgetUsd: null,
16267
+ pricePerMTok: null,
16268
+ totals: {
16269
+ cells: included.reduce((sum, part) => sum + part.cells.length, 0),
16270
+ steps: included.reduce((sum, part) => sum + part.steps, 0),
16271
+ applicableCells: applicableCellCount(library, surfaces),
16272
+ tokens: null,
16273
+ usd: null
16274
+ },
16275
+ recordCommand: planRecordCommand(id)
16276
+ };
16277
+ return {
16278
+ schema: head.schema,
16279
+ planId: head.planId,
16280
+ createdAt: head.createdAt,
16281
+ commit: head.commit,
16282
+ frameworkVersion: head.frameworkVersion,
16283
+ tier: head.tier,
16284
+ budgetTokens: head.budgetTokens,
16285
+ budgetUsd: head.budgetUsd,
16286
+ pricePerMTok: head.pricePerMTok,
16287
+ parts: parts.map((part) => ({ ...part, prompt: renderPartPrompt({ planId: id, commit }, part) })),
16288
+ totals: head.totals,
16289
+ prompt: renderPlanPrompt({ ...head, parts }),
16290
+ recordCommand: head.recordCommand
16291
+ };
16292
+ }
16293
+ function planPartStatuses(plan, scoresByPart) {
16294
+ return plan.parts.map((part) => {
16295
+ const planned = new Set(part.cells.map((cell) => planCellKey(cell.criterion_id, cell.surface)));
16296
+ const scoredKeys = /* @__PURE__ */ new Set();
16297
+ const strayKeys = /* @__PURE__ */ new Set();
16298
+ const stray = [];
16299
+ const scores = Object.prototype.hasOwnProperty.call(scoresByPart, part.auditId) ? scoresByPart[part.auditId] : [];
16300
+ for (const score of scores) {
16301
+ const key = planCellKey(score.criterion_id, score.surface);
16302
+ if (planned.has(key)) scoredKeys.add(key);
16303
+ else if (!strayKeys.has(key)) {
16304
+ strayKeys.add(key);
16305
+ stray.push({ criterion_id: score.criterion_id, surface: score.surface });
16306
+ }
16307
+ }
16308
+ const missing = part.cells.filter((cell) => !scoredKeys.has(planCellKey(cell.criterion_id, cell.surface)));
16309
+ const scored = part.cells.length - missing.length;
16310
+ const progress = part.status === "deferred" ? "deferred" : scored === 0 && stray.length === 0 ? "not started" : missing.length === 0 ? "scored" : "in progress";
16311
+ return {
16312
+ auditId: part.auditId,
16313
+ domain: part.domain,
16314
+ surface: part.surface,
16315
+ progress,
16316
+ scored,
16317
+ cells: part.cells.length,
16318
+ missing,
16319
+ stray
16320
+ };
16321
+ });
16322
+ }
16323
+ function coverageOf(section, library, scored = 0) {
16324
+ const assessments = Array.isArray(section.assessments) ? section.assessments : [];
16325
+ const listed = section.profile?.surfaces;
16326
+ const surfaces = [];
16327
+ for (const surface of Array.isArray(listed) ? listed : []) {
16328
+ const id = surface?.id;
16329
+ if (typeof id === "string" && id !== "" && id !== CROSS_SURFACE_ID && !surfaces.includes(id)) surfaces.push(id);
16330
+ }
16331
+ if (surfaces.length === 0) {
16332
+ for (const assessment of assessments) {
16333
+ const id = assessment?.surface;
16334
+ if (typeof id === "string" && id !== "" && id !== CROSS_SURFACE_ID && !surfaces.includes(id)) surfaces.push(id);
16335
+ }
16336
+ }
16337
+ const perSurface = /* @__PURE__ */ new Map();
16338
+ for (const surface of surfaces) perSurface.set(surface, { assessed: 0, applicable: 0 });
16339
+ const applicable = /* @__PURE__ */ new Set();
16340
+ for (const entry of applicableCells(library, surfaces)) {
16341
+ for (const surface of entry.surfaces) {
16342
+ const counts = perSurface.get(surface);
16343
+ if (counts === void 0) continue;
16344
+ applicable.add(planCellKey(entry.criterion_id, surface));
16345
+ counts.applicable++;
16346
+ }
16347
+ }
16348
+ const assessed = /* @__PURE__ */ new Set();
16349
+ for (const assessment of assessments) {
16350
+ if (typeof assessment?.criterion_id !== "string" || typeof assessment?.surface !== "string") continue;
16351
+ const key = planCellKey(assessment.criterion_id, assessment.surface);
16352
+ if (!applicable.has(key) || assessed.has(key)) continue;
16353
+ assessed.add(key);
16354
+ const counts = perSurface.get(assessment.surface);
16355
+ if (counts !== void 0) counts.assessed++;
16356
+ }
16357
+ const bySurface = {};
16358
+ for (const [surface, counts] of perSurface) {
16359
+ if (surface === "__proto__") continue;
16360
+ bySurface[surface] = counts;
16361
+ }
16362
+ return { scored, assessed: assessed.size, applicable: applicable.size, surfaces: bySurface };
16363
+ }
16364
+ function coverageNotes(coverage, overall) {
16365
+ const notes = [];
16366
+ const surfaces = coverage.surfaces ?? {};
16367
+ for (const surface of Object.keys(surfaces)) {
16368
+ const { assessed, applicable } = surfaces[surface];
16369
+ if (!(assessed < applicable)) continue;
16370
+ const score = Object.prototype.hasOwnProperty.call(overall, surface) ? overall[surface] : void 0;
16371
+ notes.push(`${surface} ${typeof score === "number" ? score : "\u2014"}, from ${assessed} of ${applicable} cells`);
16372
+ }
16373
+ return notes;
16374
+ }
16375
+ function auditReadings(auditIds) {
16376
+ const readings = [];
16377
+ const byId = /* @__PURE__ */ new Map();
16378
+ const lastAt = /* @__PURE__ */ new Map();
16379
+ auditIds.forEach((auditId, index) => {
16380
+ const id = planIdOfPartId(auditId) ?? auditId;
16381
+ const existing = byId.get(id);
16382
+ if (existing !== void 0) {
16383
+ existing.auditIds.push(auditId);
16384
+ lastAt.set(existing, index);
16385
+ return;
16386
+ }
16387
+ const reading = { id, auditIds: [auditId] };
16388
+ byId.set(id, reading);
16389
+ lastAt.set(reading, index);
16390
+ readings.push(reading);
16391
+ });
16392
+ return readings.sort((a, b) => (lastAt.get(a) ?? 0) - (lastAt.get(b) ?? 0));
16393
+ }
16394
+ function readingOf(readings, id) {
16395
+ return readings.find((reading) => reading.id === id) ?? readings.find((reading) => reading.auditIds.includes(id));
16396
+ }
16397
+
16398
+ // ../schema/src/quality-schemas.ts
16399
+ var GradeSchema = external_exports.enum(["A", "B", "C", "D", "E"]);
16400
+ var KritikScalesSchema = external_exports.object({
16401
+ grades: external_exports.partialRecord(GradeSchema, external_exports.number()).optional(),
16402
+ severity_buckets: external_exports.partialRecord(external_exports.enum(["critical", "high", "medium", "low", "info"]), external_exports.tuple([external_exports.number(), external_exports.number()])).optional(),
16403
+ caps: external_exports.object({ critical_open: GradeSchema.optional(), high_open: GradeSchema.optional() }).catchall(external_exports.unknown()).optional()
16404
+ }).catchall(external_exports.unknown()).meta({
16405
+ id: "KritikScales",
16406
+ 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)."
16407
+ });
16408
+ 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)." });
16409
+ var KritikIssueTemplateSchema = external_exports.object({
16410
+ title_template: external_exports.string().optional(),
16411
+ labels: external_exports.array(external_exports.string()).optional(),
16412
+ body_skeleton: external_exports.string().optional()
16413
+ }).catchall(external_exports.unknown()).meta({ id: "KritikIssueTemplate", description: "Per-criterion issue skeleton \u2014 what `arkaik kritik issue` prefills." });
16414
+ 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." });
16415
+ var KritikCriterionSchema = external_exports.object({
16416
+ id: external_exports.string().meta({ description: "Stable identifier, `<DOMAIN>-NN`. Never redefined \u2014 retired via superseded_by." }),
16417
+ domain: external_exports.string(),
16418
+ subcategory: external_exports.string().optional(),
16419
+ name: external_exports.string().optional(),
16420
+ question: external_exports.string().optional(),
16421
+ definition: external_exports.string().optional(),
16422
+ rationale: external_exports.string().optional(),
16423
+ applies_to: external_exports.array(external_exports.string()).optional().meta({ description: "Surface ids where the criterion is meaningful; absence means N/A." }),
16424
+ level_anchors: external_exports.record(external_exports.string(), external_exports.string()).optional().meta({ description: "Observable descriptions per maturity level, keyed l0\u2026l4." }),
16425
+ default_impact: external_exports.number().optional(),
16426
+ weight: external_exports.number().optional().meta({ description: "Weight in the domain roll-up (1\u20133; 3 = load-bearing). Absent means 1." }),
16427
+ references: external_exports.array(KritikReferenceSchema).optional(),
16428
+ checklist: external_exports.array(external_exports.string()).optional(),
16429
+ signals: external_exports.array(external_exports.string()).optional().meta({ description: "Mechanically checkable monitoring hooks run between audits." }),
16430
+ remediation: external_exports.string().optional(),
16431
+ issue: KritikIssueTemplateSchema.optional(),
16432
+ superseded_by: external_exports.string().optional()
16433
+ }).catchall(external_exports.unknown()).meta({ id: "KritikCriterion", description: "The atomic auditable unit (packages/kritik-library/SPEC.md \xA7 5)." });
16434
+ var KritikLibrarySchema = external_exports.object({
16435
+ version: external_exports.string().meta({ description: "Semver of the pack; matrices are comparable only within a major." }),
16436
+ domains: external_exports.array(KritikDomainSchema),
16437
+ criteria: external_exports.array(KritikCriterionSchema),
16438
+ scales: KritikScalesSchema.optional()
16439
+ }).catchall(external_exports.unknown()).meta({
16440
+ id: "KritikLibrary",
16441
+ description: "A versioned criteria pack. Embedded on export; repos may instead pin it as a sidecar file."
16442
+ });
16443
+ var SurfaceDefSchema = external_exports.object({
16444
+ id: external_exports.string(),
16445
+ title: external_exports.string(),
16446
+ platform: PlatformSchema.optional().meta({
16447
+ description: "Optional bridge to PLATFORM_IDS where a surface is also a view-shipping platform. Surfaces are not platforms (RFC \xA7 2)."
16448
+ }),
16449
+ path: external_exports.string().optional()
16450
+ }).catchall(external_exports.unknown()).meta({ id: "SurfaceDef", description: "One independently assessable body of code \u2014 an audit target, chosen at install." });
16451
+ var QualityProfileSchema = external_exports.object({
16452
+ surfaces: external_exports.array(SurfaceDefSchema),
16453
+ domain_weights: external_exports.record(external_exports.string(), external_exports.number()).optional().meta({
16454
+ description: "Per-domain weight in the surface roll-up, keyed by domain code. A missing weight is 1."
16455
+ })
16456
+ }).catchall(external_exports.unknown()).meta({ id: "QualityProfile", description: "The project's parameterization of the pack (RFC \xA7 6)." });
16457
+ var QualityAssessmentSchema = external_exports.object({
16458
+ criterion_id: external_exports.string(),
16459
+ surface: external_exports.string(),
16460
+ 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({
16461
+ description: "Maturity 0\u20134. N/A is the absence of the row, never a level."
16462
+ }),
16463
+ evidence: external_exports.string().meta({ description: "file:line / config citations. A score without evidence is an opinion, not an assessment." }),
16464
+ audit_id: external_exports.string(),
16465
+ commit: external_exports.string().optional(),
16466
+ ts: external_exports.string()
16467
+ }).catchall(external_exports.unknown()).meta({ id: "QualityAssessment", description: "One (criterion \xD7 surface) score \u2014 latest wins; history lives in the journal." });
16468
+ var QualityFindingSchema = external_exports.object({
16469
+ id: external_exports.string(),
16470
+ criterion_id: external_exports.string(),
16471
+ surface: external_exports.string(),
16472
+ title: external_exports.string(),
16473
+ detail: external_exports.string(),
16474
+ evidence: external_exports.string(),
16475
+ impact: external_exports.number().meta({ description: "Worst plausible consequence, 1\u20135." }),
16476
+ likelihood: external_exports.number().meta({ description: "Probability it materializes, 1\u20135." }),
16477
+ cost: external_exports.enum(["S", "M", "L", "XL"]),
16478
+ status: external_exports.enum(["open", "resolved", "refuted", "accepted-risk"]),
16479
+ remediation: external_exports.string().optional(),
16480
+ node_ids: external_exports.array(external_exports.string()).optional().meta({ description: "Graph nodes this finding is about \u2014 the tie deliverable.shipped already uses." }),
16481
+ issue_url: external_exports.string().optional(),
16482
+ commit: external_exports.string().optional().meta({
16483
+ 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."
16484
+ }),
16485
+ 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." })
16486
+ }).catchall(external_exports.unknown()).meta({
16487
+ id: "QualityFinding",
16488
+ 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."
16489
+ });
16490
+ var QualitySectionSchema = external_exports.object({
16491
+ framework_version: external_exports.string(),
16492
+ library: KritikLibrarySchema.optional(),
16493
+ profile: QualityProfileSchema,
16494
+ assessments: external_exports.array(QualityAssessmentSchema),
16495
+ findings: external_exports.array(QualityFindingSchema)
16496
+ }).catchall(external_exports.unknown()).meta({
16497
+ id: "QualitySection",
16498
+ 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."
16499
+ });
16500
+ var KritikPlanBandSchema = external_exports.object({
16501
+ low: external_exports.number().nonnegative(),
16502
+ mid: external_exports.number().nonnegative(),
16503
+ high: external_exports.number().nonnegative()
16504
+ });
16505
+ var KritikPlanCellSchema = external_exports.object({ criterion_id: external_exports.string(), surface: external_exports.string() });
16506
+ var KritikPlanPartSchema = external_exports.object({
16507
+ domain: external_exports.string().regex(/^[A-Z0-9]{2,5}$/),
16508
+ surface: external_exports.string().min(1),
16509
+ auditId: external_exports.string(),
16510
+ cells: external_exports.array(KritikPlanCellSchema).min(1),
16511
+ steps: external_exports.number().int().nonnegative(),
16512
+ estimate: external_exports.object({
16513
+ tokens: KritikPlanBandSchema,
16514
+ usd: KritikPlanBandSchema.nullable(),
16515
+ inputs: external_exports.object({
16516
+ P: external_exports.number(),
16517
+ B: external_exports.number(),
16518
+ c: KritikPlanBandSchema,
16519
+ q: KritikPlanBandSchema,
16520
+ h: KritikPlanBandSchema,
16521
+ V: KritikPlanBandSchema
16522
+ }),
16523
+ calibrated: external_exports.boolean()
16524
+ }).nullable(),
16525
+ status: external_exports.enum(["included", "deferred"]),
16526
+ prompt: external_exports.string()
16527
+ });
16528
+ var KritikPlanSchema = external_exports.object({
16529
+ schema: external_exports.literal(KRITIK_PLAN_SCHEMA),
16530
+ planId: external_exports.string(),
16531
+ createdAt: external_exports.iso.datetime(),
16532
+ commit: external_exports.string().nullable(),
16533
+ frameworkVersion: external_exports.string(),
16534
+ tier: external_exports.string().nullable(),
16535
+ budgetTokens: external_exports.number().int().positive().nullable(),
16536
+ budgetUsd: external_exports.number().positive().nullable(),
16537
+ pricePerMTok: external_exports.number().positive().nullable(),
16538
+ parts: external_exports.array(KritikPlanPartSchema).min(1),
16539
+ totals: external_exports.object({
16540
+ cells: external_exports.number().int(),
16541
+ steps: external_exports.number().int(),
16542
+ applicableCells: external_exports.number().int(),
16543
+ tokens: KritikPlanBandSchema.nullable(),
16544
+ usd: KritikPlanBandSchema.nullable()
16545
+ }),
16546
+ prompt: external_exports.string(),
16547
+ recordCommand: external_exports.string()
16548
+ }).superRefine((plan, ctx) => {
16549
+ if (plan.budgetUsd !== null && plan.pricePerMTok === null) {
16550
+ ctx.addIssue({ code: "custom", path: ["pricePerMTok"], message: "required when budgetUsd is set" });
16551
+ }
16552
+ if (!isPlanId(plan.planId)) {
16553
+ ctx.addIssue({ code: "custom", path: ["planId"], message: "not a plan id (YYYY-MM-zplan-DDNN)" });
16554
+ return;
16555
+ }
16556
+ const seen = /* @__PURE__ */ new Map();
16557
+ plan.parts.forEach((part, index) => {
16558
+ let expected;
16559
+ try {
16560
+ expected = planPartId(plan.planId, part.domain, part.surface);
16561
+ } catch {
16562
+ expected = null;
16563
+ }
16564
+ if (part.auditId !== expected) {
16565
+ ctx.addIssue({
16566
+ code: "custom",
16567
+ path: ["parts", index, "auditId"],
16568
+ message: expected === null ? `the surface "${part.surface}" cannot be planned, so no audit id fits this part` : `not this part's audit id: expected "${expected}"`
16569
+ });
16570
+ } else if (seen.has(part.auditId)) {
16571
+ ctx.addIssue({ code: "custom", path: ["parts", index, "auditId"], message: `repeats the audit id of part ${seen.get(part.auditId)}` });
16572
+ } else {
16573
+ seen.set(part.auditId, index);
16574
+ }
16575
+ part.cells.forEach((cell, cellIndex) => {
16576
+ if (cell.surface !== part.surface) {
16577
+ ctx.addIssue({
16578
+ code: "custom",
16579
+ path: ["parts", index, "cells", cellIndex, "surface"],
16580
+ message: `not the part's surface "${part.surface}"`
16581
+ });
16582
+ }
16583
+ });
16584
+ });
16585
+ });
16586
+ function parseKritikPlan(value) {
16587
+ const result = KritikPlanSchema.safeParse(value);
16588
+ if (result.success) return { ok: true, plan: result.data };
16589
+ const first = result.error.issues[0];
16590
+ const path = first === void 0 ? "" : first.path.map(String).join(".");
16591
+ return { ok: false, issue: `${path === "" ? "(root)" : path}: ${first?.message ?? "not a plan"}` };
16592
+ }
16593
+
16594
+ // ../schema/src/bundle.ts
16595
+ var PlatformStatusMapSchema = external_exports.partialRecord(
16596
+ PlatformSchema,
16597
+ // legacy-tolerant: migrateStatusVocabulary normalizes on load
16598
+ AnyStatusSchema
16599
+ ).meta({ id: "PlatformStatusMap", description: "Per-platform status overrides for view nodes." });
16600
+ var PlatformNotesMapSchema = external_exports.partialRecord(
16601
+ PlatformSchema,
16602
+ external_exports.string()
16603
+ ).meta({ id: "PlatformNotesMap", description: "Freeform per-platform notes." });
16604
+ var PlatformScreenshotsMapSchema = external_exports.partialRecord(
16605
+ PlatformSchema,
16606
+ external_exports.string()
16607
+ ).meta({
16608
+ id: "PlatformScreenshotsMap",
16609
+ description: "Per-platform screenshot: a relative path, an absolute URL, or a data URI (see docs/spec/bundle-format.md \xA7 Asset Values)."
16610
+ });
16611
+ var PlatformScreenshotMetaSchema = external_exports.object({
16612
+ ts: external_exports.string().optional().meta({ description: "ISO 8601 timestamp of when the current shot was recorded." }),
16613
+ source: external_exports.enum(SCREENSHOT_SOURCES).optional().meta({ description: "Who recorded the current shot: ci or manual." }),
16614
+ form: external_exports.enum(SCREENSHOT_FORMS).optional().meta({ description: "Asset form of the slot value: url, path or data (see Asset Values)." }),
16615
+ commit: external_exports.string().optional().meta({ description: "The sha a CI shot was rendered from." }),
16616
+ order: external_exports.number().int().nonnegative().optional().meta({ description: "That commit's height on the default branch." }),
16617
+ ci_order: external_exports.number().int().nonnegative().optional().meta({ description: "The highest CI order ever accepted for this slot, kept across a manual shot and a removal so a late CI re-run cannot overwrite a newer shot." })
16618
+ }).meta({ id: "PlatformScreenshotMeta", description: "Provenance of the current per-platform screenshot and the CI order watermark." });
16619
+ var PlatformScreenshotMetaMapSchema = external_exports.partialRecord(PlatformSchema, PlatformScreenshotMetaSchema).meta({ id: "PlatformScreenshotMetaMap", description: "Per-platform screenshot provenance (see PlatformScreenshotMeta)." });
16620
+ var RefSchema = external_exports.object({
16621
+ id: external_exports.string().meta({ description: 'Unique within the node, kebab-case (e.g. "gh-142").' }),
16622
+ type: external_exports.string().meta({
16623
+ description: "Ref type: figma | github-issue | gitlab-issue | linear-issue | github-pr | gitlab-mr | url. Unrecognized values are preserved and render as generic links."
16624
+ }),
16625
+ url: external_exports.string().meta({ description: "Canonical external URL." }),
16626
+ title: external_exports.string().optional().meta({ description: "Display label." }),
16627
+ external_status: external_exports.string().optional().meta({
16628
+ description: 'Mirrored external state, verbatim (e.g. "open", "merged", "In Progress").'
16629
+ }),
16630
+ // legacy-tolerant: migrateStatusVocabulary normalizes on load
16631
+ status_mapped: AnyStatusSchema.optional().meta({
16632
+ description: "Optional mapping of external_status into the arkaik lifecycle. Advisory display data \u2014 never mutates node.status."
16633
+ }),
16634
+ platform: PlatformSchema.optional().meta({ description: "Optional scoping to one platform variant." }),
16635
+ synced_at: external_exports.string().optional().meta({ description: "ISO 8601 \u2014 when external_status was last mirrored." })
16636
+ }).meta({ id: "Ref", description: "A typed external reference on a node (docs/spec/bundle-format.md \xA7 References)." });
16637
+ var NodeMetadataSchema = external_exports.object({
16638
+ stage: external_exports.string().optional(),
16639
+ blocked_by: external_exports.string().optional().meta({
16640
+ description: "Non-empty = blocked at the current status. A node id (rendered as a link) or free text naming the dependency."
16641
+ }),
16642
+ playlist: FlowPlaylistSchema.optional(),
16643
+ platformNotes: PlatformNotesMapSchema.optional(),
16644
+ platformStatuses: PlatformStatusMapSchema.optional(),
16645
+ platformScreenshots: PlatformScreenshotsMapSchema.optional(),
16646
+ platformScreenshotMeta: PlatformScreenshotMetaMapSchema.optional(),
16647
+ refs: external_exports.array(RefSchema).optional().meta({ description: "Typed external references on the node." }),
16648
+ gherkin: external_exports.string().optional().meta({
16649
+ description: "Acceptance nodes only: exactly one Given/When/Then scenario (the How). A second scenario is a second acceptance node."
16650
+ }),
16651
+ values: external_exports.array(ValueSchema).optional().meta({
16652
+ description: "Acceptance nodes only: 1..n Bain value elements served (the Why)."
16653
+ }),
16654
+ product: external_exports.string().optional().meta({
16655
+ description: "Product membership (docs/spec/bundle-format.md \xA7 Products); flow, view, and acceptance only."
16656
+ }),
16657
+ decision_status: DecisionStatusSchema.optional().meta({
16658
+ description: "Decision nodes only: proposed | approved | enacted | rejected | deprecated | superseded. The node's lifecycle status is kept in sync (spec \xA72)."
16659
+ }),
16660
+ context: external_exports.string().optional().meta({
16661
+ description: "Decision nodes only: Context \u2014 the Why (markdown)."
16662
+ }),
16663
+ consequences: external_exports.string().optional().meta({
16664
+ description: "Decision nodes only: Consequences \u2014 the How (markdown)."
16665
+ }),
16666
+ decided_at: external_exports.string().optional().meta({
16667
+ description: "Decision nodes only: ISO 8601 date the decision was made."
16668
+ })
16669
+ }).catchall(external_exports.unknown()).meta({ id: "NodeMetadata", description: "Optional metadata for a node." });
16670
+ var NodeSchema = external_exports.object({
16671
+ id: external_exports.string().meta({ description: "Unique node ID. Convention: prefix with species \u2014 F- (flow), V- (view), DM- (data-model), API- (api-endpoint)." }),
16672
+ project_id: external_exports.string().meta({ description: "Must match project.id." }),
16673
+ species: SpeciesSchema,
16674
+ title: external_exports.string().meta({ description: "Human-readable node title." }),
16675
+ description: external_exports.string().optional().meta({ description: "Optional description of the node's purpose." }),
16676
+ // legacy-tolerant: migrateStatusVocabulary normalizes on load
16677
+ status: AnyStatusSchema,
16678
+ platforms: external_exports.array(PlatformSchema).meta({ description: "One or more target platforms." }),
16679
+ metadata: NodeMetadataSchema.optional()
16680
+ }).meta({ id: "Node" });
16681
+ var EdgeSchema = external_exports.object({
16682
+ id: external_exports.string().meta({ description: "Unique edge ID. Convention: e-{source_id}-{target_id}." }),
16683
+ project_id: external_exports.string().meta({ description: "Must match project.id." }),
16684
+ source_id: external_exports.string().meta({ description: "ID of the source node." }),
16685
+ target_id: external_exports.string().meta({ description: "ID of the target node." }),
16686
+ edge_type: EdgeTypeSchema,
16687
+ metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().meta({ description: "Optional edge metadata." })
16688
+ }).meta({ id: "Edge" });
16689
+ var MapDisplayOptionsSchema = external_exports.object({
16690
+ images: external_exports.boolean().optional().meta({ description: "Screenshot (or cover) art on view cards." }),
16691
+ flow_platforms: external_exports.string().optional().meta({
16692
+ description: "A flow card's platform delivery: rings (default) | bars."
16693
+ }),
16694
+ view_platforms: external_exports.string().optional().meta({
16695
+ description: "A view card's platform availability: chips (default) | rows."
16696
+ }),
16697
+ minimap_color: external_exports.string().optional().meta({
16698
+ description: "What a minimap node's fill encodes: status (default) | species."
16699
+ })
16700
+ }).catchall(external_exports.unknown()).meta({ id: "MapDisplayOptions", description: "How a map draws its cards (docs/spec/maps.md \xA7 Display Options)." });
16701
+ var MapDefinitionSchema = external_exports.object({
16702
+ id: external_exports.string().meta({
16703
+ description: "Kebab-case, unique within the project; built-in ids (journey, system, screens) are reserved."
16704
+ }),
16705
+ title: external_exports.string().meta({ description: "Display title." }),
16706
+ description: external_exports.string().optional().meta({ description: "What this map is for." }),
16707
+ kind: external_exports.string().meta({
16708
+ description: "Map kind: journey | system | screens. Selects the renderer and selection defaults; unrecognized kinds are preserved and listed as unrenderable."
16709
+ }),
16710
+ species: external_exports.array(external_exports.string()).optional().meta({
16711
+ description: "Node filter; defaults by kind (journey: flow+view; system: view+api-endpoint+data-model; screens: flow+view)."
16712
+ }),
16713
+ edge_types: external_exports.array(external_exports.string()).optional().meta({
16714
+ description: "Edge filter; defaults by kind (journey: composes; system: calls+displays+queries; screens: none)."
16715
+ }),
16716
+ root_node_id: external_exports.string().optional().meta({
16717
+ description: "Scope anchor: the subgraph is the undirected neighborhood reachable from this node."
16718
+ }),
16719
+ product: external_exports.string().optional().meta({ description: "Product scope; absent = every product." }),
16720
+ depth: external_exports.number().optional().meta({ description: "Traversal bound from the root; absent = unbounded." }),
16721
+ layout: external_exports.object({ direction: external_exports.string().optional() }).catchall(external_exports.unknown()).optional().meta({ description: "Renderer layout hints (e.g. direction: DOWN | RIGHT)." }),
16722
+ display: MapDisplayOptionsSchema.optional().meta({
16723
+ description: "Card rendering; the human twin is project.metadata.map_display[id]."
16724
+ })
16725
+ }).catchall(external_exports.unknown()).meta({ id: "MapDefinition", description: "A stored map definition (docs/spec/maps.md \xA7 MapDefinition)." });
16726
+ var ProductDefinitionSchema = external_exports.object({
16727
+ id: external_exports.string().meta({ description: "Kebab-case, unique within the project." }),
16728
+ title: external_exports.string().meta({ description: "Display title." }),
15674
16729
  description: external_exports.string().optional().meta({ description: "What this product is." }),
15675
16730
  platforms: external_exports.array(PlatformSchema).meta({
15676
16731
  description: "The platforms this product can ship on; empty means availability is not tracked."
@@ -15841,9 +16896,12 @@ var MAP_VIEW_PLATFORMS_MODES = ["chips", "rows"];
15841
16896
  var MAP_MINIMAP_COLOR_MODES = ["status", "species"];
15842
16897
  var KIND_DEFAULTS = {
15843
16898
  journey: { species: ["flow", "view"], edge_types: ["composes"] },
15844
- system: { species: ["view", "api-endpoint", "data-model"], edge_types: ["calls", "displays", "queries"] }
16899
+ system: { species: ["view", "api-endpoint", "data-model"], edge_types: ["calls", "displays", "queries"] },
16900
+ // A wall of screens: every flow gets a strip and every view a frame; no edge
16901
+ // is drawn (the strips are the playlists, read app-side by the wall model).
16902
+ screens: { species: ["flow", "view"], edge_types: [] }
15845
16903
  };
15846
- var BUILT_IN_MAP_IDS = ["journey", "system"];
16904
+ var BUILT_IN_MAP_IDS = ["journey", "system", "screens"];
15847
16905
  function isBuiltInMapId(id) {
15848
16906
  return BUILT_IN_MAP_IDS.includes(id);
15849
16907
  }
@@ -15860,6 +16918,12 @@ var BUILT_IN_MAPS = [
15860
16918
  description: "The model layer \u2014 views, API endpoints, and data models joined by cross-layer edges.",
15861
16919
  kind: "system",
15862
16920
  layout: { algorithm: "organic" }
16921
+ },
16922
+ {
16923
+ id: "screens",
16924
+ title: "Screens",
16925
+ description: "What is live, screen by screen \u2014 every flow as a strip of its screenshots.",
16926
+ kind: "screens"
15863
16927
  }
15864
16928
  ];
15865
16929
  function resolveMapDefaults(definition) {
@@ -15875,277 +16939,68 @@ function declared(value) {
15875
16939
  }
15876
16940
  function mapProductId(definition, defaultProductId = null) {
15877
16941
  return declared(definition?.product) ?? defaultProductId;
15878
- }
15879
- function computeMapSubgraph(definition, nodes, edges, options) {
15880
- const resolved = resolveMapDefaults(definition);
15881
- const speciesSet = new Set(resolved.species);
15882
- const edgeTypeSet = new Set(resolved.edge_types);
15883
- const productId = options?.product !== void 0 ? options.product : mapProductId(definition);
15884
- const productGraph = productId === null ? void 0 : options?.graph ?? buildProductGraph(nodes, edges);
15885
- const selectable = productGraph === void 0 ? nodes : nodes.filter((node) => nodeInProduct(node, productId, productGraph));
15886
- const keptNodes = selectable.filter((node) => speciesSet.has(node.species));
15887
- const keptNodeIds = new Set(keptNodes.map((node) => node.id));
15888
- const keptEdges = edges.filter(
15889
- (edge) => edgeTypeSet.has(edge.edge_type) && keptNodeIds.has(edge.source_id) && keptNodeIds.has(edge.target_id)
15890
- );
15891
- const rootId = definition.root_node_id;
15892
- if (rootId === void 0) {
15893
- return { nodes: [...keptNodes], edges: [...keptEdges] };
15894
- }
15895
- if (!keptNodeIds.has(rootId)) {
15896
- return { nodes: [], edges: [] };
15897
- }
15898
- const neighborsByNodeId = /* @__PURE__ */ new Map();
15899
- const addNeighbor = (from, to) => {
15900
- const list = neighborsByNodeId.get(from);
15901
- if (list) list.push(to);
15902
- else neighborsByNodeId.set(from, [to]);
15903
- };
15904
- for (const edge of keptEdges) {
15905
- addNeighbor(edge.source_id, edge.target_id);
15906
- addNeighbor(edge.target_id, edge.source_id);
15907
- }
15908
- const depthLimit = typeof definition.depth === "number" && definition.depth >= 0 ? definition.depth : Infinity;
15909
- const visited = /* @__PURE__ */ new Set([rootId]);
15910
- let frontier = [rootId];
15911
- let distance = 0;
15912
- while (frontier.length > 0 && distance < depthLimit) {
15913
- const next = [];
15914
- for (const nodeId of frontier) {
15915
- for (const neighborId of neighborsByNodeId.get(nodeId) ?? []) {
15916
- if (visited.has(neighborId)) continue;
15917
- visited.add(neighborId);
15918
- next.push(neighborId);
15919
- }
15920
- }
15921
- frontier = next;
15922
- distance += 1;
15923
- }
15924
- return {
15925
- nodes: keptNodes.filter((node) => visited.has(node.id)),
15926
- edges: keptEdges.filter((edge) => visited.has(edge.source_id) && visited.has(edge.target_id))
15927
- };
15928
- }
15929
- function listMaps(project) {
15930
- const stored = project.metadata?.maps;
15931
- const storedDefinitions = Array.isArray(stored) ? stored : [];
15932
- const custom2 = storedDefinitions.filter((definition) => {
15933
- if (typeof definition !== "object" || definition === null || Array.isArray(definition)) return false;
15934
- const candidate = definition;
15935
- if (typeof candidate.id !== "string" || typeof candidate.title !== "string") return false;
15936
- return !isBuiltInMapId(candidate.id);
15937
- });
15938
- return [...BUILT_IN_MAPS, ...custom2];
15939
- }
15940
-
15941
- // ../schema/src/quality.ts
15942
- var asArray = (value) => Array.isArray(value) ? value : [];
15943
- var MATURITY_LEVELS = [0, 1, 2, 3, 4];
15944
- var FINDING_SEVERITIES = ["critical", "high", "medium", "low", "info"];
15945
- var REMEDIATION_COSTS = ["S", "M", "L", "XL"];
15946
- var FINDING_STATUSES = ["open", "resolved", "refuted", "accepted-risk"];
15947
- var QUALITY_GRADES = ["A", "B", "C", "D", "E"];
15948
- var DEFAULT_GRADE_BANDS = { A: 85, B: 70, C: 55, D: 40, E: 0 };
15949
- var DEFAULT_SEVERITY_BUCKETS = {
15950
- critical: [20, 25],
15951
- high: [12, 19],
15952
- medium: [6, 11],
15953
- low: [2, 5],
15954
- info: [1, 1]
15955
- };
15956
- var DEFAULT_CAPS = {
15957
- critical_open: "D",
15958
- high_open: "B"
15959
- };
15960
- var CROSS_SURFACE_ID = "cross-surface";
15961
- function mergeKritikLibrary(pack, overlay) {
15962
- if (!overlay || typeof overlay !== "object") return pack;
15963
- const domains = [...asArray(pack.domains)];
15964
- for (const domain2 of asArray(overlay.domains)) {
15965
- if (typeof domain2?.code !== "string" || domain2.code === "") continue;
15966
- const at = domains.findIndex((existing) => existing?.code === domain2.code);
15967
- if (at >= 0) domains[at] = domain2;
15968
- else domains.push(domain2);
15969
- }
15970
- const criteria = [...asArray(pack.criteria)];
15971
- for (const criterion of asArray(overlay.criteria)) {
15972
- if (typeof criterion?.id !== "string" || criterion.id === "") continue;
15973
- const at = criteria.findIndex((existing) => existing?.id === criterion.id);
15974
- if (at >= 0) criteria[at] = criterion;
15975
- else criteria.push(criterion);
15976
- }
15977
- const scales = pack.scales || overlay.scales ? { ...pack.scales ?? {}, ...overlay.scales ?? {} } : void 0;
15978
- return { ...pack, domains, criteria, ...scales ? { scales } : {} };
15979
- }
15980
- function bucketsOf(library) {
15981
- const stored = library?.scales?.severity_buckets;
15982
- const out = { ...DEFAULT_SEVERITY_BUCKETS };
15983
- if (!stored || typeof stored !== "object") return out;
15984
- for (const severity of FINDING_SEVERITIES) {
15985
- const band = stored[severity];
15986
- if (Array.isArray(band) && typeof band[0] === "number" && typeof band[1] === "number") {
15987
- out[severity] = [band[0], band[1]];
15988
- }
15989
- }
15990
- return out;
15991
- }
15992
- function bandsOf(library) {
15993
- const stored = library?.scales?.grades;
15994
- const out = { ...DEFAULT_GRADE_BANDS };
15995
- if (!stored || typeof stored !== "object") return out;
15996
- for (const grade of QUALITY_GRADES) {
15997
- const min = stored[grade];
15998
- if (typeof min === "number" && Number.isFinite(min)) out[grade] = min;
15999
- }
16000
- return out;
16001
- }
16002
- function capsOf(library) {
16003
- const stored = library?.scales?.caps;
16004
- const pick2 = (value, fallback) => typeof value === "string" && QUALITY_GRADES.includes(value) ? value : fallback;
16005
- return {
16006
- critical_open: pick2(stored?.critical_open, DEFAULT_CAPS.critical_open),
16007
- high_open: pick2(stored?.high_open, DEFAULT_CAPS.high_open)
16008
- };
16009
- }
16010
- function severityOf(finding, library) {
16011
- const impact = typeof finding.impact === "number" ? finding.impact : 0;
16012
- const likelihood = typeof finding.likelihood === "number" ? finding.likelihood : 0;
16013
- const score = impact * likelihood;
16014
- const buckets = bucketsOf(library);
16015
- const worstFirst = [...FINDING_SEVERITIES].sort((a, b) => buckets[b][0] - buckets[a][0]);
16016
- for (const severity of worstFirst) {
16017
- if (score >= buckets[severity][0]) return severity;
16018
- }
16019
- return "info";
16020
- }
16021
- function priorityOf(finding, library) {
16022
- const severity = severityOf(finding, library);
16023
- const cheap = finding.cost === "S";
16024
- if (severity === "critical") return "P0";
16025
- if (severity === "high") return cheap ? "P0" : "P1";
16026
- if (severity === "medium") return cheap ? "P1" : "P2";
16027
- if (severity === "low") return cheap ? "P2" : "P3";
16028
- return "P3";
16029
- }
16030
- function gradeOf(score, library) {
16031
- const bands = bandsOf(library);
16032
- const bestFirst = [...QUALITY_GRADES].sort((a, b) => bands[b] - bands[a]);
16033
- for (const grade of bestFirst) {
16034
- if (score >= bands[grade]) return grade;
16035
- }
16036
- return "E";
16037
- }
16038
- function capGrade(grade, cap) {
16039
- return QUALITY_GRADES[Math.max(QUALITY_GRADES.indexOf(grade), QUALITY_GRADES.indexOf(cap))];
16040
- }
16041
- function isOpenFinding(finding) {
16042
- return (finding.status ?? "open") === "open";
16043
- }
16044
- function rollUpSurface(scores, weights) {
16045
- let weighted = 0;
16046
- let total = 0;
16047
- for (const domain2 of Object.keys(scores)) {
16048
- const score = scores[domain2];
16049
- if (typeof score !== "number" || !Number.isFinite(score)) continue;
16050
- const weight = typeof weights?.[domain2] === "number" ? weights[domain2] : 1;
16051
- weighted += score * weight;
16052
- total += weight;
16053
- }
16054
- return total > 0 ? Math.round(weighted / total) : null;
16055
- }
16056
- function resolveKritikLibrary(section, library) {
16057
- const explicit = library ?? section?.library;
16058
- if (explicit && Array.isArray(explicit.criteria) && Array.isArray(explicit.domains)) return explicit;
16059
- if (!section) return void 0;
16060
- const ids = /* @__PURE__ */ new Set();
16061
- for (const row of [...asArray(section.assessments), ...asArray(section.findings)]) {
16062
- if (typeof row?.criterion_id === "string" && row.criterion_id !== "") ids.add(row.criterion_id);
16063
- }
16064
- if (ids.size === 0) return void 0;
16065
- const domainOf = (id) => id.includes("-") ? id.slice(0, id.lastIndexOf("-")) : id;
16066
- const criteria = [...ids].sort().map((id) => ({ id, domain: domainOf(id), weight: 1 }));
16067
- const domains = [...new Set(criteria.map((c) => c.domain))].sort().map((code) => ({ code, name: code }));
16068
- return { version: explicit?.version ?? "unknown", domains, criteria, scales: explicit?.scales };
16069
- }
16070
- function deriveQualityMatrix(bundle, library) {
16071
- const section = bundle.quality;
16072
- const pack = resolveKritikLibrary(section, library);
16073
- const assessments = asArray(section?.assessments);
16074
- const findings = asArray(section?.findings);
16075
- const openFindings = findings.filter((finding) => isOpenFinding(finding));
16076
- const declared2 = asArray(section?.profile?.surfaces).map((surface) => surface?.id).filter((id) => typeof id === "string" && id !== "");
16077
- const surfaces = declared2.length > 0 ? [...new Set(declared2)] : [...new Set(assessments.map((a) => a.surface).filter((id) => typeof id === "string" && id !== ""))].sort();
16078
- const domains = asArray(pack?.domains).map((domain2) => domain2?.code).filter((code) => typeof code === "string" && code !== "");
16079
- const domainOfCriterion = /* @__PURE__ */ new Map();
16080
- const weightOfCriterion = /* @__PURE__ */ new Map();
16081
- for (const criterion of asArray(pack?.criteria)) {
16082
- if (typeof criterion?.id !== "string") continue;
16083
- if (typeof criterion.domain === "string") domainOfCriterion.set(criterion.id, criterion.domain);
16084
- weightOfCriterion.set(criterion.id, typeof criterion.weight === "number" && criterion.weight > 0 ? criterion.weight : 1);
16942
+ }
16943
+ function computeMapSubgraph(definition, nodes, edges, options) {
16944
+ const resolved = resolveMapDefaults(definition);
16945
+ const speciesSet = new Set(resolved.species);
16946
+ const edgeTypeSet = new Set(resolved.edge_types);
16947
+ const productId = options?.product !== void 0 ? options.product : mapProductId(definition);
16948
+ const productGraph = productId === null ? void 0 : options?.graph ?? buildProductGraph(nodes, edges);
16949
+ const selectable = productGraph === void 0 ? nodes : nodes.filter((node) => nodeInProduct(node, productId, productGraph));
16950
+ const keptNodes = selectable.filter((node) => speciesSet.has(node.species));
16951
+ const keptNodeIds = new Set(keptNodes.map((node) => node.id));
16952
+ const keptEdges = edges.filter(
16953
+ (edge) => edgeTypeSet.has(edge.edge_type) && keptNodeIds.has(edge.source_id) && keptNodeIds.has(edge.target_id)
16954
+ );
16955
+ const rootId = definition.root_node_id;
16956
+ if (rootId === void 0 || definition.kind === "screens") {
16957
+ return { nodes: [...keptNodes], edges: [...keptEdges] };
16085
16958
  }
16086
- const caps = capsOf(pack);
16087
- const weights = section?.profile?.domain_weights;
16088
- const matrix = {};
16089
- for (const domain2 of domains) {
16090
- matrix[domain2] = {};
16091
- for (const surface of surfaces) {
16092
- const rows = assessments.filter((a) => a.surface === surface && domainOfCriterion.get(a.criterion_id) === domain2);
16093
- if (rows.length === 0) {
16094
- matrix[domain2][surface] = null;
16095
- continue;
16096
- }
16097
- let earned = 0;
16098
- let available = 0;
16099
- for (const row of rows) {
16100
- const weight = weightOfCriterion.get(row.criterion_id) ?? 1;
16101
- const level = typeof row.level === "number" ? Math.min(Math.max(row.level, 0), 4) : 0;
16102
- earned += level * weight;
16103
- available += 4 * weight;
16104
- }
16105
- if (available === 0) {
16106
- matrix[domain2][surface] = null;
16107
- continue;
16108
- }
16109
- const score = Math.round(earned / available * 100);
16110
- const cellSeverities = openFindings.filter((finding) => finding.surface === surface && domainOfCriterion.get(finding.criterion_id) === domain2).map((finding) => severityOf(finding, pack));
16111
- const banded = gradeOf(score, pack);
16112
- let grade = banded;
16113
- if (cellSeverities.includes("critical")) grade = capGrade(grade, caps.critical_open);
16114
- else if (cellSeverities.includes("high")) grade = capGrade(grade, caps.high_open);
16115
- matrix[domain2][surface] = {
16116
- score,
16117
- grade,
16118
- capped: grade !== banded,
16119
- criteria: rows.length,
16120
- findings: {
16121
- critical: cellSeverities.filter((s) => s === "critical").length,
16122
- high: cellSeverities.filter((s) => s === "high").length,
16123
- medium: cellSeverities.filter((s) => s === "medium").length,
16124
- low: cellSeverities.filter((s) => s === "low").length
16125
- }
16126
- };
16127
- }
16959
+ if (!keptNodeIds.has(rootId)) {
16960
+ return { nodes: [], edges: [] };
16128
16961
  }
16129
- const overall = {};
16130
- for (const surface of surfaces) {
16131
- const bySurface = {};
16132
- for (const domain2 of domains) {
16133
- const cell = matrix[domain2]?.[surface];
16134
- if (cell) bySurface[domain2] = cell.score;
16962
+ const neighborsByNodeId = /* @__PURE__ */ new Map();
16963
+ const addNeighbor = (from, to) => {
16964
+ const list = neighborsByNodeId.get(from);
16965
+ if (list) list.push(to);
16966
+ else neighborsByNodeId.set(from, [to]);
16967
+ };
16968
+ for (const edge of keptEdges) {
16969
+ addNeighbor(edge.source_id, edge.target_id);
16970
+ addNeighbor(edge.target_id, edge.source_id);
16971
+ }
16972
+ const depthLimit = typeof definition.depth === "number" && definition.depth >= 0 ? definition.depth : Infinity;
16973
+ const visited = /* @__PURE__ */ new Set([rootId]);
16974
+ let frontier = [rootId];
16975
+ let distance = 0;
16976
+ while (frontier.length > 0 && distance < depthLimit) {
16977
+ const next = [];
16978
+ for (const nodeId of frontier) {
16979
+ for (const neighborId of neighborsByNodeId.get(nodeId) ?? []) {
16980
+ if (visited.has(neighborId)) continue;
16981
+ visited.add(neighborId);
16982
+ next.push(neighborId);
16983
+ }
16135
16984
  }
16136
- overall[surface] = rollUpSurface(bySurface, weights);
16985
+ frontier = next;
16986
+ distance += 1;
16137
16987
  }
16138
- const finding_counts = { critical: 0, high: 0, medium: 0, low: 0, info: 0 };
16139
- for (const finding of openFindings) finding_counts[severityOf(finding, pack)]++;
16140
16988
  return {
16141
- framework_version: section?.framework_version,
16142
- surfaces,
16143
- domains,
16144
- matrix,
16145
- overall,
16146
- finding_counts
16989
+ nodes: keptNodes.filter((node) => visited.has(node.id)),
16990
+ edges: keptEdges.filter((edge) => visited.has(edge.source_id) && visited.has(edge.target_id))
16147
16991
  };
16148
16992
  }
16993
+ function listMaps(project) {
16994
+ const stored = project.metadata?.maps;
16995
+ const storedDefinitions = Array.isArray(stored) ? stored : [];
16996
+ const custom2 = storedDefinitions.filter((definition) => {
16997
+ if (typeof definition !== "object" || definition === null || Array.isArray(definition)) return false;
16998
+ const candidate = definition;
16999
+ if (typeof candidate.id !== "string" || typeof candidate.title !== "string") return false;
17000
+ return !isBuiltInMapId(candidate.id);
17001
+ });
17002
+ return [...BUILT_IN_MAPS, ...custom2];
17003
+ }
16149
17004
 
16150
17005
  // ../schema/src/validate.ts
16151
17006
  var VALID_STAGES = ["beta", "monitoring", "deprecated"];
@@ -17270,7 +18125,7 @@ function computeDeliverables(events) {
17270
18125
  return null;
17271
18126
  };
17272
18127
  const out = [];
17273
- for (const [id, anchorIndex] of firstIndex) {
18128
+ for (const [id, anchorIndex2] of firstIndex) {
17274
18129
  const ev = latest.get(id);
17275
18130
  if (ev === void 0) continue;
17276
18131
  const summary = asString(ev.summary);
@@ -17283,8 +18138,8 @@ function computeDeliverables(events) {
17283
18138
  ...url2 !== void 0 ? { url: url2 } : {},
17284
18139
  node_ids: Array.isArray(ev.node_ids) ? ev.node_ids.filter((n) => typeof n === "string") : [],
17285
18140
  ...platform !== void 0 ? { platform } : {},
17286
- ts: asString(ordered[anchorIndex].ts) ?? "",
17287
- releaseVersion: releaseOf(anchorIndex)
18141
+ ts: asString(ordered[anchorIndex2].ts) ?? "",
18142
+ releaseVersion: releaseOf(anchorIndex2)
17288
18143
  });
17289
18144
  }
17290
18145
  return out;
@@ -17375,7 +18230,7 @@ function edgeRemovedInput(edgeId2) {
17375
18230
  }
17376
18231
  var TOP_LEVEL_FIELDS = ["species", "title", "description", "status", "platforms"];
17377
18232
  var MAX_SCALAR_LEN = 512;
17378
- function isRecord(value) {
18233
+ function isRecord3(value) {
17379
18234
  return typeof value === "object" && value !== null && !Array.isArray(value);
17380
18235
  }
17381
18236
  function isShortScalar(value) {
@@ -17386,8 +18241,8 @@ function valueEqual(a, b) {
17386
18241
  return JSON.stringify(a) === JSON.stringify(b);
17387
18242
  }
17388
18243
  function changedMapKeys(prev, next) {
17389
- const p = isRecord(prev) ? prev : {};
17390
- const n = isRecord(next) ? next : {};
18244
+ const p = isRecord3(prev) ? prev : {};
18245
+ const n = isRecord3(next) ? next : {};
17391
18246
  const changed = [];
17392
18247
  for (const key of /* @__PURE__ */ new Set([...Object.keys(p), ...Object.keys(n)])) {
17393
18248
  if (!valueEqual(p[key], n[key])) changed.push(key);
@@ -17395,8 +18250,8 @@ function changedMapKeys(prev, next) {
17395
18250
  return changed.sort();
17396
18251
  }
17397
18252
  function diffPlatformStatuses(nodeId, currentBase, nextBase, prev, next) {
17398
- const p = isRecord(prev) ? prev : {};
17399
- const n = isRecord(next) ? next : {};
18253
+ const p = isRecord3(prev) ? prev : {};
18254
+ const n = isRecord3(next) ? next : {};
17400
18255
  const events = [];
17401
18256
  for (const platform of [.../* @__PURE__ */ new Set([...Object.keys(p), ...Object.keys(n)])].sort()) {
17402
18257
  const from = p[platform];
@@ -17420,7 +18275,7 @@ function diffRefs(nodeId, prev, next) {
17420
18275
  const byId = (arr) => {
17421
18276
  const map2 = /* @__PURE__ */ new Map();
17422
18277
  for (const item of arr) {
17423
- if (isRecord(item) && typeof item.id === "string") map2.set(item.id, item);
18278
+ if (isRecord3(item) && typeof item.id === "string") map2.set(item.id, item);
17424
18279
  }
17425
18280
  return map2;
17426
18281
  };
@@ -17460,8 +18315,8 @@ function diffNodeUpdate(current, patch) {
17460
18315
  }
17461
18316
  }
17462
18317
  if ("metadata" in pat) {
17463
- const prevMeta = isRecord(current.metadata) ? current.metadata : {};
17464
- const nextMeta = isRecord(patch.metadata) ? patch.metadata : {};
18318
+ const prevMeta = isRecord3(current.metadata) ? current.metadata : {};
18319
+ const nextMeta = isRecord3(patch.metadata) ? patch.metadata : {};
17465
18320
  const currentBase = current.status;
17466
18321
  const nextBase = "status" in pat && pat.status !== void 0 ? pat.status : current.status;
17467
18322
  for (const key of /* @__PURE__ */ new Set([...Object.keys(prevMeta), ...Object.keys(nextMeta)])) {
@@ -17660,201 +18515,83 @@ function applyOps(input, ops) {
17660
18515
  }
17661
18516
  edges = edges.filter((candidate) => candidate.id !== op.edge_id);
17662
18517
  eventInputs.push(edgeRemovedInput(op.edge_id));
17663
- break;
17664
- }
17665
- }
17666
- }
17667
- return { nodes, edges, eventInputs, synthesizedEdges, cascadedEdgeIds };
17668
- }
17669
-
17670
- // ../schema/src/quality-ops.ts
17671
- function upsertAssessment(assessments, next) {
17672
- const index = assessments.findIndex(
17673
- (candidate) => candidate.criterion_id === next.criterion_id && candidate.surface === next.surface
17674
- );
17675
- if (index === -1) return { assessments: [...assessments, next] };
17676
- const updated = [...assessments];
17677
- const replaced = updated[index];
17678
- updated[index] = next;
17679
- return { assessments: updated, replaced };
17680
- }
17681
- function domainCodeOf(criterionId, library) {
17682
- const criterion = (library?.criteria ?? []).find((candidate) => candidate.id === criterionId);
17683
- if (typeof criterion?.domain === "string" && criterion.domain !== "") return criterion.domain;
17684
- const dash = criterionId.indexOf("-");
17685
- return dash > 0 ? criterionId.slice(0, dash) : criterionId;
17686
- }
17687
- function mintFindingId(auditId, criterionId, surface, taken, library) {
17688
- const prefix = `F-${auditId}-${domainCodeOf(criterionId, library)}-${surface}-`;
17689
- const used = new Set(taken);
17690
- for (let n = 1; n < 1e3; n++) {
17691
- const candidate = `${prefix}${String(n).padStart(2, "0")}`;
17692
- if (!used.has(candidate)) return candidate;
17693
- }
17694
- throw new Error(`Kritik: exhausted finding ids for ${prefix}NN \u2014 999 findings on one cell is a data problem, not a numbering one`);
17695
- }
17696
- function upsertFinding(findings, next) {
17697
- const index = findings.findIndex((candidate) => candidate.id === next.id);
17698
- if (index === -1) return { findings: [...findings, next] };
17699
- const updated = [...findings];
17700
- const replaced = updated[index];
17701
- updated[index] = next;
17702
- return { findings: updated, replaced };
17703
- }
17704
- function patchFinding(findings, id, patch) {
17705
- const index = findings.findIndex((candidate) => candidate.id === id);
17706
- if (index === -1) return { findings: [...findings] };
17707
- const updated = [...findings];
17708
- const previous = updated[index];
17709
- const finding = { ...previous, ...patch };
17710
- updated[index] = finding;
17711
- return { findings: updated, finding, previous };
17712
- }
17713
- function resolveFinding(findings, id, resolvedBy) {
17714
- return patchFinding(findings, id, {
17715
- status: "resolved",
17716
- ...resolvedBy !== void 0 ? { resolved_by: resolvedBy } : {}
17717
- });
17718
- }
17719
- function acceptedDetail(detail, note) {
17720
- return `${detail}
17721
-
17722
- Accepted risk: ${note}`.trim();
17723
- }
17724
- function acceptFinding(findings, id, note) {
17725
- const existing = findings.find((candidate) => candidate.id === id);
17726
- const detail = existing === void 0 ? note : acceptedDetail(existing.detail, note);
17727
- return patchFinding(findings, id, { status: "accepted-risk", detail });
17728
- }
17729
- function fillTemplate(text, values) {
17730
- return text.replace(/\{(\w+)\}/g, (whole, key) => values[key] ?? whole);
17731
- }
17732
- function renderIssue(criterion, options) {
17733
- const { surface, finding, library } = options;
17734
- const anchors = criterion.level_anchors ?? {};
17735
- const level = options.level === void 0 || options.level === "" ? "" : String(options.level);
17736
- const observed = level === "" ? "{observed_level}" : level;
17737
- const target = options.targetLevel !== void 0 && options.targetLevel !== "" ? String(options.targetLevel) : level === "" ? "{target_level}" : String(Math.min(Number(level) + 1, 4));
17738
- const values = {
17739
- surface,
17740
- observed_level: observed,
17741
- target_level: target,
17742
- observed_level_name: anchors[`l${observed}`] ?? "{observed_level_name}",
17743
- target_level_name: anchors[`l${target}`] ?? "{target_level_name}",
17744
- target_anchor_text: anchors[`l${target}`] ?? "{target_anchor_text}",
17745
- impact: String(finding?.impact ?? criterion.default_impact ?? 3)
17746
- };
17747
- if (finding !== void 0) {
17748
- values.likelihood = String(finding.likelihood);
17749
- values.evidence_bullets_with_file_paths = finding.evidence;
17750
- values.risk_narrative = finding.detail;
17751
- if (typeof finding.remediation === "string" && finding.remediation !== "") {
17752
- values.remediation_step_1 = finding.remediation;
17753
- }
17754
- }
17755
- const issue2 = criterion.issue ?? {};
17756
- const labels = [.../* @__PURE__ */ new Set([...issue2.labels ?? ["quality"], surface])];
17757
- const body = fillTemplate(issue2.body_skeleton ?? "", values);
17758
- return {
17759
- title: fillTemplate(issue2.title_template ?? `[Quality] ${criterion.id} on {surface}`, values),
17760
- labels,
17761
- body: finding === void 0 ? body : `${body}
17762
- ${findingFooter(finding, library)}`,
17763
- ...typeof criterion.remediation === "string" && criterion.remediation !== "" ? { remediation: criterion.remediation } : {}
17764
- };
17765
- }
17766
- function findingFooter(finding, library) {
17767
- const lines = [
17768
- ``,
17769
- `---`,
17770
- `<sub>Kritik finding \`${finding.id}\` \u2014 **${severityOf(finding, library)} / ${priorityOf(finding, library)}** (impact ${finding.impact} x likelihood ${finding.likelihood}, cost ${finding.cost})</sub>`,
17771
- ``,
17772
- `**Evidence**`,
17773
- finding.evidence
17774
- ];
17775
- if (typeof finding.remediation === "string" && finding.remediation !== "") {
17776
- lines.push(``, `**Remediation**`, finding.remediation);
17777
- }
17778
- return lines.join("\n");
17779
- }
17780
- function signalRunSheet(library, surfaces, filter = {}) {
17781
- const surfaceIds = surfaces.map((surface) => surface.id).filter((id) => id !== CROSS_SURFACE_ID);
17782
- const rows = [];
17783
- for (const criterion of library.criteria ?? []) {
17784
- if (criterion.superseded_by !== void 0) continue;
17785
- if (filter.criterion !== void 0 && criterion.id !== filter.criterion) continue;
17786
- if (filter.domain !== void 0 && criterion.domain !== filter.domain) continue;
17787
- const signals = criterion.signals ?? [];
17788
- if (signals.length === 0) continue;
17789
- const appliesTo = criterion.applies_to;
17790
- for (const surfaceId of surfaceIds) {
17791
- if (Array.isArray(appliesTo) && !appliesTo.includes(surfaceId)) continue;
17792
- if (filter.surface !== void 0 && surfaceId !== filter.surface) continue;
17793
- signals.forEach((signal, index) => {
17794
- rows.push({ criterion_id: criterion.id, surface: surfaceId, index, signal });
17795
- });
17796
- }
17797
- }
17798
- return rows;
17799
- }
17800
- function auditCompletedInput(matrix, meta3) {
17801
- const scores = {};
17802
- for (const surface of matrix.surfaces) {
17803
- const bySurface = {};
17804
- for (const domain2 of matrix.domains) {
17805
- const cell = matrix.matrix[domain2]?.[surface];
17806
- if (cell) bySurface[domain2] = cell.score;
18518
+ break;
18519
+ }
18520
+ case "record_screenshot": {
18521
+ const index = nodes.findIndex((candidate) => candidate.id === op.node_id);
18522
+ if (index === -1) {
18523
+ throw new MutationError("node_not_found", `Node ${op.node_id} not found`, op.node_id);
18524
+ }
18525
+ const node = nodes[index];
18526
+ const decision = decideScreenshot(node, op);
18527
+ if (decision.kind === "refuse") throw new MutationError(decision.code, decision.message, op.node_id);
18528
+ if (decision.kind === "skip") break;
18529
+ const ciOrder = op.source === "ci" && typeof op.order === "number" ? op.order : void 0;
18530
+ const commit = op.source === "ci" ? op.commit : void 0;
18531
+ const prevWatermark = readSlot(node, op.platform).ciOrder;
18532
+ const watermark = ciOrder === void 0 ? prevWatermark : prevWatermark === void 0 ? ciOrder : Math.max(prevWatermark, ciOrder);
18533
+ const meta3 = {
18534
+ ts: op.ts ?? (/* @__PURE__ */ new Date()).toISOString(),
18535
+ source: op.source,
18536
+ form: op.form,
18537
+ ...commit !== void 0 ? { commit } : {},
18538
+ ...ciOrder !== void 0 ? { order: ciOrder } : {},
18539
+ ...watermark !== void 0 ? { ci_order: watermark } : {}
18540
+ };
18541
+ const updated = {
18542
+ ...node,
18543
+ metadata: {
18544
+ ...node.metadata,
18545
+ platformScreenshots: { ...node.metadata?.platformScreenshots, [op.platform]: op.value },
18546
+ platformScreenshotMeta: { ...node.metadata?.platformScreenshotMeta, [op.platform]: meta3 }
18547
+ }
18548
+ };
18549
+ const nextNodes = [...nodes];
18550
+ nextNodes[index] = updated;
18551
+ nodes = nextNodes;
18552
+ eventInputs.push({
18553
+ type: "screenshot.recorded",
18554
+ payload: {
18555
+ node_id: op.node_id,
18556
+ platform: op.platform,
18557
+ source: op.source,
18558
+ form: op.form,
18559
+ // Events never embed asset payloads: a data URI stays in the
18560
+ // snapshot. A `path` form travels under `url` too, on purpose.
18561
+ ...op.form !== "data" ? { url: op.value } : {},
18562
+ ...commit !== void 0 ? { commit } : {},
18563
+ ...ciOrder !== void 0 ? { order: ciOrder } : {},
18564
+ ...op.detail !== void 0 ? { detail: op.detail } : {}
18565
+ }
18566
+ });
18567
+ break;
18568
+ }
18569
+ case "remove_screenshot": {
18570
+ const index = nodes.findIndex((candidate) => candidate.id === op.node_id);
18571
+ if (index === -1) {
18572
+ throw new MutationError("node_not_found", `Node ${op.node_id} not found`, op.node_id);
18573
+ }
18574
+ const node = nodes[index];
18575
+ const shots = { ...node.metadata?.platformScreenshots };
18576
+ if (!(op.platform in shots)) break;
18577
+ delete shots[op.platform];
18578
+ const metas = { ...node.metadata?.platformScreenshotMeta };
18579
+ const watermark = readSlot(node, op.platform).ciOrder;
18580
+ if (watermark !== void 0) metas[op.platform] = { ci_order: watermark };
18581
+ else delete metas[op.platform];
18582
+ const updated = {
18583
+ ...node,
18584
+ metadata: { ...node.metadata, platformScreenshots: shots, platformScreenshotMeta: metas }
18585
+ };
18586
+ const nextNodes = [...nodes];
18587
+ nextNodes[index] = updated;
18588
+ nodes = nextNodes;
18589
+ eventInputs.push({ type: "screenshot.removed", payload: { node_id: op.node_id, platform: op.platform } });
18590
+ break;
18591
+ }
17807
18592
  }
17808
- scores[surface] = bySurface;
17809
18593
  }
17810
- return {
17811
- type: "quality.audit.completed",
17812
- payload: {
17813
- audit_id: meta3.audit_id,
17814
- framework_version: meta3.framework_version,
17815
- ...meta3.commit !== void 0 ? { commit: meta3.commit } : {},
17816
- scores,
17817
- counts: matrix.finding_counts,
17818
- ...meta3.scope !== void 0 ? { scope: meta3.scope } : {}
17819
- }
17820
- };
17821
- }
17822
- function findingOpenedInput(finding, library) {
17823
- return {
17824
- type: "quality.finding.opened",
17825
- payload: {
17826
- finding_id: finding.id,
17827
- criterion_id: finding.criterion_id,
17828
- surface: finding.surface,
17829
- severity: severityOf(finding, library),
17830
- priority: priorityOf(finding, library),
17831
- title: finding.title,
17832
- ...finding.node_ids !== void 0 ? { node_ids: finding.node_ids } : {},
17833
- ...finding.issue_url !== void 0 ? { issue_url: finding.issue_url } : {}
17834
- }
17835
- };
17836
- }
17837
- function findingResolvedInput(finding, resolvedBy) {
17838
- return {
17839
- type: "quality.finding.resolved",
17840
- payload: {
17841
- finding_id: finding.id,
17842
- ...resolvedBy !== void 0 ? { resolved_by: resolvedBy } : {},
17843
- ...finding.node_ids !== void 0 ? { node_ids: finding.node_ids } : {}
17844
- }
17845
- };
17846
- }
17847
- function signalTrippedInput(trip) {
17848
- return {
17849
- type: "quality.signal.tripped",
17850
- payload: {
17851
- criterion_id: trip.criterion_id,
17852
- surface: trip.surface,
17853
- signal: trip.signal,
17854
- ...trip.commit !== void 0 ? { commit: trip.commit } : {},
17855
- ...trip.detail !== void 0 ? { detail: trip.detail } : {}
17856
- }
17857
- };
18594
+ return { nodes, edges, eventInputs, synthesizedEdges, cascadedEdgeIds };
17858
18595
  }
17859
18596
 
17860
18597
  // ../schema/src/quality-regressions.ts
@@ -17936,7 +18673,7 @@ function detectRegressions(previous, next, library) {
17936
18673
 
17937
18674
  // ../schema/src/quality-trend.ts
17938
18675
  var NO_DELTA = { previous: null, delta: null };
17939
- var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
18676
+ var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
17940
18677
  function frameworkMajor(version2) {
17941
18678
  if (typeof version2 !== "string") return null;
17942
18679
  const match = /^\s*v?(\d+)/.exec(version2);
@@ -17948,15 +18685,16 @@ function sameFrameworkMajor(a, b) {
17948
18685
  return left === null || right === null || left === right;
17949
18686
  }
17950
18687
  function scopeOf(raw) {
17951
- if (!isRecord2(raw) || typeof raw.since !== "string" || raw.since === "") return void 0;
18688
+ if (readPlanScope(raw) !== null) return void 0;
18689
+ if (!isRecord4(raw) || typeof raw.since !== "string" || raw.since === "") return void 0;
17952
18690
  return { scope: { since: raw.since, cells: typeof raw.cells === "number" && Number.isFinite(raw.cells) ? raw.cells : null } };
17953
18691
  }
17954
18692
  function cleanScores(raw) {
17955
18693
  const scores = {};
17956
- if (!isRecord2(raw)) return scores;
18694
+ if (!isRecord4(raw)) return scores;
17957
18695
  for (const surface of Object.keys(raw)) {
17958
18696
  const bySurface = raw[surface];
17959
- if (!isRecord2(bySurface)) continue;
18697
+ if (!isRecord4(bySurface)) continue;
17960
18698
  const cleaned = {};
17961
18699
  for (const domain2 of Object.keys(bySurface)) {
17962
18700
  const score = bySurface[domain2];
@@ -17968,7 +18706,7 @@ function cleanScores(raw) {
17968
18706
  }
17969
18707
  function cleanCounts(raw) {
17970
18708
  const counts = { critical: 0, high: 0, medium: 0, low: 0, info: 0 };
17971
- if (!isRecord2(raw)) return counts;
18709
+ if (!isRecord4(raw)) return counts;
17972
18710
  for (const severity of Object.keys(counts)) {
17973
18711
  const value = raw[severity];
17974
18712
  if (typeof value === "number" && Number.isFinite(value)) counts[severity] = value;
@@ -17986,7 +18724,7 @@ function liveScores(live) {
17986
18724
  const scores = {};
17987
18725
  for (const domain2 of Object.keys(live.matrix ?? {})) {
17988
18726
  const row = live.matrix[domain2];
17989
- if (!isRecord2(row)) continue;
18727
+ if (!isRecord4(row)) continue;
17990
18728
  for (const surface of Object.keys(row)) {
17991
18729
  const cell = row[surface];
17992
18730
  if (!cell || typeof cell.score !== "number") continue;
@@ -18006,13 +18744,14 @@ function deriveQualityTrend(events, profile, live) {
18006
18744
  const weights = profile?.domain_weights;
18007
18745
  const byAudit = /* @__PURE__ */ new Map();
18008
18746
  const audits = (Array.isArray(events) ? events : []).filter(
18009
- (event) => isRecord2(event) && event.type === "quality.audit.completed"
18747
+ (event) => isRecord4(event) && event.type === "quality.audit.completed"
18010
18748
  );
18011
18749
  for (const event of orderEvents(audits)) {
18012
18750
  const auditId = typeof event.audit_id === "string" ? event.audit_id : typeof event.id === "string" ? event.id : "";
18013
18751
  const scores = cleanScores(event.scores);
18014
18752
  const overall = {};
18015
18753
  for (const surface of Object.keys(scores)) overall[surface] = rollUpSurface(scores[surface], weights);
18754
+ const plan = readPlanScope(event.scope);
18016
18755
  const snapshot = {
18017
18756
  audit_id: auditId,
18018
18757
  ts: typeof event.ts === "string" ? event.ts : "",
@@ -18023,7 +18762,8 @@ function deriveQualityTrend(events, profile, live) {
18023
18762
  overall,
18024
18763
  counts: cleanCounts(event.counts),
18025
18764
  ...event.baseline === true ? { baseline: true } : {},
18026
- ...scopeOf(event.scope) ?? {}
18765
+ ...scopeOf(event.scope) ?? {},
18766
+ ...plan !== null ? { plan } : {}
18027
18767
  };
18028
18768
  byAudit.delete(auditId);
18029
18769
  byAudit.set(auditId, snapshot);
@@ -18051,6 +18791,18 @@ function deriveQualityTrend(events, profile, live) {
18051
18791
  deltaOverall: (surface) => against(previous?.overall[surface], live?.overall?.[surface])
18052
18792
  };
18053
18793
  }
18794
+ function planScored(plan, surface, domain2) {
18795
+ return plan.scored.some((key) => {
18796
+ const at = key.lastIndexOf("::");
18797
+ if (at <= 0 || key.slice(at + 2) !== surface) return false;
18798
+ return domain2 === void 0 || domainCodeOf(key.slice(0, at)) === domain2;
18799
+ });
18800
+ }
18801
+ function sameDomains(a, b, surface) {
18802
+ const left = Object.keys(a.scores[surface] ?? {});
18803
+ const right = new Set(Object.keys(b.scores[surface] ?? {}));
18804
+ return left.length === right.size && left.every((domain2) => right.has(domain2));
18805
+ }
18054
18806
  function trendRows(trend, filter = {}) {
18055
18807
  const surfaces = [];
18056
18808
  for (const snapshot of trend.snapshots) {
@@ -18070,7 +18822,8 @@ function trendRows(trend, filter = {}) {
18070
18822
  for (const surface of surfaces) {
18071
18823
  const score = valueOf(snapshot, surface);
18072
18824
  const before = above === null ? null : valueOf(above, surface);
18073
- const delta = snapshot.comparable && score !== null && before !== null ? score - before : null;
18825
+ const looked = snapshot.plan === void 0 || planScored(snapshot.plan, surface, filter.domain) && (filter.domain !== void 0 || above === null || sameDomains(snapshot, above, surface));
18826
+ const delta = looked && snapshot.comparable && score !== null && before !== null ? score - before : null;
18074
18827
  cells[surface] = { score, delta };
18075
18828
  }
18076
18829
  rows.push({
@@ -18081,7 +18834,8 @@ function trendRows(trend, filter = {}) {
18081
18834
  comparable: snapshot.comparable,
18082
18835
  cells,
18083
18836
  ...snapshot.baseline ? { baseline: true } : {},
18084
- ...snapshot.scope !== void 0 ? { scope: snapshot.scope } : {}
18837
+ ...snapshot.scope !== void 0 ? { scope: snapshot.scope } : {},
18838
+ ...snapshot.plan !== void 0 ? { plan: snapshot.plan } : {}
18085
18839
  });
18086
18840
  });
18087
18841
  return { surfaces, rows };
@@ -18092,28 +18846,72 @@ var rowsOf2 = (value) => Array.isArray(value) ? value : [];
18092
18846
  var isString = (value) => typeof value === "string" && value !== "";
18093
18847
  var stringsOf = (value) => rowsOf2(value).filter(isString);
18094
18848
  var cellKey2 = (criterionId, surface) => `${criterionId}::${surface}`;
18849
+ var orderedRows = (events) => orderEvents(rowsOf2(events).filter((event) => typeof event === "object" && event !== null));
18850
+ function isPlanRecord(event) {
18851
+ if (typeof event !== "object" || event === null) return false;
18852
+ const { type, scope, audit_id: auditId } = event;
18853
+ return type === "quality.audit.completed" && (readPlanScope(scope) !== null || isPlanId(auditId));
18854
+ }
18855
+ function recordedPlans(events) {
18856
+ const plans = [];
18857
+ for (const event of orderedRows(events)) {
18858
+ if (!isPlanRecord(event)) continue;
18859
+ const reading = readPlanScope(event.scope);
18860
+ const ts = isString(event.ts) ? event.ts : null;
18861
+ if (reading === null) plans.push({ plan: event.audit_id, parts: [], scored: [], ts });
18862
+ else plans.push({ plan: reading.plan, parts: stringsOf(reading.parts), scored: stringsOf(reading.scored), ts });
18863
+ }
18864
+ return plans;
18865
+ }
18095
18866
  function recordedAuditIds(events) {
18096
18867
  const ids = [];
18097
- for (const event of orderEvents(rowsOf2(events))) {
18098
- if (event?.type !== "quality.audit.completed") continue;
18099
- const id = event.audit_id;
18868
+ const note = (id) => {
18100
18869
  if (isString(id) && !ids.includes(id)) ids.push(id);
18870
+ };
18871
+ for (const event of orderedRows(events)) {
18872
+ if (event.type !== "quality.audit.completed") continue;
18873
+ note(event.audit_id);
18874
+ for (const part of readPlanScope(event.scope)?.parts ?? []) note(part);
18101
18875
  }
18102
18876
  return ids;
18103
18877
  }
18104
- function deriveAuditScope(events, section, library, options = {}) {
18105
- const ordered = orderEvents(rowsOf2(events).filter((event) => typeof event === "object" && event !== null));
18106
- let sinceIndex = -1;
18878
+ function neverAnAnchor(event) {
18879
+ return isPlanRecord(event) || isPlanPartId(event?.audit_id);
18880
+ }
18881
+ function recordedSinceIds(events) {
18882
+ return recordedAuditIds(rowsOf2(events).filter((event) => !neverAnAnchor(event)));
18883
+ }
18884
+ function anchorIndex(ordered, since) {
18107
18885
  for (let i = ordered.length - 1; i >= 0; i--) {
18108
18886
  const event = ordered[i];
18109
- if (event.type !== "quality.audit.completed") continue;
18110
- const id = event.audit_id;
18111
- if (options.since !== void 0 && id !== options.since) continue;
18112
- sinceIndex = i;
18113
- break;
18114
- }
18887
+ if (event.type !== "quality.audit.completed" || neverAnAnchor(event)) continue;
18888
+ if (since !== void 0 && event.audit_id !== since) continue;
18889
+ return i;
18890
+ }
18891
+ return -1;
18892
+ }
18893
+ function namesPlan(ordered, id) {
18894
+ if (isPlanId(id) || isPlanPartId(id)) return true;
18895
+ return ordered.some((event) => {
18896
+ if (!isPlanRecord(event)) return false;
18897
+ if (event.audit_id === id) return true;
18898
+ const reading = readPlanScope(event.scope);
18899
+ return reading !== null && (reading.plan === id || reading.parts.includes(id));
18900
+ });
18901
+ }
18902
+ function scopeAnchorId(events) {
18903
+ const ordered = orderedRows(events);
18904
+ const at = anchorIndex(ordered, void 0);
18905
+ if (at === -1) return null;
18906
+ const id = ordered[at].audit_id;
18907
+ return isString(id) ? id : null;
18908
+ }
18909
+ function deriveAuditScope(events, section, library, options = {}) {
18910
+ const ordered = orderedRows(events);
18911
+ const sinceIndex = anchorIndex(ordered, options.since);
18912
+ const asked = options.since;
18115
18913
  const empty = {
18116
- since: options.since ?? null,
18914
+ since: asked === void 0 || namesPlan(ordered, asked) ? null : asked,
18117
18915
  since_ts: null,
18118
18916
  cells: [],
18119
18917
  findings: [],
@@ -18127,15 +18925,51 @@ function deriveAuditScope(events, section, library, options = {}) {
18127
18925
  const anchorId = anchor.audit_id;
18128
18926
  const since = isString(anchorId) ? anchorId : null;
18129
18927
  const sinceTs = isString(anchor.ts) ? anchor.ts : null;
18928
+ const scoredAt = /* @__PURE__ */ new Map();
18929
+ for (const assessment of rowsOf2(section?.assessments)) {
18930
+ if (!isString(assessment?.criterion_id) || !isString(assessment?.surface) || !isString(assessment?.audit_id)) continue;
18931
+ if (!isString(assessment.ts)) continue;
18932
+ const key = cellKey2(assessment.criterion_id, assessment.surface);
18933
+ const byAudit = scoredAt.get(key) ?? /* @__PURE__ */ new Map();
18934
+ const seen = byAudit.get(assessment.audit_id);
18935
+ if (seen === void 0 || seen < assessment.ts) byAudit.set(assessment.audit_id, assessment.ts);
18936
+ scoredAt.set(key, byAudit);
18937
+ }
18938
+ const planFloor = /* @__PURE__ */ new Map();
18939
+ for (let i = sinceIndex + 1; i < ordered.length; i++) {
18940
+ const event = ordered[i];
18941
+ if (event.type !== "quality.audit.completed") continue;
18942
+ const reading = readPlanScope(event.scope);
18943
+ if (reading === null) continue;
18944
+ for (const key of reading.scored) {
18945
+ let ts = null;
18946
+ for (const part of reading.parts) {
18947
+ const at = scoredAt.get(key)?.get(part);
18948
+ if (at !== void 0 && (ts === null || ts < at)) ts = at;
18949
+ }
18950
+ planFloor.set(key, { index: i, ts });
18951
+ }
18952
+ }
18953
+ const sortKeyAt = (index) => {
18954
+ const ts = ordered[index]?.ts;
18955
+ return typeof ts === "string" ? ts : "";
18956
+ };
18957
+ const countsFor = (key, index) => {
18958
+ const floor = planFloor.get(key);
18959
+ if (floor === void 0) return index > sinceIndex;
18960
+ return floor.ts !== null ? sortKeyAt(index) > floor.ts : index > floor.index;
18961
+ };
18130
18962
  const resolutions = /* @__PURE__ */ new Map();
18131
- for (const event of ordered.slice(sinceIndex + 1)) {
18963
+ for (let i = sinceIndex + 1; i < ordered.length; i++) {
18964
+ const event = ordered[i];
18132
18965
  if (event.type !== "quality.finding.resolved") continue;
18133
18966
  const findingId = event.finding_id;
18134
18967
  if (!isString(findingId)) continue;
18135
- const entry = resolutions.get(findingId) ?? { node_ids: /* @__PURE__ */ new Set() };
18968
+ const entry = resolutions.get(findingId) ?? { last: i, nodes: /* @__PURE__ */ new Map() };
18969
+ entry.last = i;
18136
18970
  const by = event.resolved_by;
18137
18971
  if (isString(by)) entry.resolved_by = by;
18138
- for (const node of stringsOf(event.node_ids)) entry.node_ids.add(node);
18972
+ for (const node of stringsOf(event.node_ids)) entry.nodes.set(node, i);
18139
18973
  resolutions.set(findingId, entry);
18140
18974
  }
18141
18975
  if (resolutions.size === 0) return { ...empty, since, since_ts: sinceTs };
@@ -18173,7 +19007,10 @@ function deriveAuditScope(events, section, library, options = {}) {
18173
19007
  const unknown2 = [];
18174
19008
  const unscorable = [];
18175
19009
  const resolvedBy = {};
18176
- const resolvedNodes = /* @__PURE__ */ new Set();
19010
+ const resolvedNodes = /* @__PURE__ */ new Map();
19011
+ const touch = (node, index) => {
19012
+ if ((resolvedNodes.get(node) ?? -1) < index) resolvedNodes.set(node, index);
19013
+ };
18177
19014
  for (const [findingId, resolution] of resolutions) {
18178
19015
  const finding = findingById.get(findingId);
18179
19016
  if (finding === void 0) {
@@ -18184,15 +19021,17 @@ function deriveAuditScope(events, section, library, options = {}) {
18184
19021
  const targets = (finding.surface === CROSS_SURFACE_ID ? surfaces : [finding.surface]).filter(
18185
19022
  (surface) => scorable(finding.criterion_id, surface)
18186
19023
  );
18187
- for (const node of stringsOf(finding.node_ids)) resolvedNodes.add(node);
18188
- for (const node of resolution.node_ids) resolvedNodes.add(node);
19024
+ for (const node of stringsOf(finding.node_ids)) touch(node, resolution.last);
19025
+ for (const [node, index] of resolution.nodes) touch(node, index);
18189
19026
  if (targets.length === 0) {
18190
19027
  unscorable.push(findingId);
18191
19028
  continue;
18192
19029
  }
19030
+ const live = targets.filter((surface) => countsFor(cellKey2(finding.criterion_id, surface), resolution.last));
19031
+ if (live.length === 0) continue;
18193
19032
  drivers.push(findingId);
18194
19033
  if (resolution.resolved_by !== void 0) resolvedBy[findingId] = resolution.resolved_by;
18195
- for (const surface of targets) addDirect(finding.criterion_id, surface, findingId);
19034
+ for (const surface of live) addDirect(finding.criterion_id, surface, findingId);
18196
19035
  }
18197
19036
  let widened = 0;
18198
19037
  if (options.widen !== false && resolvedNodes.size > 0) {
@@ -18216,7 +19055,10 @@ function deriveAuditScope(events, section, library, options = {}) {
18216
19055
  if (cells.has(key)) continue;
18217
19056
  if (!criterionById.has(assessment.criterion_id)) continue;
18218
19057
  if (!surfaces.includes(assessment.surface) || !scorable(assessment.criterion_id, assessment.surface)) continue;
18219
- const shared = [...nodesByCell.get(key) ?? []].filter((node) => resolvedNodes.has(node)).sort();
19058
+ const shared = [...nodesByCell.get(key) ?? []].filter((node) => {
19059
+ const at = resolvedNodes.get(node);
19060
+ return at !== void 0 && countsFor(key, at);
19061
+ }).sort();
18220
19062
  if (shared.length === 0) continue;
18221
19063
  cells.set(key, { criterion_id: assessment.criterion_id, surface: assessment.surface, kind: "widened", because: shared });
18222
19064
  widened++;
@@ -18249,6 +19091,11 @@ function scopedAuditId(input) {
18249
19091
  if (recorded.includes(requested)) {
18250
19092
  throw new Error(`"${requested}" is already recorded \u2014 its reading is history. Name a new audit.`);
18251
19093
  }
19094
+ if (isPlanId(requested) || isPlanPartId(requested)) {
19095
+ throw new Error(
19096
+ `"${requested}" is reserved for plans and their parts \u2014 a plan id (YYYY-MM-zplan-DDNN) names a plan, and <planId>-<domain>-<surface> one of its parts, so an audit under that id could never be recorded or read as one. Name a scoped re-audit (e.g. \`${suggestedAuditId({ ...input, requested: void 0 })}\`).`
19097
+ );
19098
+ }
18252
19099
  if (newest !== void 0 && requested < newest) {
18253
19100
  throw new Error(
18254
19101
  `"${requested}" sorts before "${newest}", and audits merge latest-wins in lexical order \u2014 its scores would be outvoted by the older ones they replace. Name one that sorts last (e.g. \`${suggestedAuditId(input)}\`).`
@@ -18257,7 +19104,7 @@ function scopedAuditId(input) {
18257
19104
  return requested;
18258
19105
  }
18259
19106
  if (open !== void 0 && (newest === void 0 || open >= newest)) return open;
18260
- for (const candidate of scopedCandidates(month)) {
19107
+ for (const candidate of scopedCandidates(month, known)) {
18261
19108
  if (known.includes(candidate)) continue;
18262
19109
  if (newest !== void 0 && candidate < newest) {
18263
19110
  throw new Error(
@@ -18268,13 +19115,16 @@ function scopedAuditId(input) {
18268
19115
  }
18269
19116
  throw new Error(`99 scoped audits in ${month} \u2014 name the next one yourself.`);
18270
19117
  }
18271
- function* scopedCandidates(month) {
18272
- for (let n = 1; n < 100; n++) yield n === 1 ? `${month}-scoped` : `${month}-scoped-${String(n).padStart(2, "0")}`;
19118
+ function* scopedCandidates(month, known) {
19119
+ const newest = [...known].sort().at(-1) ?? "";
19120
+ const stem = newest.replace(/-scoped(-\d+)?$/, "");
19121
+ const base = `${month}-scoped` < newest && isPlanPartId(stem) ? stem : month;
19122
+ for (let n = 1; n < 100; n++) yield n === 1 ? `${base}-scoped` : `${base}-scoped-${String(n).padStart(2, "0")}`;
18273
19123
  }
18274
19124
  function suggestedAuditId({ since, month, requested, known, recorded }) {
18275
19125
  const taken = /* @__PURE__ */ new Set([...known, ...recorded, since, ...requested !== void 0 ? [requested] : []]);
18276
19126
  const floor = [...taken].sort().at(-1);
18277
- for (const candidate of scopedCandidates(month)) {
19127
+ for (const candidate of scopedCandidates(month, known)) {
18278
19128
  if (taken.has(candidate)) continue;
18279
19129
  if (floor === void 0 || candidate > floor) return candidate;
18280
19130
  }
@@ -18284,8 +19134,9 @@ function scopeSummary(scope) {
18284
19134
  const direct = scope.cells.length - scope.widened;
18285
19135
  const cells = `${scope.cells.length} cell${scope.cells.length === 1 ? "" : "s"} to re-score`;
18286
19136
  const split = scope.widened > 0 ? ` (${direct} direct, ${scope.widened} widened)` : "";
18287
- const from = `${scope.findings.length} resolved finding${scope.findings.length === 1 ? "" : "s"}`;
18288
- return `${cells}${split} from ${from}${scope.since !== null ? ` since ${scope.since}` : ""}`;
19137
+ const count = scope.findings.length;
19138
+ const from = count > 0 ? ` from ${count} resolved finding${count === 1 ? "" : "s"}` : "";
19139
+ return `${cells}${split}${from}${scope.since !== null ? ` since ${scope.since}` : ""}`;
18289
19140
  }
18290
19141
 
18291
19142
  // ../schema/src/quality-burndown.ts
@@ -18295,13 +19146,13 @@ var EVENT_CAUSE = {
18295
19146
  "quality.finding.accepted": "accepted",
18296
19147
  "quality.audit.completed": "audit"
18297
19148
  };
18298
- var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
19149
+ var isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
18299
19150
  var isString2 = (value) => typeof value === "string" && value !== "";
18300
19151
  var emptyCounts = () => ({ critical: 0, high: 0, medium: 0, low: 0, info: 0 });
18301
19152
  var asSeverity = (value) => typeof value === "string" && FINDING_SEVERITIES.includes(value) ? value : null;
18302
19153
  function cleanCounts2(raw) {
18303
19154
  const counts = emptyCounts();
18304
- if (!isRecord3(raw)) return counts;
19155
+ if (!isRecord5(raw)) return counts;
18305
19156
  for (const severity of FINDING_SEVERITIES) {
18306
19157
  const value = raw[severity];
18307
19158
  if (typeof value === "number" && Number.isFinite(value) && value > 0) counts[severity] = value;
@@ -18316,19 +19167,19 @@ function deriveFindingsBurndown(events, options = {}) {
18316
19167
  const filtered = surface !== void 0 || domain2 !== void 0;
18317
19168
  const sectionById = /* @__PURE__ */ new Map();
18318
19169
  for (const finding of Array.isArray(options.findings) ? options.findings : []) {
18319
- if (isRecord3(finding) && isString2(finding.id)) sectionById.set(finding.id, finding);
19170
+ if (isRecord5(finding) && isString2(finding.id)) sectionById.set(finding.id, finding);
18320
19171
  }
18321
- const inView = (where) => {
19172
+ const inView = (where2) => {
18322
19173
  if (!filtered) return true;
18323
- if (where === void 0) return false;
18324
- if (surface !== void 0 && where.surface !== surface) return false;
18325
- if (domain2 !== void 0 && (!isString2(where.criterion_id) || domainCodeOf(where.criterion_id, library) !== domain2)) {
19174
+ if (where2 === void 0) return false;
19175
+ if (surface !== void 0 && where2.surface !== surface) return false;
19176
+ if (domain2 !== void 0 && (!isString2(where2.criterion_id) || domainCodeOf(where2.criterion_id, library) !== domain2)) {
18326
19177
  return false;
18327
19178
  }
18328
19179
  return true;
18329
19180
  };
18330
19181
  const relevant = (Array.isArray(events) ? events : []).filter(
18331
- (event) => isRecord3(event) && typeof event.type === "string" && event.type in EVENT_CAUSE
19182
+ (event) => isRecord5(event) && typeof event.type === "string" && event.type in EVENT_CAUSE
18332
19183
  );
18333
19184
  const openedIds = /* @__PURE__ */ new Set();
18334
19185
  const decidedIds = /* @__PURE__ */ new Set();
@@ -18444,19 +19295,17 @@ function burndownSummary(burndown, openNow) {
18444
19295
  if (burndown.points.length === 0) return null;
18445
19296
  const tally = burndown.since ?? burndown;
18446
19297
  const closed = tally.resolved + tally.accepted;
18447
- const where = burndown.since ? ` since the ${burndown.since.audit_id} audit` : "";
19298
+ const where2 = burndown.since ? ` since the ${burndown.since.audit_id} audit` : "";
18448
19299
  const open = openNow ?? openTotal(burndown.points[burndown.points.length - 1].open);
18449
- return `${closed} closed${where} (${tally.resolved} resolved, ${tally.accepted} accepted) \xB7 ${tally.opened} opened \xB7 ${open} open`;
19300
+ return `${closed} closed${where2} (${tally.resolved} resolved, ${tally.accepted} accepted) \xB7 ${tally.opened} opened \xB7 ${open} open`;
18450
19301
  }
18451
19302
 
18452
19303
  // ../schema/src/quality-baseline.ts
18453
19304
  var EPOCH = "1970-01-01T00:00:00.000Z";
18454
19305
  var DECISIONS = /* @__PURE__ */ new Set(["quality.finding.resolved", "quality.finding.accepted"]);
18455
19306
  var REVERTIBLE = /* @__PURE__ */ new Set(["resolved", "accepted-risk"]);
18456
- var SCOPED_AUDIT_ID = /-scoped(-\d+)?$/;
18457
19307
  var rowsOf3 = (value) => Array.isArray(value) ? value : [];
18458
19308
  var isString3 = (value) => typeof value === "string" && value !== "";
18459
- var isScopedAuditId = (value) => isString3(value) && SCOPED_AUDIT_ID.test(value);
18460
19309
  var isRow = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
18461
19310
  var objectRowsOf = (value) => rowsOf3(value).filter(isRow);
18462
19311
  function omit2(obj, keys) {
@@ -18475,8 +19324,8 @@ function oneMsBefore(iso) {
18475
19324
  }
18476
19325
  function implicitAuditBaseline(events, section, library) {
18477
19326
  const rows = objectRowsOf(events);
18478
- if (rows.some((event) => event.type === "quality.audit.completed")) return null;
18479
- const assessmentRows = objectRowsOf(section?.assessments).filter((row) => !isScopedAuditId(row.audit_id));
19327
+ if (rows.some((event) => event.type === "quality.audit.completed" && !isPlanRecord(event))) return null;
19328
+ const assessmentRows = objectRowsOf(section?.assessments).filter((row) => !isPartialAuditId(row.audit_id));
18480
19329
  const taggedAssessments = assessmentRows.filter((row) => isString3(row.audit_id));
18481
19330
  if (taggedAssessments.length === 0) return null;
18482
19331
  const auditId = taggedAssessments.map((row) => row.audit_id).sort().at(-1);
@@ -18681,7 +19530,8 @@ function declaredScopeSince(auditId, recorded) {
18681
19530
  return since;
18682
19531
  }
18683
19532
  function auditOrderNote(root, auditId) {
18684
- const later = listAuditIds(root).filter((id) => id > auditId);
19533
+ const plan = planIdOfPartId(auditId);
19534
+ const later = listAuditIds(root).filter((id) => id > auditId && (plan === null || planIdOfPartId(id) !== plan));
18685
19535
  if (later.length === 0) return void 0;
18686
19536
  return `"${auditId}" sorts before ${later.map((id) => `"${id}"`).join(", ")} \u2014 audits merge latest-wins in id order, so for any cell ${later.length === 1 ? "that audit" : "those audits"} also hold${later.length === 1 ? "s" : ""}, the later score wins. Name a new audit so it sorts last.`;
18687
19537
  }
@@ -18709,10 +19559,190 @@ function locateFinding(root, id) {
18709
19559
  return void 0;
18710
19560
  }
18711
19561
 
19562
+ // ../schema/src/cli/kritik-plan.ts
19563
+ import { spawnSync } from "node:child_process";
19564
+ import { existsSync as existsSync3, readdirSync as readdirSync2, statSync as statSync2 } from "node:fs";
19565
+ import { join as join3 } from "node:path";
19566
+ var plansDir = (root) => join3(root, QUALITY_DIR, PLAN_PLANS_DIR);
19567
+ var planPath = (root, planId2) => join3(plansDir(root), `${planId2}.json`);
19568
+ function listPlanIds(root) {
19569
+ const dir = plansDir(root);
19570
+ if (!existsSync3(dir)) return [];
19571
+ return readdirSync2(dir).filter((name) => name.endsWith(".json") && statSync2(join3(dir, name)).isFile()).map((name) => name.slice(0, -".json".length)).filter((id) => isPlanId(id)).sort();
19572
+ }
19573
+ function readPlanFile(path) {
19574
+ if (!existsSync3(path)) throw new Error(`no plan at ${path}`);
19575
+ const parsed = parseKritikPlan(readJson(path));
19576
+ if (!parsed.ok) throw new Error(`${path}: ${parsed.issue}`);
19577
+ return parsed.plan;
19578
+ }
19579
+ function loadPlan(root, planId2) {
19580
+ if (!isPlanId(planId2)) {
19581
+ throw new Error(`"${planId2}" is not a plan id \u2014 a plan id reads YYYY-MM-zplan-DDNN, as \`arkaik kritik plan\` prints it.`);
19582
+ }
19583
+ const path = planPath(root, planId2);
19584
+ const plan = readPlanFile(path);
19585
+ if (plan.planId !== planId2) {
19586
+ throw new Error(`${path} holds the plan "${plan.planId}", not "${planId2}" \u2014 a plan file is named for its plan id.`);
19587
+ }
19588
+ return plan;
19589
+ }
19590
+ function savePlan(path, plan) {
19591
+ writeJson(path, plan);
19592
+ }
19593
+ function gitHead(root) {
19594
+ try {
19595
+ const result = spawnSync("git", ["rev-parse", "HEAD"], { cwd: root, encoding: "utf8" });
19596
+ if (result.error !== void 0 || result.status !== 0) return null;
19597
+ const sha = result.stdout.trim();
19598
+ return /^[0-9a-f]{40}$/.test(sha) ? sha : null;
19599
+ } catch {
19600
+ return null;
19601
+ }
19602
+ }
19603
+ function createPlan(root, library, runTokens, options = {}) {
19604
+ const profile = requireProfile(root);
19605
+ const surfaces = (profile.surfaces ?? []).map((surface) => surface.id);
19606
+ const { runs, warnings } = parseRun(runTokens, {
19607
+ domains: (library.domains ?? []).map((domain2) => domain2.code),
19608
+ surfaces
19609
+ });
19610
+ const known = [.../* @__PURE__ */ new Set([...listAuditIds(root), ...listPlanIds(root), ...options.recorded ?? []])];
19611
+ const plan = buildKritikPlan({
19612
+ library,
19613
+ surfaces,
19614
+ runs,
19615
+ known,
19616
+ now: options.now ?? /* @__PURE__ */ new Date(),
19617
+ commit: gitHead(root)
19618
+ });
19619
+ return { plan, warnings };
19620
+ }
19621
+ function planStatus(root, plan) {
19622
+ const scoresByPart = Object.fromEntries(
19623
+ plan.parts.map((part) => [part.auditId, loadScoresOrEmpty(root, part.auditId).assessments])
19624
+ );
19625
+ return planPartStatuses(plan, scoresByPart);
19626
+ }
19627
+ var cellLabel = (cell) => `${cell.criterion_id} on ${cell.surface}`;
19628
+ var runFlags = (parts) => parts.map((part) => `--run ${part.domain}:${part.surface}`).join(" ");
19629
+ function preparePlanRecord(root, planId2, library, events) {
19630
+ const plan = loadPlan(root, planId2);
19631
+ if (recordedPlans(events).some((recorded) => recorded.plan === planId2) || recordedAuditIds(events).includes(planId2)) {
19632
+ throw new Error(
19633
+ `plan "${planId2}" is already recorded \u2014 its reading is history, and the journal is append-only. To correct it, make a new plan for the same parts (\`arkaik kritik plan ${runFlags(plan.parts)}\`) and record that one.`
19634
+ );
19635
+ }
19636
+ const included = plan.parts.filter((part) => part.status === "included");
19637
+ if (included.length === 0) {
19638
+ throw new Error(`plan "${planId2}" includes no part \u2014 every part was deferred, so there is nothing to record.`);
19639
+ }
19640
+ const recordedAlone = included.filter(
19641
+ (part) => events.some((event) => event?.type === "quality.audit.completed" && event.audit_id === part.auditId)
19642
+ );
19643
+ if (recordedAlone.length > 0) {
19644
+ const [first] = recordedAlone;
19645
+ throw new Error(
19646
+ `plan "${planId2}" cannot be recorded \u2014 its part "${first.auditId}" was already recorded on its own` + (recordedAlone.length > 1 ? ` (and ${recordedAlone.slice(1).map((part) => `"${part.auditId}"`).join(", ")})` : "") + `, and a part recorded on its own cannot be folded into a plan record: its reading is history, and the journal is append-only. To record these cells as a plan, make a new plan: \`arkaik kritik plan ${runFlags(plan.parts)}\`.`
19647
+ );
19648
+ }
19649
+ const surfaces = (requireProfile(root).surfaces ?? []).map((surface) => surface.id);
19650
+ const moved = [];
19651
+ if (plan.frameworkVersion !== library.version) {
19652
+ moved.push(`the framework is ${library.version} now, and the plan was made against ${plan.frameworkVersion}`);
19653
+ }
19654
+ for (const part of included) {
19655
+ const current = planCells(library, surfaces, { domain: part.domain, surface: part.surface }).cells;
19656
+ const was = new Set(part.cells.map((cell) => planCellKey(cell.criterion_id, cell.surface)));
19657
+ const is = new Set(current.map((cell) => planCellKey(cell.criterion_id, cell.surface)));
19658
+ const added = current.filter((cell) => !was.has(planCellKey(cell.criterion_id, cell.surface)));
19659
+ const removed = part.cells.filter((cell) => !is.has(planCellKey(cell.criterion_id, cell.surface)));
19660
+ const changes = [];
19661
+ if (added.length > 0) changes.push(`gained ${added.map((cell) => cell.criterion_id).join(", ")}`);
19662
+ if (removed.length > 0) changes.push(`lost ${removed.map((cell) => cell.criterion_id).join(", ")}`);
19663
+ if (changes.length > 0) moved.push(`${part.domain}:${part.surface} ${changes.join(" and ")}`);
19664
+ }
19665
+ if (moved.length > 0) {
19666
+ throw new Error(
19667
+ `the cells have moved since plan "${planId2}" was made \u2014 ${moved.join("; ")}. Make a new plan: \`arkaik kritik plan ${runFlags(included)}\`.`
19668
+ );
19669
+ }
19670
+ const onDiskIds = listAuditIds(root);
19671
+ const outsorted = included.map((part) => ({ part, later: outsortedBy(part.auditId, onDiskIds) })).filter((entry) => entry.later.length > 0);
19672
+ if (outsorted.length > 0) {
19673
+ throw new Error(
19674
+ `plan "${planId2}" cannot be recorded \u2014 audits merge latest-wins in id order, and on any cell an audit sorting after a part also holds, that part's scores would lose the merge:
19675
+ ` + outsorted.map(({ part, later }) => ` ${part.auditId}: ${later.map((id) => `"${id}"`).join(", ")} now sort${later.length === 1 ? "s" : ""} after it`).join("\n") + `
19676
+ Make a new plan for the affected parts and score them again: \`arkaik kritik plan ${runFlags(outsorted.map(({ part }) => part))}\` names parts that sort last again.`
19677
+ );
19678
+ }
19679
+ const last = included.map((part) => part.auditId).sort()[included.length - 1];
19680
+ const ownParts = new Set(included.map((part) => part.auditId));
19681
+ const recordedIds = new Set(recordedAuditIds(events));
19682
+ const unannounced = onDiskIds.filter((id) => id < last && !ownParts.has(id) && !recordedIds.has(id)).map((id) => ({ id, scores: loadScoresOrEmpty(root, id).assessments.length })).filter((entry) => entry.scores > 0);
19683
+ if (unannounced.length > 0) {
19684
+ throw new Error(
19685
+ `plan "${planId2}" cannot be recorded \u2014 ${unannounced.length === 1 ? "an audit directory sorts" : "audit directories sort"} before its last part, ${unannounced.length === 1 ? "holds scores and was" : "hold scores and were"} never recorded. The record merges every audit through the plan's last part but names only the plan's own cells as re-scored, so ${unannounced.length === 1 ? "its scores" : "their scores"} would enter this plan's record unannounced:
19686
+ ` + unannounced.map(({ id, scores }) => {
19687
+ const owner = planIdOfPartId(id);
19688
+ return ` ${id}: ${scores} score${scores === 1 ? "" : "s"}, never recorded` + (owner !== null ? ` (a part of plan "${owner}")` : "");
19689
+ }).join("\n") + `
19690
+ Record each first, or remove its scores (docs/quality/audits/<id>/scores.json), then record this plan.`
19691
+ );
19692
+ }
19693
+ const onDisk = new Set(onDiskIds);
19694
+ const scoresByPart = {};
19695
+ for (const part of included) scoresByPart[part.auditId] = loadScoresOrEmpty(root, part.auditId).assessments;
19696
+ const statuses = planPartStatuses({ parts: included }, scoresByPart);
19697
+ const strays = statuses.filter((status) => status.stray.length > 0);
19698
+ if (strays.length > 0) {
19699
+ const count = strays.reduce((sum, status) => sum + status.stray.length, 0);
19700
+ throw new Error(
19701
+ `${count} score${count === 1 ? "" : "s"} outside plan "${planId2}" \u2014 the merge reads every audit directory, so ${count === 1 ? "it" : "they"} would enter the recorded matrix anyway. Remove ${count === 1 ? "it" : "them"} before recording, or make a plan that includes ${count === 1 ? "it" : "them"}:
19702
+ ` + strays.map(
19703
+ (status) => ` ${status.auditId}: ${status.stray.map(cellLabel).join(", ")} \u2014 for each, delete its row from docs/quality/audits/${status.auditId}/scores.json`
19704
+ ).join("\n")
19705
+ );
19706
+ }
19707
+ const unscored = statuses.filter((status) => status.missing.length > 0);
19708
+ if (unscored.length > 0) {
19709
+ const count = unscored.reduce((sum, status) => sum + status.missing.length, 0);
19710
+ throw new Error(
19711
+ `${count} plan cell${count === 1 ? " has" : "s have"} no score yet \u2014 a plan records once, after every part is scored (\`arkaik kritik plan --status ${planId2}\`):
19712
+ ` + unscored.map(
19713
+ (status) => onDisk.has(status.auditId) ? ` ${status.auditId}: ${status.missing.map(cellLabel).join(", ")}` : ` ${status.auditId}: no audit directory in this checkout \u2014 if this part ran in another worktree, copy or merge its docs/quality/audits/${status.auditId}/ here first`
19714
+ ).join("\n")
19715
+ );
19716
+ }
19717
+ const section = loadQualitySectionThrough(root, last, library);
19718
+ const matrix = deriveQualityMatrix({ quality: section }, library);
19719
+ const scored = included.flatMap((part) => part.cells.map((cell) => planCellKey(cell.criterion_id, cell.surface)));
19720
+ const since = scopeAnchorId(events);
19721
+ const scope = {
19722
+ partial: true,
19723
+ cells: scored.length,
19724
+ ...since !== null ? { since } : {},
19725
+ plan: plan.planId,
19726
+ parts: included.map((part) => part.auditId),
19727
+ scored,
19728
+ coverage: coverageOf(section, library, scored.length)
19729
+ };
19730
+ const input = auditCompletedInput(matrix, {
19731
+ audit_id: plan.planId,
19732
+ framework_version: plan.frameworkVersion,
19733
+ ...plan.commit !== null ? { commit: plan.commit } : {},
19734
+ scope
19735
+ });
19736
+ return { plan, section, matrix, scope, input };
19737
+ }
19738
+
19739
+ // src/kritik-tools.ts
19740
+ import { existsSync as existsSync8 } from "node:fs";
19741
+
18712
19742
  // ../cli/src/lib/bundle-io.ts
18713
- import { existsSync as existsSync3, readFileSync as readFileSync2 } from "node:fs";
19743
+ import { existsSync as existsSync4, readFileSync as readFileSync2 } from "node:fs";
18714
19744
  function readBundle(filePath) {
18715
- if (!existsSync3(filePath)) throw new Error(`File not found: ${filePath}`);
19745
+ if (!existsSync4(filePath)) throw new Error(`File not found: ${filePath}`);
18716
19746
  let parsed;
18717
19747
  try {
18718
19748
  parsed = JSON.parse(readFileSync2(filePath, "utf8"));
@@ -18728,19 +19758,19 @@ function readBundle(filePath) {
18728
19758
  }
18729
19759
 
18730
19760
  // ../cli/src/lib/journal-io.ts
18731
- import { appendFileSync, existsSync as existsSync4, mkdirSync as mkdirSync2, readdirSync as readdirSync2, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "node:fs";
18732
- import { dirname as dirname2, join as join3 } from "node:path";
19761
+ import { appendFileSync, existsSync as existsSync5, mkdirSync as mkdirSync2, readdirSync as readdirSync3, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "node:fs";
19762
+ import { dirname as dirname2, join as join4 } from "node:path";
18733
19763
  var JOURNAL_SIDECAR = "journal.jsonl";
18734
19764
  function journalPathFor(bundlePath) {
18735
- return join3(dirname2(bundlePath), JOURNAL_SIDECAR);
19765
+ return join4(dirname2(bundlePath), JOURNAL_SIDECAR);
18736
19766
  }
18737
19767
  function archivePathsFor(journalPath) {
18738
- const dir = join3(dirname2(journalPath), "journal");
18739
- if (!existsSync4(dir)) return [];
18740
- return readdirSync2(dir).filter((name) => name.startsWith("archive-") && name.endsWith(".jsonl")).sort().map((name) => join3(dir, name));
19768
+ const dir = join4(dirname2(journalPath), "journal");
19769
+ if (!existsSync5(dir)) return [];
19770
+ return readdirSync3(dir).filter((name) => name.startsWith("archive-") && name.endsWith(".jsonl")).sort().map((name) => join4(dir, name));
18741
19771
  }
18742
19772
  function readJournalEvents(journalPath) {
18743
- if (!existsSync4(journalPath)) return [];
19773
+ if (!existsSync5(journalPath)) return [];
18744
19774
  return parseJournalLines(readFileSync3(journalPath, "utf8")).events;
18745
19775
  }
18746
19776
  function readFullJournalEvents(journalPath) {
@@ -18755,7 +19785,7 @@ function toLine(event) {
18755
19785
  }
18756
19786
  function appendJournalEvent(journalPath, event) {
18757
19787
  const line = toLine(event);
18758
- if (!existsSync4(journalPath)) {
19788
+ if (!existsSync5(journalPath)) {
18759
19789
  mkdirSync2(dirname2(journalPath), { recursive: true });
18760
19790
  writeFileSync2(journalPath, line);
18761
19791
  return;
@@ -18766,16 +19796,16 @@ function appendJournalEvent(journalPath, event) {
18766
19796
  }
18767
19797
 
18768
19798
  // ../cli/src/lib/kritik-io.ts
18769
- import { existsSync as existsSync5 } from "node:fs";
18770
- import { basename, dirname as dirname3, join as join4, resolve as resolve2 } from "node:path";
19799
+ import { existsSync as existsSync6 } from "node:fs";
19800
+ import { basename, dirname as dirname3, join as join5, resolve as resolve2 } from "node:path";
18771
19801
  import { fileURLToPath } from "node:url";
18772
- var DEFAULT_BUNDLE_PATH = join4("docs", "arkaik", "bundle.json");
18773
- var VENDORED_PACK = join4(QUALITY_DIR, PACK_FILE);
18774
- var BUNDLED_PACK = join4(dirname3(fileURLToPath(import.meta.url)), "assets", "kritik", "library.json");
19802
+ var DEFAULT_BUNDLE_PATH = join5("docs", "arkaik", "bundle.json");
19803
+ var VENDORED_PACK = join5(QUALITY_DIR, PACK_FILE);
19804
+ var BUNDLED_PACK = join5(dirname3(fileURLToPath(import.meta.url)), "assets", "kritik", "library.json");
18775
19805
  function resolvePack(root) {
18776
- const vendored = join4(root, VENDORED_PACK);
18777
- if (existsSync5(vendored)) return { library: readJson(vendored), path: vendored, vendored: true };
18778
- if (!existsSync5(BUNDLED_PACK)) {
19806
+ const vendored = join5(root, VENDORED_PACK);
19807
+ if (existsSync6(vendored)) return { library: readJson(vendored), path: vendored, vendored: true };
19808
+ if (!existsSync6(BUNDLED_PACK)) {
18779
19809
  throw new Error(
18780
19810
  `no criteria pack found. Looked in:
18781
19811
  ${vendored}
@@ -18790,8 +19820,8 @@ function loadKritikLibrary(root) {
18790
19820
  return { library: mergeKritikLibrary(pack.library, loadOverlay(root)), pack };
18791
19821
  }
18792
19822
  function resolveJournal(root, bundlePath) {
18793
- const resolved = bundlePath ?? join4(root, DEFAULT_BUNDLE_PATH);
18794
- return { bundlePath: resolved, journalPath: journalPathFor(resolved), present: existsSync5(resolved) };
19823
+ const resolved = bundlePath ?? join5(root, DEFAULT_BUNDLE_PATH);
19824
+ return { bundlePath: resolved, journalPath: journalPathFor(resolved), present: existsSync6(resolved) };
18795
19825
  }
18796
19826
  function resolveQualityRoot(options) {
18797
19827
  if (options.root !== void 0) return resolve2(options.fallback, options.root);
@@ -18803,7 +19833,7 @@ function resolveQualityRoot(options) {
18803
19833
  }
18804
19834
 
18805
19835
  // ../cli/src/lib/bundle-validate.ts
18806
- import { existsSync as existsSync6, readFileSync as readFileSync4 } from "node:fs";
19836
+ import { existsSync as existsSync7, readFileSync as readFileSync4 } from "node:fs";
18807
19837
  import { basename as basename2 } from "node:path";
18808
19838
  function validateBundleAt(filePath) {
18809
19839
  const bundle = readBundle(filePath);
@@ -18818,7 +19848,7 @@ function validateBundleAt(filePath) {
18818
19848
  if (loose.journal === void 0) {
18819
19849
  const sidecarPath = journalPathFor(filePath);
18820
19850
  const folded = [];
18821
- if (existsSync6(sidecarPath)) {
19851
+ if (existsSync7(sidecarPath)) {
18822
19852
  const { events, findings } = parseJournalLines(readFileSync4(sidecarPath, "utf8"));
18823
19853
  sidecarFindings = findings;
18824
19854
  sidecarLoaded = true;
@@ -18873,6 +19903,10 @@ async function appendHosted(store2, inputs) {
18873
19903
  }
18874
19904
  }
18875
19905
  var NO_HOSTED_AUDIT = "This hosted project has no audit to measure from. One must be run in the repository and restored (`arkaik restore`) first \u2014 a hosted session cannot write one.";
19906
+ function planOnlyNote(plans) {
19907
+ return `only plan records are in this journal (${plans.join(", ")}) \u2014 a plan record is never what a scope is measured from. Until a full audit is recorded, re-check a fix by running its plan part again: kritik_plan, then kritik_matrix with plan=true and record=true.`;
19908
+ }
19909
+ var lastAuditOf = (reading) => reading.auditIds[reading.auditIds.length - 1];
18876
19910
  function hostedSection(graph) {
18877
19911
  const section = graph.loaded.bundle.quality;
18878
19912
  if (section === void 0 || !Array.isArray(section.findings) || !Array.isArray(section.assessments)) {
@@ -18913,22 +19947,23 @@ function openFindingsSummary(findings, library) {
18913
19947
  }));
18914
19948
  return { open, lanes, p0 };
18915
19949
  }
18916
- function resolveAuditPair(audits, args, notFoundHint) {
18917
- if (audits.length < 2) {
19950
+ function resolveAuditPair(readings, args, notFoundHint) {
19951
+ if (readings.length < 2) {
18918
19952
  throw new ToolError(
18919
- `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.`
19953
+ `regressions needs two audits to compare \u2014 ${readings.length === 0 ? `${notFoundHint} holds none` : `only "${readings[0].id}" exists`}. A regression is the difference between two readings; one reading is a baseline.`
18920
19954
  );
18921
19955
  }
18922
19956
  const known = (id) => {
18923
- if (!audits.includes(id)) throw new ToolError(`no audit "${id}" ${notFoundHint} (have: ${audits.join(", ")})`);
18924
- return id;
19957
+ const reading = readingOf(readings, id);
19958
+ if (reading === void 0) throw new ToolError(`no audit "${id}" ${notFoundHint} (have: ${readings.map((r) => r.id).join(", ")})`);
19959
+ return reading;
18925
19960
  };
18926
- const to = typeof args.to === "string" && args.to !== "" ? known(args.to) : audits[audits.length - 1];
18927
- const from = typeof args.from === "string" && args.from !== "" ? known(args.from) : audits[audits.indexOf(to) - 1];
18928
- if (from === void 0) throw new ToolError(`"${to}" is the oldest audit \u2014 there is nothing before it to compare against.`);
18929
- if (from === to) throw new ToolError(`from and to name the same audit ("${to}") \u2014 a regression needs two readings.`);
18930
- if (audits.indexOf(from) > audits.indexOf(to)) {
18931
- throw new ToolError(`from "${from}" is newer than to "${to}" \u2014 swap them, or the comparison inverts.`);
19961
+ const to = typeof args.to === "string" && args.to !== "" ? known(args.to) : readings[readings.length - 1];
19962
+ const from = typeof args.from === "string" && args.from !== "" ? known(args.from) : readings[readings.indexOf(to) - 1];
19963
+ if (from === void 0) throw new ToolError(`"${to.id}" is the oldest audit \u2014 there is nothing before it to compare against.`);
19964
+ if (from === to) throw new ToolError(`from and to name the same audit ("${to.id}") \u2014 a regression needs two readings.`);
19965
+ if (readings.indexOf(from) > readings.indexOf(to)) {
19966
+ throw new ToolError(`from "${from.id}" is newer than to "${to.id}" \u2014 swap them, or the comparison inverts.`);
18932
19967
  }
18933
19968
  return { from, to };
18934
19969
  }
@@ -19006,6 +20041,13 @@ function auditForWrite(root, requested) {
19006
20041
  const existing = listAuditIds(root);
19007
20042
  return existing.length > 0 ? existing[existing.length - 1] : currentAuditId();
19008
20043
  }
20044
+ function refuseOutsortedPart(root, auditId) {
20045
+ const later = outsortedBy(auditId, listAuditIds(root));
20046
+ if (later.length === 0) return;
20047
+ throw new ToolError(
20048
+ `"${auditId}" is a part of plan ${planIdOfPartId(auditId)}, and ${later.map((id) => `"${id}"`).join(", ")} now sort${later.length === 1 ? "s" : ""} after it \u2014 audits merge latest-wins in id order, so on any cell ${later.length === 1 ? "both hold" : "they share with it"}, this part's scores would lose the merge. Nothing written. Make a new plan for the parts not yet scored: kritik_plan names parts that sort last again.`
20049
+ );
20050
+ }
19009
20051
  function buildKritikCatalog(ctx) {
19010
20052
  const tools2 = [];
19011
20053
  const handlers2 = {};
@@ -19053,8 +20095,15 @@ function buildKritikCatalog(ctx) {
19053
20095
  events = graph.journal;
19054
20096
  }
19055
20097
  if (options.since !== void 0) {
19056
- const recorded = recordedAuditIds(events);
19057
- if (!recorded.includes(options.since)) {
20098
+ const recordedAll = recordedAuditIds(events);
20099
+ const recorded = recordedSinceIds(events);
20100
+ const since = options.since;
20101
+ if (isPlanId(since) || isPlanPartId(since) || recordedAll.includes(since) && !recorded.includes(since)) {
20102
+ throw new ToolError(
20103
+ `"${since}" is a plan record, never a scope's anchor \u2014 a scope is measured from a full or scoped audit (recorded: ${recorded.join(", ") || "none"}).`
20104
+ );
20105
+ }
20106
+ if (!recorded.includes(since)) {
19058
20107
  const hint = ctx.qualityRoot !== void 0 ? "A scope is measured from a recorded reading \u2014 kritik_matrix with record=true writes one." : recorded.length > 0 ? "Pass one of the recorded audits, or leave since off to measure from the newest." : NO_HOSTED_AUDIT;
19059
20108
  throw new ToolError(`No recorded audit "${options.since}" in this journal (recorded: ${recorded.join(", ") || "none"}). ${hint}`);
19060
20109
  }
@@ -19064,7 +20113,7 @@ function buildKritikCatalog(ctx) {
19064
20113
  tool(
19065
20114
  {
19066
20115
  name: "kritik_matrix",
19067
- 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, and record=true (with the audit_id kritik_score returned) records that scoped re-audit \u2014 the server computes the reading from the scores it holds, rather than accepting one on the wire. A scoped re-audit (scored with kritik_score scope=true, or, in repo mode, declared with scope=true here) returns `scope` and records the MERGED matrix through it with a scope marker, so the trend never reads its unscored cells as dropped; matrix.json stays this audit alone.",
20116
+ 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, and record=true (with the audit_id kritik_score returned) records that scoped re-audit \u2014 the server computes the reading from the scores it holds, rather than accepting one on the wire. A scoped re-audit (scored with kritik_score scope=true, or, in repo mode, declared with scope=true here) returns `scope` and records the MERGED matrix through it with a scope marker, so the trend never reads its unscored cells as dropped; matrix.json stays this audit alone. With plan=true (repo mode only) audit_id is a plan made by kritik_plan: it returns the plan's merged reading \u2014 every audit through its last part, latest-wins \u2014 with `scope` (the plan marker), `coverage` and `coverage_notes`, writes nothing, and with record=true appends it as one quality.audit.completed under the plan id, after checking the plan's cells have not moved, no audit sorts after one of its parts, and every part scored exactly its cells. A plan part's own id is refused with record or scope: a plan records once, as a whole.",
19068
20117
  inputSchema: {
19069
20118
  type: "object",
19070
20119
  properties: {
@@ -19080,6 +20129,10 @@ function buildKritikCatalog(ctx) {
19080
20129
  type: "boolean",
19081
20130
  description: "Treat the audit as a scoped re-audit even though it was scored without kritik_score scope=true (which marks it). Repo mode only."
19082
20131
  },
20132
+ plan: {
20133
+ type: "boolean",
20134
+ description: "audit_id is a plan made by kritik_plan: return its merged reading with scope and coverage, and with record=true append it as one quality.audit.completed under the plan id. Repo mode only; never with scope."
20135
+ },
19083
20136
  commit: {
19084
20137
  type: "string",
19085
20138
  description: "Hosted record only: the commit the scoped re-audit read. Repo mode reads it from the audit's scores.json."
@@ -19091,6 +20144,11 @@ function buildKritikCatalog(ctx) {
19091
20144
  async (args) => {
19092
20145
  const hosted = ctx.qualityRoot === void 0;
19093
20146
  if (hosted) {
20147
+ if (args.plan === true) {
20148
+ throw new ToolError(
20149
+ "plan=true records a planned partial audit, whose parts live in docs/quality/audits/ \u2014 a hosted session has none. Run it where the checkout is \u2014 `arkaik-mcp --bundle <path>`."
20150
+ );
20151
+ }
19094
20152
  if (args.record === true) {
19095
20153
  if (typeof args.audit_id !== "string" || args.audit_id === "") {
19096
20154
  throw new ToolError(
@@ -19167,12 +20225,63 @@ function buildKritikCatalog(ctx) {
19167
20225
  }
19168
20226
  const root = repoRootOf(ctx, REPO_MODE_ONLY);
19169
20227
  const library = libraryOf(root);
20228
+ if (args.plan === true) {
20229
+ const requested = typeof args.audit_id === "string" && args.audit_id !== "" ? args.audit_id : void 0;
20230
+ if (args.scope === true) {
20231
+ throw new ToolError("plan=true and scope=true cannot be combined \u2014 a plan records its own scope marker, measured from the newest full or scoped audit.");
20232
+ }
20233
+ if (requested === void 0) {
20234
+ const plans = listPlanIds(root);
20235
+ throw new ToolError(`plan=true needs the plan id as audit_id (plans: ${plans.join(", ") || "none \u2014 kritik_plan makes one"}).`);
20236
+ }
20237
+ if (isPlanPartId(requested)) {
20238
+ const owner = planIdOfPartId(requested) ?? requested;
20239
+ throw new ToolError(`"${requested}" is one part of plan "${owner}" \u2014 pass the plan id: audit_id "${owner}" with plan=true.`);
20240
+ }
20241
+ const graph2 = await load2();
20242
+ let prepared;
20243
+ try {
20244
+ prepared = preparePlanRecord(root, requested, library, graph2.journal);
20245
+ } catch (error51) {
20246
+ throw new ToolError(error51.message);
20247
+ }
20248
+ const events2 = args.record === true ? await record2(graph2, [prepared.input]) : [];
20249
+ const { open: open2, lanes: lanes2, p0: p02 } = openFindingsSummary(prepared.section.findings, library);
20250
+ return {
20251
+ audit_id: prepared.plan.planId,
20252
+ ...prepared.plan.commit !== null ? { commit: prepared.plan.commit } : {},
20253
+ framework_version: prepared.plan.frameworkVersion,
20254
+ matrix: prepared.matrix.matrix,
20255
+ overall: prepared.matrix.overall,
20256
+ finding_counts: prepared.matrix.finding_counts,
20257
+ scope: prepared.scope,
20258
+ coverage: prepared.scope.coverage,
20259
+ coverage_notes: coverageNotes(prepared.scope.coverage, prepared.matrix.overall),
20260
+ assessment_count: prepared.section.assessments.length,
20261
+ open_findings: open2.length,
20262
+ lanes: lanes2,
20263
+ p0: p02,
20264
+ events: events2,
20265
+ ...args.record === true ? {} : { note: `Preview only \u2014 nothing written. record=true appends this reading as one quality.audit.completed under ${prepared.plan.planId}.` }
20266
+ };
20267
+ }
19170
20268
  let auditId;
19171
20269
  try {
19172
20270
  auditId = typeof args.audit_id === "string" && args.audit_id !== "" ? args.audit_id : newestAuditId(root);
19173
20271
  } catch (error51) {
19174
20272
  throw new ToolError(error51.message);
19175
20273
  }
20274
+ if (isPlanId(auditId)) {
20275
+ throw new ToolError(
20276
+ `"${auditId}" is a plan, not an audit \u2014 pass plan=true: audit_id "${auditId}" with plan=true previews its merged reading, and with record=true records it.`
20277
+ );
20278
+ }
20279
+ if (isPlanPartId(auditId) && (args.record === true || args.scope === true)) {
20280
+ const owner = planIdOfPartId(auditId) ?? auditId;
20281
+ throw new ToolError(
20282
+ `"${auditId}" is one part of plan "${owner}" \u2014 a plan records once, as a whole, and carries its own scope marker: kritik_matrix with audit_id "${owner}", plan=true and record=true.`
20283
+ );
20284
+ }
19176
20285
  let computed;
19177
20286
  try {
19178
20287
  computed = computeAuditMatrix(root, auditId, library);
@@ -19183,10 +20292,15 @@ function buildKritikCatalog(ctx) {
19183
20292
  const { open, lanes, p0 } = openFindingsSummary(section.findings, library);
19184
20293
  let graph;
19185
20294
  let since = loadScoresOrEmpty(root, auditId).scope?.since;
20295
+ if (since !== void 0 && (isPlanId(since) || isPlanPartId(since))) {
20296
+ throw new ToolError(
20297
+ `${scoresPath(root, auditId)} stamps "scope": { "since": "${since}" }, a plan or one of its parts \u2014 a scope is measured from a full or scoped audit, never from a plan. Stamp the full or scoped audit this one followed.`
20298
+ );
20299
+ }
19186
20300
  if (since === void 0 && args.scope === true) {
19187
20301
  graph = await load2();
19188
20302
  try {
19189
- since = declaredScopeSince(auditId, recordedAuditIds(graph.journal));
20303
+ since = declaredScopeSince(auditId, recordedSinceIds(graph.journal));
19190
20304
  } catch (error51) {
19191
20305
  throw new ToolError(`scope=true refused \u2014 ${error51.message}`);
19192
20306
  }
@@ -19322,8 +20436,8 @@ function buildKritikCatalog(ctx) {
19322
20436
  inputSchema: {
19323
20437
  type: "object",
19324
20438
  properties: {
19325
- from: { type: "string", description: "The older audit. Default: the audit before `to`." },
19326
- to: { type: "string", description: "The newer audit. Default: the newest on disk." },
20439
+ from: { type: "string", description: "The older reading. Default: the reading before `to`. A plan id, or any of its part ids, reads the whole plan." },
20440
+ to: { type: "string", description: "The newer reading. Default: the newest on disk. A plan id, or any of its part ids, reads the whole plan." },
19327
20441
  record: { type: "boolean", description: "Append one quality.signal.tripped per regression." }
19328
20442
  },
19329
20443
  additionalProperties: false
@@ -19342,8 +20456,10 @@ function buildKritikCatalog(ctx) {
19342
20456
  if (bucket) bucket.push(assessment);
19343
20457
  else grouped.set(assessment.audit_id, [assessment]);
19344
20458
  }
19345
- const audits2 = [...grouped.keys()].sort();
19346
- const { from: from2, to: to2 } = resolveAuditPair(audits2, args, "in this project's assessments");
20459
+ const audits = [...grouped.keys()].sort();
20460
+ const hostedPair = resolveAuditPair(audits.map((id) => ({ id, auditIds: [id] })), args, "in this project's assessments");
20461
+ const from2 = hostedPair.from.id;
20462
+ const to2 = hostedPair.to.id;
19347
20463
  const fromState = { assessments: grouped.get(from2) ?? [], findings: section.findings };
19348
20464
  const toState = { assessments: grouped.get(to2) ?? [], findings: section.findings };
19349
20465
  let regressions2;
@@ -19363,13 +20479,14 @@ function buildKritikCatalog(ctx) {
19363
20479
  }
19364
20480
  const root = repoRootOf(ctx, REPO_MODE_ONLY);
19365
20481
  const library = libraryOf(root);
19366
- const audits = listAuditIds(root);
19367
- const { from, to } = resolveAuditPair(audits, args, "under docs/quality/audits/");
20482
+ const pair = resolveAuditPair(auditReadings(listAuditIds(root)), args, "under docs/quality/audits/");
20483
+ const from = pair.from.id;
20484
+ const to = pair.to.id;
19368
20485
  let regressions;
19369
20486
  try {
19370
20487
  regressions = detectRegressions(
19371
- loadQualitySectionThrough(root, from, library),
19372
- loadQualitySectionThrough(root, to, library),
20488
+ loadQualitySectionThrough(root, lastAuditOf(pair.from), library),
20489
+ loadQualitySectionThrough(root, lastAuditOf(pair.to), library),
19373
20490
  library
19374
20491
  );
19375
20492
  } catch (error51) {
@@ -19541,17 +20658,96 @@ function buildKritikCatalog(ctx) {
19541
20658
  );
19542
20659
  }
19543
20660
  }
20661
+ const planOnly = ctx.qualityRoot !== void 0 && scope.since === null ? recordedPlans(graph.journal).map((p) => p.plan) : [];
19544
20662
  return {
19545
20663
  ...scope,
19546
20664
  cells,
19547
20665
  summary: scopeSummary(scope),
19548
20666
  ...ctx.qualityRoot === void 0 ? { open_audit: openAudit } : {},
19549
20667
  ...scope.since === null ? {
19550
- note: ctx.qualityRoot === void 0 ? NO_HOSTED_AUDIT : "No recorded audit yet \u2014 a scope is measured from one. `kritik_matrix` with record=true writes it."
20668
+ note: ctx.qualityRoot === void 0 ? NO_HOSTED_AUDIT : planOnly.length > 0 ? `No full audit recorded yet: ${planOnlyNote(planOnly)}` : "No recorded audit yet \u2014 a scope is measured from one. `kritik_matrix` with record=true writes it."
19551
20669
  } : {}
19552
20670
  };
19553
20671
  }
19554
20672
  );
20673
+ tool(
20674
+ {
20675
+ name: "kritik_plan",
20676
+ description: "Plan a partial audit before running it: one part per DOMAIN:SURFACE in runs (e.g. SEC:web), each with its own audit id that sorts after every audit on disk, the exact cells it scores, its checklist step count, and a prompt to paste into an agent session \u2014 plus one combined prompt for a session that runs every part in order. Writes docs/quality/plans/<planId>.json (dry_run=true writes nothing) and returns the plan, the path and any warnings; the same plan file `arkaik kritik plan` writes. Counts only: no token estimate yet. With status=<planId> it instead reads each part's progress from its audit directory (not started, in progress, scored; cells still missing; scores outside the plan, which block the record \u2014 delete such a row from docs/quality/audits/<partId>/scores.json) and writes nothing; each part's summary reads like the CLI's status row ('scored, 1 outside the plan'), and ready_to_record says whether the plan can be recorded. Score every cell with kritik_score and audit_id=<the part's audit id>; never record a part on its own \u2014 the plan is recorded once, after every part is scored, with `arkaik kritik matrix <planId> --record --plan`. Repo sessions only: a part is scored against a checkout.",
20677
+ inputSchema: {
20678
+ type: "object",
20679
+ properties: {
20680
+ runs: {
20681
+ type: "array",
20682
+ items: { type: "string" },
20683
+ description: 'One DOMAIN:SURFACE per part, e.g. ["SEC:web", "AGT:ios"]. The order is kept. Required unless status is given.'
20684
+ },
20685
+ dry_run: { type: "boolean", description: "Build and return the plan, write nothing. Default: false." },
20686
+ status: { type: "string", description: "A plan id: return each part's progress instead of making a plan. Read-only." }
20687
+ },
20688
+ additionalProperties: false
20689
+ }
20690
+ },
20691
+ async (args) => {
20692
+ const root = repoRootOf(
20693
+ ctx,
20694
+ "A plan's parts are audits under docs/quality/audits/, scored against a checkout."
20695
+ );
20696
+ if (args.status !== void 0) {
20697
+ const planId2 = requireString(args, "status");
20698
+ if (!isPlanId(planId2)) {
20699
+ throw new ToolError(`"${planId2}" is not a plan id \u2014 a plan id reads YYYY-MM-zplan-DDNN, as kritik_plan returns it.`);
20700
+ }
20701
+ }
20702
+ const graph = await load2();
20703
+ const recorded = recordedAuditIds(graph.journal);
20704
+ if (args.status !== void 0) {
20705
+ const planId2 = requireString(args, "status");
20706
+ if (args.runs !== void 0) {
20707
+ throw new ToolError("status reads a plan that exists \u2014 pass runs or status, not both.");
20708
+ }
20709
+ try {
20710
+ const plan = loadPlan(root, planId2);
20711
+ const isRecorded = recorded.includes(plan.planId);
20712
+ const statuses = planStatus(root, plan);
20713
+ return {
20714
+ plan_id: plan.planId,
20715
+ recorded: isRecorded,
20716
+ // `summary` is the CLI's status row: a fully scored part holding a
20717
+ // score outside the plan reads "scored, 1 outside the plan", since
20718
+ // the record refuses it until that row is deleted from its scores.json.
20719
+ parts: statuses.map((status) => ({
20720
+ ...status,
20721
+ summary: status.stray.length === 0 ? status.progress : `${status.progress}, ${status.stray.length} outside the plan`
20722
+ })),
20723
+ ready_to_record: !isRecorded && statuses.every((status) => status.progress === "deferred" || status.progress === "scored" && status.stray.length === 0)
20724
+ };
20725
+ } catch (error51) {
20726
+ throw new ToolError(error51.message);
20727
+ }
20728
+ }
20729
+ const runs = args.runs;
20730
+ if (!Array.isArray(runs) || runs.length === 0 || runs.some((run) => typeof run !== "string")) {
20731
+ throw new ToolError('`runs` is required: one DOMAIN:SURFACE string per part, e.g. ["SEC:web"].');
20732
+ }
20733
+ const library = libraryOf(root);
20734
+ let created;
20735
+ try {
20736
+ created = createPlan(root, library, runs, { recorded });
20737
+ } catch (error51) {
20738
+ throw new ToolError(error51.message);
20739
+ }
20740
+ const path = planPath(root, created.plan.planId);
20741
+ const written = args.dry_run !== true;
20742
+ if (written && existsSync8(path)) {
20743
+ throw new ToolError(
20744
+ `${path} already exists \u2014 a plan file is written once, and another plan took ${created.plan.planId} meanwhile. Call kritik_plan again for the next id.`
20745
+ );
20746
+ }
20747
+ if (written) savePlan(path, created.plan);
20748
+ return { plan: created.plan, path, written, warnings: created.warnings };
20749
+ }
20750
+ );
19555
20751
  tool(
19556
20752
  {
19557
20753
  name: "kritik_issue",
@@ -19713,7 +20909,10 @@ function buildKritikCatalog(ctx) {
19713
20909
  if (args.scope === true) {
19714
20910
  const scope = scopeOf2(graph);
19715
20911
  if (scope.since === null) {
19716
- throw new ToolError("scope=true needs a recorded audit to measure from \u2014 kritik_matrix with record=true writes one.");
20912
+ const plans = recordedPlans(graph.journal).map((p) => p.plan);
20913
+ throw new ToolError(
20914
+ plans.length > 0 ? `scope=true needs a full or scoped audit to measure from, and ${planOnlyNote(plans)}` : "scope=true needs a recorded audit to measure from \u2014 kritik_matrix with record=true writes one."
20915
+ );
19717
20916
  }
19718
20917
  if (!scope.cells.some((cell) => cell.criterion_id === criterionId && cell.surface === surface)) {
19719
20918
  throw new ToolError(
@@ -19735,12 +20934,13 @@ function buildKritikCatalog(ctx) {
19735
20934
  } else {
19736
20935
  auditId = auditForWrite(root, args.audit_id);
19737
20936
  }
20937
+ refuseOutsortedPart(root, auditId);
19738
20938
  const notes = [];
19739
20939
  if (scopedFrom === void 0) {
19740
20940
  if (recordedAuditIds(graph.journal).includes(auditId)) {
19741
20941
  notes.push(`${auditId} is already recorded \u2014 a re-score here rewrites that reading. For a re-audit after fixes, pass scope=true.`);
19742
20942
  }
19743
- const order = auditOrderNote(root, auditId);
20943
+ const order = isPlanPartId(auditId) ? void 0 : auditOrderNote(root, auditId);
19744
20944
  if (order !== void 0) notes.push(order);
19745
20945
  }
19746
20946
  const file2 = loadScoresOrEmpty(root, auditId);
@@ -19824,6 +21024,7 @@ function buildKritikCatalog(ctx) {
19824
21024
  throw new ToolError(`\`cost\` must be one of ${REMEDIATION_COSTS.join(", ")} \u2014 it decides priority.`);
19825
21025
  }
19826
21026
  const auditId = auditForWrite(root, args.audit_id);
21027
+ refuseOutsortedPart(root, auditId);
19827
21028
  const file2 = loadFindings(root, auditId);
19828
21029
  const taken = new Set(file2.findings.map((candidate) => candidate.id));
19829
21030
  const requestedId = typeof args.finding_id === "string" && args.finding_id !== "" ? args.finding_id : void 0;
@@ -20047,11 +21248,24 @@ function unwrap(result) {
20047
21248
  return { warnings: result.warnings, events: result.events };
20048
21249
  }
20049
21250
  var UPDATABLE_NODE_FIELDS = /* @__PURE__ */ new Set(["title", "description", "status", "platforms", "metadata"]);
21251
+ function requirePlatform(args) {
21252
+ const raw = requireString2(args, "platform");
21253
+ const platform = PLATFORM_IDS.find((id) => id === raw);
21254
+ if (platform === void 0) {
21255
+ throw new ToolError(`"${raw}" is not a platform (expected one of: ${PLATFORM_IDS.join(", ")}).`);
21256
+ }
21257
+ return platform;
21258
+ }
21259
+ function requireScreenshotForm(args) {
21260
+ const raw = requireString2(args, "form");
21261
+ if (raw === "url" || raw === "path" || raw === "data") return raw;
21262
+ throw new ToolError(`"${raw}" is not a screenshot form (url, path or data).`);
21263
+ }
20050
21264
  function mutate(graph, ops) {
20051
21265
  try {
20052
21266
  return applyOps({ projectId: graph.project.id, nodes: graph.nodes, edges: graph.edges }, ops);
20053
21267
  } catch (err) {
20054
- if (err instanceof MutationError) throw new ToolError(err.message);
21268
+ if (err instanceof MutationError) throw new ToolError(`${err.code}: ${err.message}`);
20055
21269
  throw err;
20056
21270
  }
20057
21271
  }
@@ -20357,6 +21571,74 @@ ${node.description ?? ""}`.toLowerCase();
20357
21571
  return { node: updated, edges: outcome.synthesizedEdges, events, warnings };
20358
21572
  }
20359
21573
  );
21574
+ tool(
21575
+ {
21576
+ name: "record_screenshot",
21577
+ description: "Record a screenshot for one platform slot of a view or acceptance (screenshot.recorded). `form` is url (https), path (relative to the bundle) or data (an image data URI). Source is manual; CI posts through the screenshots door. Never patch metadata.platformScreenshots with update_node.",
21578
+ inputSchema: {
21579
+ type: "object",
21580
+ properties: {
21581
+ node_id: { type: "string" },
21582
+ platform: { type: "string", enum: [...PLATFORM_IDS] },
21583
+ form: { type: "string", enum: ["url", "path", "data"] },
21584
+ value: { type: "string", description: "The https URL, relative path or image data URI, per form." },
21585
+ detail: { type: "string" }
21586
+ },
21587
+ required: ["node_id", "platform", "form", "value"],
21588
+ additionalProperties: false
21589
+ }
21590
+ },
21591
+ async (args) => {
21592
+ const nodeId = requireString2(args, "node_id");
21593
+ const platform = requirePlatform(args);
21594
+ const form = requireScreenshotForm(args);
21595
+ const value = requireString2(args, "value");
21596
+ const graph = await load(ctx);
21597
+ const ops = [
21598
+ {
21599
+ op: "record_screenshot",
21600
+ node_id: nodeId,
21601
+ platform,
21602
+ source: "manual",
21603
+ form,
21604
+ value,
21605
+ ...typeof args.detail === "string" && args.detail !== "" ? { detail: args.detail } : {}
21606
+ }
21607
+ ];
21608
+ const outcome = mutate(graph, ops);
21609
+ const node = outcome.nodes.find((candidate) => candidate.id === nodeId);
21610
+ if (outcome.eventInputs.length === 0) {
21611
+ return { node, events: [], note: "No-op \u2014 the slot already holds this value, or a newer CI shot outranks it; nothing written." };
21612
+ }
21613
+ const result = await ctx.store.persist(graph, { nodes: outcome.nodes, edges: outcome.edges, ops }, outcome.eventInputs);
21614
+ const { warnings, events } = unwrap(result);
21615
+ return { node, events, warnings };
21616
+ }
21617
+ );
21618
+ tool(
21619
+ {
21620
+ name: "remove_screenshot",
21621
+ description: "Clear one platform slot's screenshot (screenshot.removed). The slot's CI order watermark survives, so a late CI re-run cannot bring the shot back.",
21622
+ inputSchema: {
21623
+ type: "object",
21624
+ properties: { node_id: { type: "string" }, platform: { type: "string", enum: [...PLATFORM_IDS] } },
21625
+ required: ["node_id", "platform"],
21626
+ additionalProperties: false
21627
+ }
21628
+ },
21629
+ async (args) => {
21630
+ const nodeId = requireString2(args, "node_id");
21631
+ const platform = requirePlatform(args);
21632
+ const graph = await load(ctx);
21633
+ const ops = [{ op: "remove_screenshot", node_id: nodeId, platform }];
21634
+ const outcome = mutate(graph, ops);
21635
+ const node = outcome.nodes.find((candidate) => candidate.id === nodeId);
21636
+ if (outcome.eventInputs.length === 0) return { node, events: [], note: "No-op \u2014 the slot was already empty." };
21637
+ const result = await ctx.store.persist(graph, { nodes: outcome.nodes, edges: outcome.edges, ops }, outcome.eventInputs);
21638
+ const { warnings, events } = unwrap(result);
21639
+ return { node, events, warnings };
21640
+ }
21641
+ );
20360
21642
  tool(
20361
21643
  {
20362
21644
  name: "delete_node",
@@ -20753,12 +22035,12 @@ function describeFailure(status, body) {
20753
22035
 
20754
22036
  // src/config.ts
20755
22037
  import { readFileSync as readFileSync5 } from "node:fs";
20756
- import { join as join5 } from "node:path";
22038
+ import { join as join6 } from "node:path";
20757
22039
  var LINK_FILE = "docs/arkaik/arkaik.json";
20758
22040
  var DEFAULT_BASE_URL = "https://arkaik.app";
20759
22041
  function readLinkFile(cwd) {
20760
22042
  try {
20761
- const parsed = JSON.parse(readFileSync5(join5(cwd, LINK_FILE), "utf8"));
22043
+ const parsed = JSON.parse(readFileSync5(join6(cwd, LINK_FILE), "utf8"));
20762
22044
  if (typeof parsed !== "object" || parsed === null) return null;
20763
22045
  return parsed;
20764
22046
  } catch {
@@ -20799,7 +22081,7 @@ function resolveRemoteConfig(argv2, env, cwd) {
20799
22081
  }
20800
22082
 
20801
22083
  // src/index.ts
20802
- var VERSION = "0.9.0";
22084
+ var VERSION = "0.10.0";
20803
22085
  var argv = process.argv.slice(2);
20804
22086
  if (argv.includes("--help") || argv.includes("-h")) {
20805
22087
  process.stdout.write(