arkaik-mcp 0.3.0 → 0.5.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 +606 -68
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -6,7 +6,7 @@ var __export = (target, all) => {
6
6
  };
7
7
 
8
8
  // src/index.ts
9
- import { dirname as dirname4, resolve as resolve3, sep } from "node:path";
9
+ import { dirname as dirname4 } from "node:path";
10
10
 
11
11
  // src/protocol.ts
12
12
  import { createInterface } from "node:readline";
@@ -15359,12 +15359,20 @@ var QualityFindingResolvedEventSchema = external_exports.object({
15359
15359
  resolved_by: external_exports.string().optional(),
15360
15360
  node_ids: external_exports.array(external_exports.string()).optional()
15361
15361
  }).catchall(external_exports.unknown());
15362
+ var QualityFindingAcceptedEventSchema = external_exports.object({
15363
+ ...envelope,
15364
+ type: external_exports.literal("quality.finding.accepted"),
15365
+ finding_id: external_exports.string(),
15366
+ reason: external_exports.string(),
15367
+ node_ids: external_exports.array(external_exports.string()).optional()
15368
+ }).catchall(external_exports.unknown());
15362
15369
  var QualitySignalTrippedEventSchema = external_exports.object({
15363
15370
  ...envelope,
15364
15371
  type: external_exports.literal("quality.signal.tripped"),
15365
15372
  criterion_id: external_exports.string(),
15366
15373
  surface: external_exports.string(),
15367
15374
  signal: external_exports.string(),
15375
+ commit: external_exports.string().optional(),
15368
15376
  detail: external_exports.string().optional()
15369
15377
  }).catchall(external_exports.unknown());
15370
15378
  var JOURNAL_EVENT_SCHEMAS = {
@@ -15386,6 +15394,7 @@ var JOURNAL_EVENT_SCHEMAS = {
15386
15394
  "quality.audit.completed": QualityAuditCompletedEventSchema,
15387
15395
  "quality.finding.opened": QualityFindingOpenedEventSchema,
15388
15396
  "quality.finding.resolved": QualityFindingResolvedEventSchema,
15397
+ "quality.finding.accepted": QualityFindingAcceptedEventSchema,
15389
15398
  "quality.signal.tripped": QualitySignalTrippedEventSchema
15390
15399
  };
15391
15400
  var KnownJournalEventSchema = external_exports.union([
@@ -15407,6 +15416,7 @@ var KnownJournalEventSchema = external_exports.union([
15407
15416
  QualityAuditCompletedEventSchema,
15408
15417
  QualityFindingOpenedEventSchema,
15409
15418
  QualityFindingResolvedEventSchema,
15419
+ QualityFindingAcceptedEventSchema,
15410
15420
  QualitySignalTrippedEventSchema
15411
15421
  ]);
15412
15422
 
@@ -15494,6 +15504,9 @@ var QualityFindingSchema = external_exports.object({
15494
15504
  remediation: external_exports.string().optional(),
15495
15505
  node_ids: external_exports.array(external_exports.string()).optional().meta({ description: "Graph nodes this finding is about \u2014 the tie deliverable.shipped already uses." }),
15496
15506
  issue_url: external_exports.string().optional(),
15507
+ commit: external_exports.string().optional().meta({
15508
+ 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."
15509
+ }),
15497
15510
  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." })
15498
15511
  }).catchall(external_exports.unknown()).meta({
15499
15512
  id: "QualityFinding",
@@ -16005,6 +16018,18 @@ function capGrade(grade, cap) {
16005
16018
  function isOpenFinding(finding) {
16006
16019
  return (finding.status ?? "open") === "open";
16007
16020
  }
16021
+ function rollUpSurface(scores, weights) {
16022
+ let weighted = 0;
16023
+ let total = 0;
16024
+ for (const domain2 of Object.keys(scores)) {
16025
+ const score = scores[domain2];
16026
+ if (typeof score !== "number" || !Number.isFinite(score)) continue;
16027
+ const weight = typeof weights?.[domain2] === "number" ? weights[domain2] : 1;
16028
+ weighted += score * weight;
16029
+ total += weight;
16030
+ }
16031
+ return total > 0 ? Math.round(weighted / total) : null;
16032
+ }
16008
16033
  function resolveKritikLibrary(section, library) {
16009
16034
  const explicit = library ?? section?.library;
16010
16035
  if (explicit && Array.isArray(explicit.criteria) && Array.isArray(explicit.domains)) return explicit;
@@ -16080,16 +16105,12 @@ function deriveQualityMatrix(bundle, library) {
16080
16105
  }
16081
16106
  const overall = {};
16082
16107
  for (const surface of surfaces) {
16083
- let weighted = 0;
16084
- let total = 0;
16108
+ const bySurface = {};
16085
16109
  for (const domain2 of domains) {
16086
16110
  const cell = matrix[domain2]?.[surface];
16087
- if (!cell) continue;
16088
- const weight = typeof weights?.[domain2] === "number" ? weights[domain2] : 1;
16089
- weighted += cell.score * weight;
16090
- total += weight;
16111
+ if (cell) bySurface[domain2] = cell.score;
16091
16112
  }
16092
- overall[surface] = total > 0 ? Math.round(weighted / total) : null;
16113
+ overall[surface] = rollUpSurface(bySurface, weights);
16093
16114
  }
16094
16115
  const finding_counts = { critical: 0, high: 0, medium: 0, low: 0, info: 0 };
16095
16116
  for (const finding of openFindings) finding_counts[severityOf(finding, pack)]++;
@@ -16942,6 +16963,15 @@ function validateBundle(input) {
16942
16963
  );
16943
16964
  }
16944
16965
  }
16966
+ if (type === "quality.finding.accepted" && typeof event.finding_id === "string") {
16967
+ if (!openedInJournal.has(event.finding_id) && !seenFindingIds.has(event.finding_id)) {
16968
+ warn(
16969
+ `journal[${index}].finding_id`,
16970
+ "quality-accepted-never-opened",
16971
+ `Journal event ${index}: accepts finding "${event.finding_id}", which no quality.finding.opened event or stored finding ever declared`
16972
+ );
16973
+ }
16974
+ }
16945
16975
  });
16946
16976
  }
16947
16977
  for (const finding of crossCheckJournal(bundle)) findings.push(finding);
@@ -17663,11 +17693,14 @@ function resolveFinding(findings, id, resolvedBy) {
17663
17693
  ...resolvedBy !== void 0 ? { resolved_by: resolvedBy } : {}
17664
17694
  });
17665
17695
  }
17666
- function acceptFinding(findings, id, note) {
17667
- const existing = findings.find((candidate) => candidate.id === id);
17668
- const detail = existing === void 0 ? note : `${existing.detail}
17696
+ function acceptedDetail(detail, note) {
17697
+ return `${detail}
17669
17698
 
17670
17699
  Accepted risk: ${note}`.trim();
17700
+ }
17701
+ function acceptFinding(findings, id, note) {
17702
+ const existing = findings.find((candidate) => candidate.id === id);
17703
+ const detail = existing === void 0 ? note : acceptedDetail(existing.detail, note);
17671
17704
  return patchFinding(findings, id, { status: "accepted-risk", detail });
17672
17705
  }
17673
17706
  function fillTemplate(text, values) {
@@ -17794,11 +17827,234 @@ function signalTrippedInput(trip) {
17794
17827
  criterion_id: trip.criterion_id,
17795
17828
  surface: trip.surface,
17796
17829
  signal: trip.signal,
17830
+ ...trip.commit !== void 0 ? { commit: trip.commit } : {},
17797
17831
  ...trip.detail !== void 0 ? { detail: trip.detail } : {}
17798
17832
  }
17799
17833
  };
17800
17834
  }
17801
17835
 
17836
+ // ../schema/src/quality-regressions.ts
17837
+ var REGRESSION_SIGNALS = {
17838
+ "level-drop": "maturity on this cell does not regress",
17839
+ "new-severe-finding": "no open Critical or High finding on this cell",
17840
+ "reopened-finding": "a resolved finding stays resolved"
17841
+ };
17842
+ var cellKey = (criterionId, surface) => `${criterionId}::${surface}`;
17843
+ var rowsOf = (value) => Array.isArray(value) ? value : [];
17844
+ function assessmentsByCell(state) {
17845
+ const cells = /* @__PURE__ */ new Map();
17846
+ for (const assessment of rowsOf(state?.assessments)) {
17847
+ if (typeof assessment?.criterion_id !== "string" || typeof assessment?.surface !== "string") continue;
17848
+ cells.set(cellKey(assessment.criterion_id, assessment.surface), assessment);
17849
+ }
17850
+ return cells;
17851
+ }
17852
+ function severeByCell(state, library) {
17853
+ const cells = /* @__PURE__ */ new Map();
17854
+ for (const finding of rowsOf(state?.findings)) {
17855
+ if (typeof finding?.criterion_id !== "string" || typeof finding?.surface !== "string") continue;
17856
+ if (!isOpenFinding(finding)) continue;
17857
+ const severity = severityOf(finding, library);
17858
+ if (severity !== "critical" && severity !== "high") continue;
17859
+ const key = cellKey(finding.criterion_id, finding.surface);
17860
+ const existing = cells.get(key);
17861
+ if (existing === void 0) cells.set(key, [finding]);
17862
+ else existing.push(finding);
17863
+ }
17864
+ return cells;
17865
+ }
17866
+ function detectRegressions(previous, next, library) {
17867
+ const before = assessmentsByCell(previous);
17868
+ const after = assessmentsByCell(next);
17869
+ const comparable = (key) => before.has(key) && after.has(key);
17870
+ const regressions = [];
17871
+ for (const [key, current] of after) {
17872
+ const earlier = before.get(key);
17873
+ if (earlier === void 0) continue;
17874
+ if (!(Number(current.level) < Number(earlier.level))) continue;
17875
+ regressions.push({
17876
+ kind: "level-drop",
17877
+ criterion_id: current.criterion_id,
17878
+ surface: current.surface,
17879
+ signal: REGRESSION_SIGNALS["level-drop"],
17880
+ detail: `level ${earlier.level} \u2192 ${current.level} (${earlier.audit_id} \u2192 ${current.audit_id})`
17881
+ });
17882
+ }
17883
+ const severeBefore = severeByCell(previous, library);
17884
+ for (const [key, findings] of severeByCell(next, library)) {
17885
+ if (!comparable(key)) continue;
17886
+ if ((severeBefore.get(key) ?? []).length > 0) continue;
17887
+ for (const finding of findings) {
17888
+ regressions.push({
17889
+ kind: "new-severe-finding",
17890
+ criterion_id: finding.criterion_id,
17891
+ surface: finding.surface,
17892
+ signal: REGRESSION_SIGNALS["new-severe-finding"],
17893
+ detail: `${finding.id} \u2014 ${severityOf(finding, library)} (impact ${finding.impact} \xD7 likelihood ${finding.likelihood})`
17894
+ });
17895
+ }
17896
+ }
17897
+ const resolvedBefore = new Set(
17898
+ rowsOf(previous?.findings).filter((finding) => finding?.status === "resolved").map((finding) => finding.id)
17899
+ );
17900
+ for (const finding of rowsOf(next?.findings)) {
17901
+ if (!isOpenFinding(finding) || !resolvedBefore.has(finding.id)) continue;
17902
+ regressions.push({
17903
+ kind: "reopened-finding",
17904
+ criterion_id: finding.criterion_id,
17905
+ surface: finding.surface,
17906
+ signal: REGRESSION_SIGNALS["reopened-finding"],
17907
+ detail: `${finding.id} \u2014 "${finding.title}"`
17908
+ });
17909
+ }
17910
+ return regressions;
17911
+ }
17912
+
17913
+ // ../schema/src/quality-trend.ts
17914
+ var NO_DELTA = { previous: null, delta: null };
17915
+ var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
17916
+ function frameworkMajor(version2) {
17917
+ if (typeof version2 !== "string") return null;
17918
+ const match = /^\s*v?(\d+)/.exec(version2);
17919
+ return match ? Number(match[1]) : null;
17920
+ }
17921
+ function sameFrameworkMajor(a, b) {
17922
+ const left = frameworkMajor(a);
17923
+ const right = frameworkMajor(b);
17924
+ return left === null || right === null || left === right;
17925
+ }
17926
+ function cleanScores(raw) {
17927
+ const scores = {};
17928
+ if (!isRecord2(raw)) return scores;
17929
+ for (const surface of Object.keys(raw)) {
17930
+ const bySurface = raw[surface];
17931
+ if (!isRecord2(bySurface)) continue;
17932
+ const cleaned = {};
17933
+ for (const domain2 of Object.keys(bySurface)) {
17934
+ const score = bySurface[domain2];
17935
+ if (typeof score === "number" && Number.isFinite(score)) cleaned[domain2] = score;
17936
+ }
17937
+ scores[surface] = cleaned;
17938
+ }
17939
+ return scores;
17940
+ }
17941
+ function cleanCounts(raw) {
17942
+ const counts = { critical: 0, high: 0, medium: 0, low: 0, info: 0 };
17943
+ if (!isRecord2(raw)) return counts;
17944
+ for (const severity of Object.keys(counts)) {
17945
+ const value = raw[severity];
17946
+ if (typeof value === "number" && Number.isFinite(value)) counts[severity] = value;
17947
+ }
17948
+ return counts;
17949
+ }
17950
+ function cellSet(scores) {
17951
+ const cells = /* @__PURE__ */ new Map();
17952
+ for (const surface of Object.keys(scores)) {
17953
+ for (const domain2 of Object.keys(scores[surface])) cells.set(`${surface}::${domain2}`, scores[surface][domain2]);
17954
+ }
17955
+ return cells;
17956
+ }
17957
+ function liveScores(live) {
17958
+ const scores = {};
17959
+ for (const domain2 of Object.keys(live.matrix ?? {})) {
17960
+ const row = live.matrix[domain2];
17961
+ if (!isRecord2(row)) continue;
17962
+ for (const surface of Object.keys(row)) {
17963
+ const cell = row[surface];
17964
+ if (!cell || typeof cell.score !== "number") continue;
17965
+ (scores[surface] ??= {})[domain2] = cell.score;
17966
+ }
17967
+ }
17968
+ return scores;
17969
+ }
17970
+ function sameCells(a, b) {
17971
+ if (a.size !== b.size) return false;
17972
+ for (const [key, value] of a) {
17973
+ if (b.get(key) !== value) return false;
17974
+ }
17975
+ return true;
17976
+ }
17977
+ function deriveQualityTrend(events, profile, live) {
17978
+ const weights = profile?.domain_weights;
17979
+ const byAudit = /* @__PURE__ */ new Map();
17980
+ const audits = (Array.isArray(events) ? events : []).filter(
17981
+ (event) => isRecord2(event) && event.type === "quality.audit.completed"
17982
+ );
17983
+ for (const event of orderEvents(audits)) {
17984
+ const auditId = typeof event.audit_id === "string" ? event.audit_id : typeof event.id === "string" ? event.id : "";
17985
+ const scores = cleanScores(event.scores);
17986
+ const overall = {};
17987
+ for (const surface of Object.keys(scores)) overall[surface] = rollUpSurface(scores[surface], weights);
17988
+ const snapshot = {
17989
+ audit_id: auditId,
17990
+ ts: typeof event.ts === "string" ? event.ts : "",
17991
+ ...typeof event.commit === "string" && event.commit !== "" ? { commit: event.commit } : {},
17992
+ ...typeof event.framework_version === "string" ? { framework_version: event.framework_version } : {},
17993
+ comparable: true,
17994
+ scores,
17995
+ overall,
17996
+ counts: cleanCounts(event.counts)
17997
+ };
17998
+ byAudit.delete(auditId);
17999
+ byAudit.set(auditId, snapshot);
18000
+ }
18001
+ const snapshots = [...byAudit.values()];
18002
+ for (let i = 1; i < snapshots.length; i++) {
18003
+ snapshots[i].comparable = sameFrameworkMajor(snapshots[i - 1].framework_version, snapshots[i].framework_version);
18004
+ }
18005
+ const latest = snapshots.length > 0 ? snapshots[snapshots.length - 1] : null;
18006
+ let previous = latest;
18007
+ if (live && latest !== null && sameCells(cellSet(latest.scores), cellSet(liveScores(live)))) {
18008
+ previous = snapshots.length > 1 ? snapshots[snapshots.length - 2] : null;
18009
+ }
18010
+ const comparable = previous !== null && live ? sameFrameworkMajor(previous.framework_version, live.framework_version) : false;
18011
+ const against = (prev, current) => {
18012
+ if (previous === null || typeof prev !== "number") return NO_DELTA;
18013
+ const delta = comparable && typeof current === "number" ? current - prev : null;
18014
+ return { previous: prev, delta, audit_id: previous.audit_id };
18015
+ };
18016
+ return {
18017
+ snapshots,
18018
+ latest,
18019
+ previous,
18020
+ deltaCell: (domain2, surface) => against(previous?.scores[surface]?.[domain2], live?.matrix?.[domain2]?.[surface]?.score),
18021
+ deltaOverall: (surface) => against(previous?.overall[surface], live?.overall?.[surface])
18022
+ };
18023
+ }
18024
+ function trendRows(trend, filter = {}) {
18025
+ const surfaces = [];
18026
+ for (const snapshot of trend.snapshots) {
18027
+ for (const surface of Object.keys(snapshot.scores)) {
18028
+ if (filter.surface !== void 0 && surface !== filter.surface) continue;
18029
+ if (!surfaces.includes(surface)) surfaces.push(surface);
18030
+ }
18031
+ }
18032
+ const valueOf = (snapshot, surface) => {
18033
+ if (filter.domain !== void 0) return snapshot.scores[surface]?.[filter.domain] ?? null;
18034
+ return snapshot.overall[surface] ?? null;
18035
+ };
18036
+ const rows = [];
18037
+ trend.snapshots.forEach((snapshot, index) => {
18038
+ const above = index > 0 ? trend.snapshots[index - 1] : null;
18039
+ const cells = {};
18040
+ for (const surface of surfaces) {
18041
+ const score = valueOf(snapshot, surface);
18042
+ const before = above === null ? null : valueOf(above, surface);
18043
+ const delta = snapshot.comparable && score !== null && before !== null ? score - before : null;
18044
+ cells[surface] = { score, delta };
18045
+ }
18046
+ rows.push({
18047
+ audit_id: snapshot.audit_id,
18048
+ ts: snapshot.ts,
18049
+ ...snapshot.commit !== void 0 ? { commit: snapshot.commit } : {},
18050
+ ...snapshot.framework_version !== void 0 ? { framework_version: snapshot.framework_version } : {},
18051
+ comparable: snapshot.comparable,
18052
+ cells
18053
+ });
18054
+ });
18055
+ return { surfaces, rows };
18056
+ }
18057
+
17802
18058
  // ../schema/src/cli/kritik-audit.ts
17803
18059
  import { existsSync as existsSync2, readdirSync, statSync } from "node:fs";
17804
18060
  import { join as join2 } from "node:path";
@@ -17812,7 +18068,12 @@ var OVERLAY_FILE = "criteria.custom.json";
17812
18068
  var AUDITS_DIR = "audits";
17813
18069
  var PACK_FILE = "library.json";
17814
18070
  function readJson(path) {
17815
- return JSON.parse(readFileSync(path, "utf8"));
18071
+ const text = readFileSync(path, "utf8");
18072
+ try {
18073
+ return JSON.parse(text);
18074
+ } catch (e) {
18075
+ throw new Error(`${path}: not valid JSON \u2014 ${e.message}`);
18076
+ }
17816
18077
  }
17817
18078
  function writeJson(path, value) {
17818
18079
  mkdirSync(dirname(path), { recursive: true });
@@ -17820,7 +18081,8 @@ function writeJson(path, value) {
17820
18081
  }
17821
18082
  var profilePath = (root) => join(root, QUALITY_DIR, PROFILE_FILE);
17822
18083
  var overlayPath = (root) => join(root, QUALITY_DIR, OVERLAY_FILE);
17823
- var auditDir = (root, auditId) => join(root, QUALITY_DIR, AUDITS_DIR, auditId);
18084
+ var auditsDir = (root) => join(root, QUALITY_DIR, AUDITS_DIR);
18085
+ var auditDir = (root, auditId) => join(auditsDir(root), auditId);
17824
18086
  function loadProfile(root) {
17825
18087
  const path = profilePath(root);
17826
18088
  return existsSync(path) ? readJson(path) : null;
@@ -17838,12 +18100,12 @@ var scoresPath = (root, auditId) => join2(auditDir(root, auditId), SCORES_FILE);
17838
18100
  var findingsPath = (root, auditId) => join2(auditDir(root, auditId), FINDINGS_FILE);
17839
18101
  var matrixPath = (root, auditId) => join2(auditDir(root, auditId), MATRIX_FILE);
17840
18102
  function listAuditIds(root) {
17841
- const dir = join2(root, QUALITY_DIR, AUDITS_DIR);
18103
+ const dir = auditsDir(root);
17842
18104
  if (!existsSync2(dir)) return [];
17843
18105
  return readdirSync(dir).filter((name) => statSync(join2(dir, name)).isDirectory()).sort();
17844
18106
  }
17845
18107
  function newestAuditId(root) {
17846
- const dir = join2(root, QUALITY_DIR, AUDITS_DIR);
18108
+ const dir = auditsDir(root);
17847
18109
  if (!existsSync2(dir)) throw new Error(`no audits directory at ${dir}`);
17848
18110
  const ids = listAuditIds(root);
17849
18111
  if (ids.length === 0) throw new Error(`no audits found under ${dir}`);
@@ -17970,7 +18232,7 @@ function appendJournalEvent(journalPath, event) {
17970
18232
 
17971
18233
  // ../cli/src/lib/kritik-io.ts
17972
18234
  import { existsSync as existsSync5 } from "node:fs";
17973
- import { dirname as dirname3, join as join4 } from "node:path";
18235
+ import { basename, dirname as dirname3, join as join4, resolve as resolve2 } from "node:path";
17974
18236
  import { fileURLToPath } from "node:url";
17975
18237
  var DEFAULT_BUNDLE_PATH = join4("docs", "arkaik", "bundle.json");
17976
18238
  var VENDORED_PACK = join4(QUALITY_DIR, PACK_FILE);
@@ -17996,10 +18258,18 @@ function resolveJournal(root, bundlePath) {
17996
18258
  const resolved = bundlePath ?? join4(root, DEFAULT_BUNDLE_PATH);
17997
18259
  return { bundlePath: resolved, journalPath: journalPathFor(resolved), present: existsSync5(resolved) };
17998
18260
  }
18261
+ function resolveQualityRoot(options) {
18262
+ if (options.root !== void 0) return resolve2(options.fallback, options.root);
18263
+ const envRoot = (options.env ?? process.env).ARKAIK_QUALITY_ROOT;
18264
+ if (envRoot) return resolve2(envRoot);
18265
+ const dir = dirname3(options.bundlePath);
18266
+ if (basename(dir) === "arkaik" && basename(dirname3(dir)) === "docs") return resolve2(dir, "..", "..");
18267
+ return options.fallback;
18268
+ }
17999
18269
 
18000
18270
  // ../cli/src/lib/bundle-validate.ts
18001
18271
  import { existsSync as existsSync6, readFileSync as readFileSync4 } from "node:fs";
18002
- import { basename } from "node:path";
18272
+ import { basename as basename2 } from "node:path";
18003
18273
  function validateBundleAt(filePath) {
18004
18274
  const bundle = readBundle(filePath);
18005
18275
  const loose = bundle;
@@ -18021,7 +18291,7 @@ function validateBundleAt(filePath) {
18021
18291
  }
18022
18292
  for (const archivePath of archivePathsFor(sidecarPath)) {
18023
18293
  const { events, findings } = parseJournalLines(readFileSync4(archivePath, "utf8"));
18024
- const file2 = basename(archivePath);
18294
+ const file2 = basename2(archivePath);
18025
18295
  for (const finding of findings) archiveFindings.push({ ...finding, file: file2 });
18026
18296
  archivesLoaded.push(file2);
18027
18297
  folded.push(...events);
@@ -18048,14 +18318,77 @@ function validateBundleAt(filePath) {
18048
18318
  }
18049
18319
 
18050
18320
  // src/kritik-tools.ts
18051
- function rootOf(ctx) {
18321
+ function repoRootOf(ctx, needs) {
18052
18322
  if (ctx.qualityRoot === void 0) {
18053
18323
  throw new ToolError(
18054
- `Kritik runs against a repository's docs/quality/ files, and this session is connected to a hosted project (${ctx.store.describe()}). Point the server at the checkout instead \u2014 \`arkaik-mcp --bundle <path>\` \u2014 and run the audit where the code is.`
18324
+ `${needs} This session is connected to a hosted project (${ctx.store.describe()}); run it where the checkout is \u2014 \`arkaik-mcp --bundle <path>\`.`
18055
18325
  );
18056
18326
  }
18057
18327
  return ctx.qualityRoot;
18058
18328
  }
18329
+ var REPO_MODE_ONLY = "Repo-mode reads come from docs/quality/ files.";
18330
+ async function appendHosted(store2, inputs) {
18331
+ if (store2.appendQualityEvents === void 0) {
18332
+ throw new ToolError(`${store2.describe()} cannot append quality events.`);
18333
+ }
18334
+ try {
18335
+ return await store2.appendQualityEvents(inputs);
18336
+ } catch (error51) {
18337
+ throw new ToolError(error51.message);
18338
+ }
18339
+ }
18340
+ function hostedSection(graph) {
18341
+ const section = graph.loaded.bundle.quality;
18342
+ if (section === void 0 || !Array.isArray(section.findings) || !Array.isArray(section.assessments)) {
18343
+ throw new ToolError(
18344
+ "This hosted project has no quality section yet. Run an audit in the repository and `arkaik restore` it \u2014 hosted Kritik reads what an audit stored."
18345
+ );
18346
+ }
18347
+ return { section, library: resolveKritikLibrary(section) };
18348
+ }
18349
+ function refuseHostedRecord(eventType) {
18350
+ throw new ToolError(`Recording ${eventType} belongs to the audit run, which reads code. Run the audit where the checkout is.`);
18351
+ }
18352
+ function openFindingsSummary(findings, library) {
18353
+ const open = findings.filter(isOpenFinding);
18354
+ const lanes = { P0: 0, P1: 0, P2: 0, P3: 0 };
18355
+ for (const finding of open) lanes[priorityOf(finding, library)]++;
18356
+ const p0 = open.filter((finding) => priorityOf(finding, library) === "P0").map((finding) => ({
18357
+ id: finding.id,
18358
+ surface: finding.surface,
18359
+ criterion_id: finding.criterion_id,
18360
+ title: finding.title,
18361
+ severity: severityOf(finding, library)
18362
+ }));
18363
+ return { open, lanes, p0 };
18364
+ }
18365
+ function resolveAuditPair(audits, args, notFoundHint) {
18366
+ if (audits.length < 2) {
18367
+ throw new ToolError(
18368
+ `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.`
18369
+ );
18370
+ }
18371
+ const known = (id) => {
18372
+ if (!audits.includes(id)) throw new ToolError(`no audit "${id}" ${notFoundHint} (have: ${audits.join(", ")})`);
18373
+ return id;
18374
+ };
18375
+ const to = typeof args.to === "string" && args.to !== "" ? known(args.to) : audits[audits.length - 1];
18376
+ const from = typeof args.from === "string" && args.from !== "" ? known(args.from) : audits[audits.indexOf(to) - 1];
18377
+ if (from === void 0) throw new ToolError(`"${to}" is the oldest audit \u2014 there is nothing before it to compare against.`);
18378
+ if (from === to) throw new ToolError(`from and to name the same audit ("${to}") \u2014 a regression needs two readings.`);
18379
+ if (audits.indexOf(from) > audits.indexOf(to)) {
18380
+ throw new ToolError(`from "${from}" is newer than to "${to}" \u2014 swap them, or the comparison inverts.`);
18381
+ }
18382
+ return { from, to };
18383
+ }
18384
+ function matchesFindingArgs(row, args) {
18385
+ if (typeof args.surface === "string" && row.surface !== args.surface) return false;
18386
+ if (typeof args.status === "string" && (row.status ?? "open") !== args.status) return false;
18387
+ if (typeof args.priority === "string" && row.priority !== args.priority) return false;
18388
+ if (typeof args.criterion_id === "string" && row.criterion_id !== args.criterion_id) return false;
18389
+ if (typeof args.finding_id === "string" && row.id !== args.finding_id) return false;
18390
+ return true;
18391
+ }
18059
18392
  function libraryOf(root) {
18060
18393
  try {
18061
18394
  return loadKritikLibrary(root).library;
@@ -18150,7 +18483,7 @@ function buildKritikCatalog(ctx) {
18150
18483
  tool(
18151
18484
  {
18152
18485
  name: "kritik_matrix",
18153
- description: "The comparative quality matrix for one audit: 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. Refreshes the audit's matrix.json, and with record=true appends quality.audit.completed.",
18486
+ description: "The comparative quality matrix: a score and grade per (domain x surface), the weighted roll-up per surface, and open findings by priority lane. Anti-averaging caps are applied \u2014 one open Critical caps its cell at D, one open High at B \u2014 so a cell full of 3s cannot absorb a live defect. In repo mode this refreshes the audit's matrix.json, and with record=true appends quality.audit.completed; in hosted mode it is a read of the stored quality section (no audit_id/commit \u2014 hosted has no audit file) and record is refused \u2014 recording belongs to the audit run, which reads code.",
18154
18487
  inputSchema: {
18155
18488
  type: "object",
18156
18489
  properties: {
@@ -18164,7 +18497,29 @@ function buildKritikCatalog(ctx) {
18164
18497
  }
18165
18498
  },
18166
18499
  async (args) => {
18167
- const root = rootOf(ctx);
18500
+ const hosted = ctx.qualityRoot === void 0;
18501
+ if (hosted) {
18502
+ if (args.record === true) refuseHostedRecord("quality.audit.completed");
18503
+ if (typeof args.audit_id === "string" && args.audit_id !== "") {
18504
+ throw new ToolError("The hosted matrix is the current state, not one audit \u2014 audit_id does not partition it (issue #400 decision 3).");
18505
+ }
18506
+ const graph = await load2();
18507
+ const { section: section2, library: library2 } = hostedSection(graph);
18508
+ const m = deriveQualityMatrix({ quality: section2 }, library2);
18509
+ const { open: open2, lanes: lanes2, p0: p02 } = openFindingsSummary(section2.findings, library2);
18510
+ return {
18511
+ ...m.framework_version !== void 0 ? { framework_version: m.framework_version } : {},
18512
+ matrix: m.matrix,
18513
+ overall: m.overall,
18514
+ finding_counts: m.finding_counts,
18515
+ assessment_count: section2.assessments.length,
18516
+ open_findings: open2.length,
18517
+ lanes: lanes2,
18518
+ p0: p02,
18519
+ events: []
18520
+ };
18521
+ }
18522
+ const root = repoRootOf(ctx, REPO_MODE_ONLY);
18168
18523
  const library = libraryOf(root);
18169
18524
  let auditId;
18170
18525
  try {
@@ -18179,9 +18534,7 @@ function buildKritikCatalog(ctx) {
18179
18534
  throw new ToolError(error51.message);
18180
18535
  }
18181
18536
  const { section, matrix, file: file2 } = computed;
18182
- const open = section.findings.filter(isOpenFinding);
18183
- const lanes = { P0: 0, P1: 0, P2: 0, P3: 0 };
18184
- for (const finding of open) lanes[priorityOf(finding, library)]++;
18537
+ const { open, lanes, p0 } = openFindingsSummary(section.findings, library);
18185
18538
  let events = [];
18186
18539
  if (args.record === true) {
18187
18540
  const graph = await load2();
@@ -18198,13 +18551,7 @@ function buildKritikCatalog(ctx) {
18198
18551
  assessment_count: section.assessments.length,
18199
18552
  open_findings: open.length,
18200
18553
  lanes,
18201
- p0: open.filter((finding) => priorityOf(finding, library) === "P0").map((finding) => ({
18202
- id: finding.id,
18203
- surface: finding.surface,
18204
- criterion_id: finding.criterion_id,
18205
- title: finding.title,
18206
- severity: severityOf(finding, library)
18207
- })),
18554
+ p0,
18208
18555
  events
18209
18556
  };
18210
18557
  }
@@ -18212,7 +18559,7 @@ function buildKritikCatalog(ctx) {
18212
18559
  tool(
18213
18560
  {
18214
18561
  name: "kritik_findings",
18215
- description: "Findings across every audit, with their derived severity and priority. Filter by surface, status, priority, or criterion. Severity and priority are computed from impact x likelihood and cost on every read \u2014 they are never stored, so they cannot drift from the numbers behind them.",
18562
+ description: "Findings, with their derived severity and priority. Filter by surface, status, priority, criterion, or finding id. Severity and priority are computed from impact x likelihood and cost on every read \u2014 they are never stored, so they cannot drift from the numbers behind them. Repo mode reads across every audit under docs/quality/audits/, filterable by audit_id; hosted findings are a single living pool with no audit_id partition.",
18216
18563
  inputSchema: {
18217
18564
  type: "object",
18218
18565
  properties: {
@@ -18220,13 +18567,29 @@ function buildKritikCatalog(ctx) {
18220
18567
  status: { type: "string", enum: [...FINDING_STATUSES] },
18221
18568
  priority: { type: "string", enum: ["P0", "P1", "P2", "P3"] },
18222
18569
  criterion_id: { type: "string" },
18223
- audit_id: { type: "string", description: "Default: every audit." }
18570
+ finding_id: { type: "string" },
18571
+ audit_id: { type: "string", description: "Default: every audit. Not valid in hosted mode." }
18224
18572
  },
18225
18573
  additionalProperties: false
18226
18574
  }
18227
18575
  },
18228
18576
  async (args) => {
18229
- const root = rootOf(ctx);
18577
+ const hosted = ctx.qualityRoot === void 0;
18578
+ if (hosted) {
18579
+ if (typeof args.audit_id === "string" && args.audit_id !== "") {
18580
+ throw new ToolError("Hosted findings are a living pool \u2014 audit_id does not partition them (issue #400 decision 3).");
18581
+ }
18582
+ const graph = await load2();
18583
+ const { section, library: library2 } = hostedSection(graph);
18584
+ const rows2 = section.findings.map((finding) => ({
18585
+ ...finding,
18586
+ severity: severityOf(finding, library2),
18587
+ priority: priorityOf(finding, library2)
18588
+ }));
18589
+ const matches2 = rows2.filter((row) => matchesFindingArgs(row, args));
18590
+ return { total: matches2.length, findings: matches2 };
18591
+ }
18592
+ const root = repoRootOf(ctx, REPO_MODE_ONLY);
18230
18593
  const library = libraryOf(root);
18231
18594
  const auditIds = typeof args.audit_id === "string" && args.audit_id !== "" ? [args.audit_id] : listAuditIds(root);
18232
18595
  const rows = auditIds.flatMap(
@@ -18237,20 +18600,14 @@ function buildKritikCatalog(ctx) {
18237
18600
  priority: priorityOf(finding, library)
18238
18601
  }))
18239
18602
  );
18240
- const matches = rows.filter((row) => {
18241
- if (typeof args.surface === "string" && row.surface !== args.surface) return false;
18242
- if (typeof args.status === "string" && (row.status ?? "open") !== args.status) return false;
18243
- if (typeof args.priority === "string" && row.priority !== args.priority) return false;
18244
- if (typeof args.criterion_id === "string" && row.criterion_id !== args.criterion_id) return false;
18245
- return true;
18246
- });
18603
+ const matches = rows.filter((row) => matchesFindingArgs(row, args));
18247
18604
  return { total: matches.length, findings: matches };
18248
18605
  }
18249
18606
  );
18250
18607
  tool(
18251
18608
  {
18252
18609
  name: "kritik_signals",
18253
- description: "The signal pack: every applicable criterion's mechanically checkable statements, expanded across the surfaces it applies to, plus anything that has tripped since the last recorded audit. These are statements to CHECK, not commands to run \u2014 a grep that must return nothing, a CI job that must exist \u2014 so run them yourself and report what failed with kritik_trip_signal.",
18610
+ description: "The signal pack: every applicable criterion's mechanically checkable statements, expanded across the surfaces it applies to, plus anything that has tripped since the last recorded audit. These are statements to CHECK, not commands to run \u2014 a grep that must return nothing, a CI job that must exist \u2014 so run them yourself and report what failed with kritik_trip_signal. Repo sessions only: the pack and its run sheet live with the code.",
18254
18611
  inputSchema: {
18255
18612
  type: "object",
18256
18613
  properties: {
@@ -18262,7 +18619,10 @@ function buildKritikCatalog(ctx) {
18262
18619
  }
18263
18620
  },
18264
18621
  async (args) => {
18265
- const root = rootOf(ctx);
18622
+ const root = repoRootOf(
18623
+ ctx,
18624
+ "Signals are statements checked against the repository \u2014 the pack and its run sheet live with the code."
18625
+ );
18266
18626
  const library = libraryOf(root);
18267
18627
  const profile = profileOf(root);
18268
18628
  const filter = {
@@ -18278,6 +18638,115 @@ function buildKritikCatalog(ctx) {
18278
18638
  return { library_version: library.version, total: rows.length, signals: rows, tripped_since_last_audit: tripped };
18279
18639
  }
18280
18640
  );
18641
+ tool(
18642
+ {
18643
+ name: "kritik_regressions",
18644
+ description: "What got worse between two audits: a cell whose maturity level dropped, a cell that gained an open Critical or High finding, and a finding that was resolved and is open again. Cells scored in only one of the two audits are not compared \u2014 a half-finished audit is not a regression. With record=true, appends one quality.signal.tripped per regression (repo mode only \u2014 hosted comparisons are read-only and cover assessment-level drops, since hosted findings are a living pool rather than per-audit snapshots). A tripped signal is NOT a finding; it is the prompt to go look.",
18645
+ inputSchema: {
18646
+ type: "object",
18647
+ properties: {
18648
+ from: { type: "string", description: "The older audit. Default: the audit before `to`." },
18649
+ to: { type: "string", description: "The newer audit. Default: the newest on disk." },
18650
+ record: { type: "boolean", description: "Append one quality.signal.tripped per regression." }
18651
+ },
18652
+ additionalProperties: false
18653
+ }
18654
+ },
18655
+ async (args) => {
18656
+ const hosted = ctx.qualityRoot === void 0;
18657
+ if (hosted) {
18658
+ if (args.record === true) refuseHostedRecord("quality.signal.tripped");
18659
+ const graph = await load2();
18660
+ const { section, library: library2 } = hostedSection(graph);
18661
+ const grouped = /* @__PURE__ */ new Map();
18662
+ for (const assessment of section.assessments) {
18663
+ if (typeof assessment.audit_id !== "string" || assessment.audit_id === "") continue;
18664
+ const bucket = grouped.get(assessment.audit_id);
18665
+ if (bucket) bucket.push(assessment);
18666
+ else grouped.set(assessment.audit_id, [assessment]);
18667
+ }
18668
+ const audits2 = [...grouped.keys()].sort();
18669
+ const { from: from2, to: to2 } = resolveAuditPair(audits2, args, "in this project's assessments");
18670
+ const fromState = { assessments: grouped.get(from2) ?? [], findings: section.findings };
18671
+ const toState = { assessments: grouped.get(to2) ?? [], findings: section.findings };
18672
+ let regressions2;
18673
+ try {
18674
+ regressions2 = detectRegressions(fromState, toState, library2);
18675
+ } catch (error51) {
18676
+ throw new ToolError(error51.message);
18677
+ }
18678
+ return {
18679
+ from: from2,
18680
+ to: to2,
18681
+ total: regressions2.length,
18682
+ regressions: regressions2,
18683
+ events: [],
18684
+ note: "hosted comparison covers assessment level drops only \u2014 findings are a living pool (issue #400 decision 3)"
18685
+ };
18686
+ }
18687
+ const root = repoRootOf(ctx, REPO_MODE_ONLY);
18688
+ const library = libraryOf(root);
18689
+ const audits = listAuditIds(root);
18690
+ const { from, to } = resolveAuditPair(audits, args, "under docs/quality/audits/");
18691
+ let regressions;
18692
+ try {
18693
+ regressions = detectRegressions(
18694
+ loadQualitySection(root, from, library),
18695
+ loadQualitySection(root, to, library),
18696
+ library
18697
+ );
18698
+ } catch (error51) {
18699
+ throw new ToolError(error51.message);
18700
+ }
18701
+ let events = [];
18702
+ if (args.record === true && regressions.length > 0) {
18703
+ const graph = await load2();
18704
+ events = await record2(
18705
+ graph,
18706
+ regressions.map(
18707
+ (regression) => signalTrippedInput({
18708
+ criterion_id: regression.criterion_id,
18709
+ surface: regression.surface,
18710
+ signal: regression.signal,
18711
+ detail: regression.detail
18712
+ })
18713
+ )
18714
+ );
18715
+ }
18716
+ return { from, to, total: regressions.length, regressions, events };
18717
+ }
18718
+ );
18719
+ tool(
18720
+ {
18721
+ name: "kritik_trend",
18722
+ description: "Where the product stood at each recorded audit, oldest first: one row per quality.audit.completed in the journal, the overall score per surface (or one domain's score with domain), and how each moved against the row above. The score, not the findings \u2014 'from where we started to where we are now'. Rows are ordered by when they were recorded, a re-recorded audit id keeps only its latest reading, and a framework major bump between two audits marks the later row comparable=false with no delta across it. Works in both modes: repo reads the journal sidecar, hosted reads the hosted journal.",
18723
+ inputSchema: {
18724
+ type: "object",
18725
+ properties: {
18726
+ surface: { type: "string", description: "One column only." },
18727
+ domain: { type: "string", description: "Domain code, e.g. SEC \u2014 that domain's score per surface instead of the roll-up." }
18728
+ },
18729
+ additionalProperties: false
18730
+ }
18731
+ },
18732
+ async (args) => {
18733
+ const graph = await load2();
18734
+ const profile = ctx.qualityRoot === void 0 ? graph.loaded.bundle.quality?.profile : loadProfile(ctx.qualityRoot) ?? void 0;
18735
+ const trend = deriveQualityTrend(graph.journal, profile);
18736
+ const filter = {
18737
+ ...typeof args.surface === "string" && args.surface !== "" ? { surface: args.surface } : {},
18738
+ ...typeof args.domain === "string" && args.domain !== "" ? { domain: args.domain } : {}
18739
+ };
18740
+ const { surfaces, rows } = trendRows(trend, filter);
18741
+ return {
18742
+ total: trend.snapshots.length,
18743
+ surfaces,
18744
+ rows,
18745
+ snapshots: trend.snapshots,
18746
+ ...trend.snapshots.length === 0 ? { note: "No recorded audits yet \u2014 `kritik_matrix` with record=true writes one." } : {}
18747
+ };
18748
+ }
18749
+ );
18281
18750
  tool(
18282
18751
  {
18283
18752
  name: "kritik_issue",
@@ -18295,7 +18764,28 @@ function buildKritikCatalog(ctx) {
18295
18764
  }
18296
18765
  },
18297
18766
  async (args) => {
18298
- const root = rootOf(ctx);
18767
+ const hosted = ctx.qualityRoot === void 0;
18768
+ if (hosted) {
18769
+ const graph = await load2();
18770
+ const { section, library: library2 } = hostedSection(graph);
18771
+ if (library2 === void 0) {
18772
+ throw new ToolError("This hosted project's quality section carries no criteria vocabulary \u2014 no embedded library and no scored criteria to synthesize one from.");
18773
+ }
18774
+ const criterion2 = criterionOf(library2, requireString(args, "criterion_id"));
18775
+ const surface2 = requireString(args, "surface");
18776
+ if (section.profile) surfaceOf(section.profile, surface2, true);
18777
+ let finding2;
18778
+ if (typeof args.finding_id === "string" && args.finding_id !== "") {
18779
+ finding2 = section.findings.find((candidate) => candidate.id === args.finding_id);
18780
+ if (!finding2) throw new ToolError(`No finding "${args.finding_id}" in this hosted project's quality section.`);
18781
+ }
18782
+ return renderIssue(criterion2, {
18783
+ surface: surface2,
18784
+ ...typeof args.level === "number" ? { level: args.level } : {},
18785
+ ...finding2 !== void 0 ? { finding: finding2, library: library2 } : {}
18786
+ });
18787
+ }
18788
+ const root = repoRootOf(ctx, REPO_MODE_ONLY);
18299
18789
  const library = libraryOf(root);
18300
18790
  const criterion = criterionOf(library, requireString(args, "criterion_id"));
18301
18791
  const surface = requireString(args, "surface");
@@ -18317,7 +18807,7 @@ function buildKritikCatalog(ctx) {
18317
18807
  tool(
18318
18808
  {
18319
18809
  name: "kritik_score",
18320
- description: "Record one (criterion x surface) maturity level with the evidence behind it. A cell holds exactly one level, so re-scoring replaces in place. Evidence is required: a score without a citation is an opinion, not an assessment. Score what the code IS, never what an open PR promises \u2014 that is what makes a trend real.",
18810
+ description: "Record one (criterion x surface) maturity level with the evidence behind it. A cell holds exactly one level, so re-scoring replaces in place. Evidence is required: a score without a citation is an opinion, not an assessment. Score what the code IS, never what an open PR promises \u2014 that is what makes a trend real. Repo sessions only: scoring reads the code, so a hosted session refuses.",
18321
18811
  inputSchema: {
18322
18812
  type: "object",
18323
18813
  properties: {
@@ -18337,7 +18827,7 @@ function buildKritikCatalog(ctx) {
18337
18827
  }
18338
18828
  },
18339
18829
  async (args) => {
18340
- const root = rootOf(ctx);
18830
+ const root = repoRootOf(ctx, "Scoring reads the code \u2014 evidence is file:line against a working tree.");
18341
18831
  const library = libraryOf(root);
18342
18832
  const profile = profileOf(root);
18343
18833
  const criterionId = requireString(args, "criterion_id");
@@ -18382,7 +18872,7 @@ function buildKritikCatalog(ctx) {
18382
18872
  tool(
18383
18873
  {
18384
18874
  name: "kritik_open_finding",
18385
- description: "Open a finding on a (criterion x surface) cell and append quality.finding.opened. One finding is one defect \u2014 not one criterion, and not one surface's worth of grumbling. Verify Critical and High adversarially BEFORE opening: try to refute them against the repo, and record the verdict. Severity and priority come back derived; they are never stored.",
18875
+ description: "Open a finding on a (criterion x surface) cell and append quality.finding.opened. One finding is one defect \u2014 not one criterion, and not one surface's worth of grumbling. Verify Critical and High adversarially BEFORE opening: try to refute them against the repo, and record the verdict. Severity and priority come back derived; they are never stored. Repo sessions only: a new finding cites code, so a hosted session refuses.",
18386
18876
  inputSchema: {
18387
18877
  type: "object",
18388
18878
  properties: {
@@ -18415,7 +18905,7 @@ function buildKritikCatalog(ctx) {
18415
18905
  }
18416
18906
  },
18417
18907
  async (args) => {
18418
- const root = rootOf(ctx);
18908
+ const root = repoRootOf(ctx, "A new finding cites code: evidence is file:line, verified adversarially against the checkout.");
18419
18909
  const library = libraryOf(root);
18420
18910
  const profile = profileOf(root);
18421
18911
  const criterionId = requireString(args, "criterion_id");
@@ -18489,14 +18979,30 @@ function buildKritikCatalog(ctx) {
18489
18979
  }
18490
18980
  },
18491
18981
  async (args) => {
18492
- const root = rootOf(ctx);
18493
18982
  const id = requireString(args, "finding_id");
18983
+ const resolvedBy = typeof args.resolved_by === "string" && args.resolved_by !== "" ? args.resolved_by : void 0;
18984
+ if (ctx.qualityRoot === void 0) {
18985
+ const graph2 = await load2();
18986
+ const { section } = hostedSection(graph2);
18987
+ const finding2 = section.findings.find((candidate) => candidate.id === id);
18988
+ if (!finding2) throw new ToolError(`No finding "${id}" in this hosted project's quality section.`);
18989
+ if (finding2.status === "resolved") {
18990
+ return { finding: finding2, events: [], note: "Already resolved \u2014 nothing written." };
18991
+ }
18992
+ const events2 = await appendHosted(ctx.store, [
18993
+ { type: "quality.finding.resolved", finding_id: finding2.id, ...resolvedBy !== void 0 ? { resolved_by: resolvedBy } : {} }
18994
+ ]);
18995
+ return {
18996
+ finding: { ...finding2, status: "resolved", ...resolvedBy !== void 0 ? { resolved_by: resolvedBy } : {} },
18997
+ events: events2
18998
+ };
18999
+ }
19000
+ const root = repoRootOf(ctx, REPO_MODE_ONLY);
18494
19001
  const located = locateFinding(root, id);
18495
19002
  if (!located) throw new ToolError(`No finding "${id}" in any audit under docs/quality/audits/.`);
18496
19003
  if (located.finding.status === "resolved") {
18497
19004
  return { finding: located.finding, audit_id: located.auditId, events: [], note: "Already resolved \u2014 nothing written." };
18498
19005
  }
18499
- const resolvedBy = typeof args.resolved_by === "string" && args.resolved_by !== "" ? args.resolved_by : void 0;
18500
19006
  const graph = await load2();
18501
19007
  const events = await record2(graph, [findingResolvedInput(located.finding, resolvedBy)]);
18502
19008
  const { findings, finding } = resolveFinding(located.file.findings, id, resolvedBy);
@@ -18507,7 +19013,7 @@ function buildKritikCatalog(ctx) {
18507
19013
  tool(
18508
19014
  {
18509
19015
  name: "kritik_accept_finding",
18510
- description: "Record a finding as a known, owned risk. The note is required \u2014 an accepted risk is a decision and reads like one, and the findings board renders it as a decision-log entry. No journal event: acceptance is a state of the finding, not something that happened to the product.",
19016
+ description: "Record a finding as a known, owned risk. The note is required \u2014 an accepted risk is a decision and reads like one, and the findings board renders it as a decision-log entry. In repo mode acceptance is a state of the finding, written straight to the findings file with no journal event; a hosted session has no findings file to hold that state, so it appends quality.finding.accepted instead, and the read derives status accepted-risk from it.",
18511
19017
  inputSchema: {
18512
19018
  type: "object",
18513
19019
  properties: {
@@ -18519,9 +19025,20 @@ function buildKritikCatalog(ctx) {
18519
19025
  }
18520
19026
  },
18521
19027
  async (args) => {
18522
- const root = rootOf(ctx);
18523
19028
  const id = requireString(args, "finding_id");
18524
19029
  const note = requireString(args, "note");
19030
+ if (ctx.qualityRoot === void 0) {
19031
+ const graph = await load2();
19032
+ const { section } = hostedSection(graph);
19033
+ const finding2 = section.findings.find((candidate) => candidate.id === id);
19034
+ if (!finding2) throw new ToolError(`No finding "${id}" in this hosted project's quality section.`);
19035
+ const events = await appendHosted(ctx.store, [{ type: "quality.finding.accepted", finding_id: finding2.id, reason: note }]);
19036
+ return {
19037
+ finding: { ...finding2, status: "accepted-risk", detail: acceptedDetail(finding2.detail, note) },
19038
+ events
19039
+ };
19040
+ }
19041
+ const root = repoRootOf(ctx, REPO_MODE_ONLY);
18525
19042
  const located = locateFinding(root, id);
18526
19043
  if (!located) throw new ToolError(`No finding "${id}" in any audit under docs/quality/audits/.`);
18527
19044
  const { findings, finding } = acceptFinding(located.file.findings, id, note);
@@ -18532,7 +19049,7 @@ function buildKritikCatalog(ctx) {
18532
19049
  tool(
18533
19050
  {
18534
19051
  name: "kritik_trip_signal",
18535
- description: "Record that a monitoring signal failed between audits: appends quality.signal.tripped. A tripped signal is NOT a finding \u2014 it is the prompt to go look. Cheap, frequent, and allowed to be wrong, where a finding is expensive, rare, and has survived an adversarial pass.",
19052
+ description: "Record that a monitoring signal failed between audits: appends quality.signal.tripped. A tripped signal is NOT a finding \u2014 it is the prompt to go look. Cheap, frequent, and allowed to be wrong, where a finding is expensive, rare, and has survived an adversarial pass. Repo sessions only: signals are checked against the repository.",
18536
19053
  inputSchema: {
18537
19054
  type: "object",
18538
19055
  properties: {
@@ -18546,7 +19063,10 @@ function buildKritikCatalog(ctx) {
18546
19063
  }
18547
19064
  },
18548
19065
  async (args) => {
18549
- const root = rootOf(ctx);
19066
+ const root = repoRootOf(
19067
+ ctx,
19068
+ "Signals are statements checked against the repository \u2014 the pack and its run sheet live with the code."
19069
+ );
18550
19070
  const library = libraryOf(root);
18551
19071
  const profile = profileOf(root);
18552
19072
  const criterion = criterionOf(library, requireString(args, "criterion_id"));
@@ -19082,15 +19602,15 @@ ${node.description ?? ""}`.toLowerCase();
19082
19602
 
19083
19603
  // src/store.ts
19084
19604
  import { writeFileSync as writeFileSync3 } from "node:fs";
19085
- import { resolve as resolve2 } from "node:path";
19605
+ import { resolve as resolve3 } from "node:path";
19086
19606
  var MCP_ACTOR = "arkaik-mcp";
19087
19607
  var DEFAULT_BUNDLE_PATH2 = "docs/arkaik/bundle.json";
19088
19608
  function resolveBundlePath(argv2, env) {
19089
19609
  const flagIndex = argv2.indexOf("--bundle");
19090
19610
  const flagValue2 = flagIndex !== -1 ? argv2[flagIndex + 1] : void 0;
19091
- if (flagValue2) return resolve2(flagValue2);
19092
- if (env.ARKAIK_BUNDLE) return resolve2(env.ARKAIK_BUNDLE);
19093
- return resolve2(DEFAULT_BUNDLE_PATH2);
19611
+ if (flagValue2) return resolve3(flagValue2);
19612
+ if (env.ARKAIK_BUNDLE) return resolve3(env.ARKAIK_BUNDLE);
19613
+ return resolve3(DEFAULT_BUNDLE_PATH2);
19094
19614
  }
19095
19615
  function loadBundle(bundlePath) {
19096
19616
  return validateBundleAt(bundlePath);
@@ -19258,6 +19778,30 @@ function createRemoteStore(options) {
19258
19778
  },
19259
19779
  describe() {
19260
19780
  return `hosted project: ${options.projectId} at ${base}`;
19781
+ },
19782
+ // `quality.finding.*` events do not fold through `applyOps` — a finding
19783
+ // isn't a node or edge — so they get their own endpoint rather than riding
19784
+ // `/mutations`. And unlike `persist`, there is no client-side gate at all:
19785
+ // whether a finding is still open is a post-fold read of the journal, and
19786
+ // the server holds that journal. Sending an "open" guess from here could
19787
+ // only be stale the moment two sessions race, so this method does no
19788
+ // checking of its own — it forwards the inputs and lets the server's
19789
+ // verdict (post-fold, under its row lock) be the only one that counts.
19790
+ async appendQualityEvents(inputs) {
19791
+ try {
19792
+ const result = await request("/quality/events", {
19793
+ method: "POST",
19794
+ body: JSON.stringify({ events: inputs })
19795
+ });
19796
+ return result.events;
19797
+ } catch (err) {
19798
+ const e = err;
19799
+ if (e.status === 422 && e.body?.error === "refused") {
19800
+ const detail = e.body.refusals ? e.body.refusals.map((r) => `${r.finding_id}: ${r.reason}`).join(", ") : e.body.reason ?? "refused";
19801
+ throw new Error(`Quality events refused \u2014 ${detail}`);
19802
+ }
19803
+ throw err;
19804
+ }
19261
19805
  }
19262
19806
  };
19263
19807
  }
@@ -19317,7 +19861,7 @@ function resolveRemoteConfig(argv2, env, cwd) {
19317
19861
  }
19318
19862
 
19319
19863
  // src/index.ts
19320
- var VERSION = "0.3.0";
19864
+ var VERSION = "0.5.0";
19321
19865
  var argv = process.argv.slice(2);
19322
19866
  if (argv.includes("--help") || argv.includes("-h")) {
19323
19867
  process.stdout.write(
@@ -19354,14 +19898,8 @@ function resolveStore() {
19354
19898
  };
19355
19899
  }
19356
19900
  const bundlePath = resolveBundlePath(argv, process.env);
19357
- return { store: createFileStore(bundlePath), qualityRoot: qualityRootFor(bundlePath) };
19358
- }
19359
- function qualityRootFor(bundlePath) {
19360
- if (process.env.ARKAIK_QUALITY_ROOT) return resolve3(process.env.ARKAIK_QUALITY_ROOT);
19361
- const dir = dirname4(bundlePath);
19362
- const parent = dirname4(dir);
19363
- if (dir.endsWith(`${sep}arkaik`) && parent.endsWith(`${sep}docs`)) return dirname4(parent);
19364
- return dir;
19901
+ const qualityRoot2 = resolveQualityRoot({ bundlePath, fallback: dirname4(bundlePath) });
19902
+ return { store: createFileStore(bundlePath), qualityRoot: qualityRoot2 };
19365
19903
  }
19366
19904
  var store;
19367
19905
  var qualityRoot;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "arkaik-mcp",
3
- "version": "0.3.0",
3
+ "version": "0.5.0",
4
4
  "description": "Arkaik MCP server — stdio tools over an Arkaik product-graph bundle: read projections plus validator-gated dual-write mutations.",
5
5
  "license": "MIT",
6
6
  "type": "module",