@mrciphersmith/keryx 0.4.52 → 0.4.54

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -38284,7 +38284,7 @@ var package_default;
38284
38284
  var init_package = __esm(() => {
38285
38285
  package_default = {
38286
38286
  name: "@mrciphersmith/keryx",
38287
- version: "0.4.52",
38287
+ version: "0.4.54",
38288
38288
  description: "Version-controlled project context for AI coding agents: code graph, architecture wiki, project memory, relevant tests, quality signals, and task flows.",
38289
38289
  private: false,
38290
38290
  publishConfig: {
@@ -40923,9 +40923,15 @@ function rankMetaprojectSearchHits(query, nodes, hits) {
40923
40923
  }
40924
40924
  return result.concat(partial.slice(0, METAPROJECT_NODE_LIMIT - result.length));
40925
40925
  }
40926
+ function metaprojectWikiGroupKey(node) {
40927
+ return node.pageType || METAPROJECT_WIKI_UNTYPED_GROUP;
40928
+ }
40926
40929
  function isMetaprojectScope(value) {
40927
40930
  return METAPROJECT_SCOPES.some((scope) => scope === value);
40928
40931
  }
40932
+ function isMetaprojectTreeScope(value) {
40933
+ return METAPROJECT_TREE_SCOPES.some((scope) => scope === value);
40934
+ }
40929
40935
  function isMetaprojectV2EdgeKind(value) {
40930
40936
  return METAPROJECT_EDGE_KINDS_V2.some((kind) => kind === value);
40931
40937
  }
@@ -40944,6 +40950,9 @@ function validId(value) {
40944
40950
  function validDirection(value) {
40945
40951
  return value === "both" || value === "incoming" || value === "outgoing";
40946
40952
  }
40953
+ function validTreeParent(scope, value) {
40954
+ return scope === "graph" ? isMetaprojectRelativePath(value) : validId(value);
40955
+ }
40947
40956
  function parseV2(input) {
40948
40957
  const keys = Object.keys(input);
40949
40958
  const exact = (...allowed) => keys.every((key) => allowed.includes(key));
@@ -40955,7 +40964,7 @@ function parseV2(input) {
40955
40964
  if (input.expectedSnapshotId !== undefined && !isSha256(input.expectedSnapshotId))
40956
40965
  throw invalid();
40957
40966
  const base = { version: 2, ...input.expectedSnapshotId !== undefined && { expectedSnapshotId: input.expectedSnapshotId } };
40958
- const { action, id, artifact, section, digest, scopes, query, collection, cursor, depth, kinds, direction, includeArchive } = input;
40967
+ const { action, id, artifact, section, digest, scopes, query, collection, cursor, depth, kinds, direction, includeArchive, scope, parent } = input;
40959
40968
  switch (action) {
40960
40969
  case "catalog":
40961
40970
  if (allowed())
@@ -40993,6 +41002,11 @@ function parseV2(input) {
40993
41002
  return { ...base, action, id, ...cursor !== undefined && { cursor } };
40994
41003
  }
40995
41004
  break;
41005
+ case "tree":
41006
+ if (allowed("scope", "parent", "cursor") && isMetaprojectTreeScope(scope) && (parent === undefined || validTreeParent(scope, parent)) && (cursor === undefined || validId(cursor))) {
41007
+ return { ...base, action, scope, ...parent !== undefined && { parent }, ...cursor !== undefined && { cursor } };
41008
+ }
41009
+ break;
40996
41010
  }
40997
41011
  throw invalid();
40998
41012
  }
@@ -41003,7 +41017,7 @@ function parseExplorerRequest(value) {
41003
41017
  throw new MetaprojectRequestError("unsupported-version", "Unsupported Metaproject request version.");
41004
41018
  return parseV2(value);
41005
41019
  }
41006
- var METAPROJECT_SCHEMA = 1, METAPROJECT_NODE_LIMIT = 200, METAPROJECT_EDGE_LIMIT = 400, METAPROJECT_EDGE_KINDS, METAPROJECT_EDGE_KINDS_V2, METAPROJECT_SCHEMA_V2 = 2, METAPROJECT_RESPONSE_BYTES_V2, METAPROJECT_PAGE_SIZE_V2 = 100, METAPROJECT_CAPABILITIES, METAPROJECT_SCOPES, MetaprojectRequestError;
41020
+ var METAPROJECT_SCHEMA = 1, METAPROJECT_NODE_LIMIT = 200, METAPROJECT_EDGE_LIMIT = 400, METAPROJECT_EDGE_KINDS, METAPROJECT_EDGE_KINDS_V2, METAPROJECT_SCHEMA_V2 = 2, METAPROJECT_RESPONSE_BYTES_V2, METAPROJECT_PAGE_SIZE_V2 = 100, METAPROJECT_CAPABILITIES, METAPROJECT_SCOPES, METAPROJECT_TREE_SCOPES, METAPROJECT_WIKI_UNTYPED_GROUP = "other", MetaprojectRequestError;
41007
41021
  var init_metaproject_explorer_contract = __esm(() => {
41008
41022
  METAPROJECT_EDGE_KINDS = ["imports", "asset", "describes", "links", "contains", "defines", "calls"];
41009
41023
  METAPROJECT_EDGE_KINDS_V2 = [...METAPROJECT_EDGE_KINDS, "changes-spec", "spec-context"];
@@ -41014,9 +41028,11 @@ var init_metaproject_explorer_contract = __esm(() => {
41014
41028
  "search",
41015
41029
  "neighbors",
41016
41030
  "openspec-list",
41017
- "openspec-history"
41031
+ "openspec-history",
41032
+ "tree"
41018
41033
  ];
41019
41034
  METAPROJECT_SCOPES = ["graph", "wiki", "spec", "change", "archive"];
41035
+ METAPROJECT_TREE_SCOPES = ["graph", "wiki"];
41020
41036
  MetaprojectRequestError = class MetaprojectRequestError extends Error {
41021
41037
  code;
41022
41038
  constructor(code, message) {
@@ -42390,6 +42406,72 @@ function cursorValue(snapshotId, key, value) {
42390
42406
  throw new MetaprojectRequestError("invalid-input", "The Metaproject cursor does not match this request.");
42391
42407
  }
42392
42408
  }
42409
+ function offsetPage(items, offset, { next, action, item, byteLimit }) {
42410
+ if (typeof offset !== "number" || offset > 0 && offset >= items.length) {
42411
+ throw new MetaprojectRequestError("invalid-input", `The Metaproject ${action} cursor offset is out of range.`);
42412
+ }
42413
+ const page = boundedItems2(items.slice(offset), METAPROJECT_PAGE_SIZE_V2, byteLimit);
42414
+ if (!page.length && offset < items.length)
42415
+ throw new MetaprojectRequestError("response-limit", `Metaproject ${action} ${item} exceeds the response limit.`);
42416
+ const end = offset + page.length;
42417
+ return { page, ...end < items.length && { nextCursor: next(end) } };
42418
+ }
42419
+ function notFoundParent() {
42420
+ return new MetaprojectRequestError("not-found", "Unknown Metaproject tree parent.");
42421
+ }
42422
+ function graphTree(model, parent) {
42423
+ if (!model.graphPresent)
42424
+ return { entries: [], partial: true };
42425
+ const prefix = parent === undefined ? "" : `${parent}/`;
42426
+ const folders = new Map;
42427
+ const files = [];
42428
+ const modules = new Map;
42429
+ for (const node of model.nodes) {
42430
+ if (node.kind === "module")
42431
+ modules.set(node.path, node);
42432
+ if (node.kind !== "file" || !node.path.startsWith(prefix))
42433
+ continue;
42434
+ const rest = node.path.slice(prefix.length);
42435
+ const slash = rest.indexOf("/");
42436
+ if (slash < 0)
42437
+ files.push(node);
42438
+ else
42439
+ folders.set(rest.slice(0, slash), (folders.get(rest.slice(0, slash)) ?? 0) + 1);
42440
+ }
42441
+ if (parent !== undefined && !folders.size && !files.length)
42442
+ throw notFoundParent();
42443
+ const folderEntries = [...folders].sort(([a], [b]) => compareText2(a, b)).map(([name, count]) => {
42444
+ const folderPath = `${prefix}${name}`;
42445
+ const module = modules.get(folderPath);
42446
+ return { type: "folder", path: folderPath, name, files: count, ...module && { module } };
42447
+ });
42448
+ const fileEntries = files.sort((a, b) => compareText2(a.path, b.path)).map((node) => ({ type: "node", node }));
42449
+ return { entries: [...folderEntries, ...fileEntries], partial: false };
42450
+ }
42451
+ function wikiGroupName(key) {
42452
+ const words = key.replaceAll("-", " ");
42453
+ return words.charAt(0).toUpperCase() + words.slice(1);
42454
+ }
42455
+ function wikiTree(nodes, parent) {
42456
+ const groups = new Map;
42457
+ for (const node of nodes) {
42458
+ if (node.kind !== "wiki")
42459
+ continue;
42460
+ const key = metaprojectWikiGroupKey(node);
42461
+ const group = groups.get(key);
42462
+ if (group)
42463
+ group.push(node);
42464
+ else
42465
+ groups.set(key, [node]);
42466
+ }
42467
+ if (parent === undefined) {
42468
+ return [...groups].map(([key, pages]) => ({ type: "group", key, name: wikiGroupName(key), pages: pages.length })).sort((a, b) => compareText2(a.name, b.name) || compareText2(a.key, b.key));
42469
+ }
42470
+ const pages = groups.get(parent);
42471
+ if (!pages)
42472
+ throw notFoundParent();
42473
+ return pages.sort((a, b) => compareText2(a.title, b.title) || compareText2(a.path, b.path)).map((node) => ({ type: "node", node }));
42474
+ }
42393
42475
  function graphRequest(request) {
42394
42476
  switch (request.action) {
42395
42477
  case "detail":
@@ -42536,15 +42618,15 @@ class V2Read {
42536
42618
  this.model = model;
42537
42619
  this.source = source;
42538
42620
  this.openEdges = openEdges;
42539
- this.base = { schemaVersion: METAPROJECT_SCHEMA_V2, snapshotId: hash3([model.base.snapshotId, source.catalog.snapshotId, model.graph, model.graphReason, openEdges, diagnostics]) };
42621
+ this.base = { schemaVersion: METAPROJECT_SCHEMA_V2, snapshotId: hash3([model.base.snapshotId, source.catalog.snapshotId, openEdges, diagnostics]) };
42540
42622
  this.state = sourceState(source, diagnostics);
42541
42623
  this.openNodes = source.catalog.entries.map(entryNode);
42542
42624
  }
42543
- read(request) {
42625
+ async read(request, freshness) {
42544
42626
  checkSnapshot2(this.base.snapshotId, request.expectedSnapshotId);
42545
42627
  switch (request.action) {
42546
42628
  case "catalog":
42547
- return this.catalog();
42629
+ return this.catalog(await freshness());
42548
42630
  case "detail":
42549
42631
  return this.detail(request);
42550
42632
  case "neighbors":
@@ -42555,10 +42637,12 @@ class V2Read {
42555
42637
  return this.list(request.collection, request.cursor);
42556
42638
  case "openspec-history":
42557
42639
  return this.history(request.id, request.cursor);
42640
+ case "tree":
42641
+ return this.tree(request);
42558
42642
  }
42559
42643
  }
42560
- catalog() {
42561
- const { graph, graphReason, hasWikiLayer, hasSymbolLayer, counts } = this.model;
42644
+ catalog({ graph, graphReason }) {
42645
+ const { hasWikiLayer, hasSymbolLayer, counts } = this.model;
42562
42646
  const groups = [
42563
42647
  this.model.nodes.filter((node) => node.kind === "wiki"),
42564
42648
  this.model.nodes.filter((node) => node.kind !== "wiki"),
@@ -42643,19 +42727,26 @@ class V2Read {
42643
42727
  }
42644
42728
  }))
42645
42729
  ]);
42646
- if (typeof offset !== "number" || offset > 0 && offset >= hits.length) {
42647
- throw new MetaprojectRequestError("invalid-input", "The Metaproject search cursor offset is out of range.");
42648
- }
42649
- const page = boundedItems2(hits.slice(offset), METAPROJECT_PAGE_SIZE_V2, SEARCH_ITEMS_BYTES);
42650
- if (!page.length && offset < hits.length)
42651
- throw new MetaprojectRequestError("response-limit", "Metaproject search hit exceeds the response limit.");
42652
- const next = offset + page.length;
42653
- return {
42654
- ...this.base,
42655
- hits: page,
42656
- partial: partial || legacy.partial,
42657
- ...next < hits.length && { nextCursor: cursor(this.base.snapshotId, key, next) }
42658
- };
42730
+ const { page, nextCursor } = offsetPage(hits, offset, {
42731
+ next: (end) => cursor(this.base.snapshotId, key, end),
42732
+ action: "search",
42733
+ item: "hit",
42734
+ byteLimit: SEARCH_ITEMS_BYTES
42735
+ });
42736
+ return { ...this.base, hits: page, partial: partial || legacy.partial, ...nextCursor && { nextCursor } };
42737
+ }
42738
+ tree(request) {
42739
+ const { scope, parent } = request;
42740
+ const key = hash3(["tree", scope, parent ?? null]);
42741
+ const offset = cursorValue(this.base.snapshotId, key, request.cursor) ?? 0;
42742
+ const { entries, partial } = scope === "graph" ? graphTree(this.model, parent) : { entries: wikiTree(this.model.nodes, parent), partial: false };
42743
+ const { page, nextCursor } = offsetPage(entries, offset, {
42744
+ next: (end) => cursor(this.base.snapshotId, key, end),
42745
+ action: "tree",
42746
+ item: "entry",
42747
+ byteLimit: TREE_ITEMS_BYTES
42748
+ });
42749
+ return { ...this.base, scope, parent: parent ?? null, entries: page, partial, ...nextCursor && { nextCursor } };
42659
42750
  }
42660
42751
  openSpecSearch(needle, scope, scopes) {
42661
42752
  if (!needle || !scope.length)
@@ -42703,14 +42794,14 @@ async function metaprojectExplorerV2(projectRoot, request, load) {
42703
42794
  return { schemaVersion: METAPROJECT_SCHEMA_V2, actions: METAPROJECT_CAPABILITIES };
42704
42795
  try {
42705
42796
  const root = await realpath12(projectRoot);
42706
- const [{ graph: loaded, confirm, track }, source] = await Promise.all([
42797
+ const [{ graph: loaded, freshness, confirm, track }, source] = await Promise.all([
42707
42798
  load(root, graphRequest(request)),
42708
42799
  readOpenSpec(root)
42709
42800
  ]);
42710
42801
  const graph = { ...loaded, nodes: loaded.nodes.filter(safeGraphNode) };
42711
42802
  const { edges, diagnostics } = await buildRelationships(source, graph, root, track);
42712
42803
  await confirm();
42713
- const response = new V2Read(graph, source, edges, diagnostics).read(request);
42804
+ const response = await new V2Read(graph, source, edges, diagnostics).read(request, freshness);
42714
42805
  if (bytes(response) + 1 > METAPROJECT_RESPONSE_BYTES_V2) {
42715
42806
  throw new MetaprojectRequestError("response-limit", "Metaproject response exceeds the byte limit.");
42716
42807
  }
@@ -42723,7 +42814,7 @@ async function metaprojectExplorerV2(projectRoot, request, load) {
42723
42814
  throw new MetaprojectRequestError("source-unavailable", "Metaproject sources could not be read.");
42724
42815
  }
42725
42816
  }
42726
- var DEFAULT_SCOPES, MAX_DIAGNOSTICS2 = 64, MAX_EDGE_EVIDENCE = 3, MAX_DETAIL_RELATIONSHIPS = 40, CATALOG_METADATA_BYTES, SEARCH_ITEMS_BYTES, MAX_LEGACY_HITS_PER_SCOPE = 12000, bytes = (value) => Buffer.byteLength(JSON.stringify(value)), hash3 = (value) => createHash22("sha256").update(JSON.stringify(value)).digest("hex"), compareText2 = (a, b) => a < b ? -1 : Number(a > b);
42817
+ var DEFAULT_SCOPES, MAX_DIAGNOSTICS2 = 64, MAX_EDGE_EVIDENCE = 3, MAX_DETAIL_RELATIONSHIPS = 40, CATALOG_METADATA_BYTES, SEARCH_ITEMS_BYTES, TREE_ITEMS_BYTES, MAX_LEGACY_HITS_PER_SCOPE = 12000, bytes = (value) => Buffer.byteLength(JSON.stringify(value)), hash3 = (value) => createHash22("sha256").update(JSON.stringify(value)).digest("hex"), compareText2 = (a, b) => a < b ? -1 : Number(a > b);
42727
42818
  var init_metaproject_explorer_v2 = __esm(() => {
42728
42819
  init_service2();
42729
42820
  init_metaproject_explorer_contract();
@@ -42731,6 +42822,7 @@ var init_metaproject_explorer_v2 = __esm(() => {
42731
42822
  DEFAULT_SCOPES = ["graph", "wiki", "spec", "change"];
42732
42823
  CATALOG_METADATA_BYTES = 128 * 1024;
42733
42824
  SEARCH_ITEMS_BYTES = 900 * 1024;
42825
+ TREE_ITEMS_BYTES = 900 * 1024;
42734
42826
  });
42735
42827
 
42736
42828
  // src/integrations/metaproject-explorer.ts
@@ -42901,17 +42993,6 @@ async function loadExplorerGraph(root, request, observation) {
42901
42993
  edges.push({ from: page.node.id, to: found.id, kind: "links" });
42902
42994
  }
42903
42995
  }
42904
- let freshness = null;
42905
- if (graphPresent) {
42906
- try {
42907
- const provenance = ".metaproject/data/gdgraph/.provenance.json";
42908
- if (await exists(root, provenance))
42909
- await safeRead(root, provenance, 1024 * 1024);
42910
- freshness = await checkGraphStaleness(root);
42911
- } catch {
42912
- freshness = { status: "unknown", reasons: ["Graph provenance could not be read within the project"] };
42913
- }
42914
- }
42915
42996
  const layerStats = await Promise.all(["symbols.jsonl", "calls.jsonl", "wiki-pages.jsonl"].map(async (name) => {
42916
42997
  try {
42917
42998
  const relative = `${storage}/${name}`;
@@ -42952,8 +43033,6 @@ async function loadExplorerGraph(root, request, observation) {
42952
43033
  throw new Error("Symbol layer could not be read; rebuild the graph");
42953
43034
  }
42954
43035
  }
42955
- const graph = graphError ? "unknown" : freshness ? freshness.status === "fresh" ? "ready" : freshness.status : "missing";
42956
- const graphReason = graphError ?? freshness?.reasons.join("; ");
42957
43036
  return {
42958
43037
  base,
42959
43038
  nodes,
@@ -42961,26 +43040,44 @@ async function loadExplorerGraph(root, request, observation) {
42961
43040
  pages,
42962
43041
  hasSymbolLayer,
42963
43042
  hasWikiLayer,
42964
- graph,
42965
- graphReason,
43043
+ graphPresent,
43044
+ graphError,
42966
43045
  counts: { files: files.length, wiki: pages.length, modules: modules.size }
42967
43046
  };
42968
43047
  }
43048
+ async function explorerGraphFreshness(root, model) {
43049
+ if (model.graphError)
43050
+ return { graph: "unknown", graphReason: model.graphError };
43051
+ if (!model.graphPresent)
43052
+ return { graph: "missing" };
43053
+ let freshness;
43054
+ try {
43055
+ const provenance = ".metaproject/data/gdgraph/.provenance.json";
43056
+ if (await exists(root, provenance))
43057
+ await safeRead(root, provenance, 1024 * 1024);
43058
+ freshness = await checkGraphStaleness(root);
43059
+ } catch {
43060
+ freshness = { status: "unknown", reasons: ["Graph provenance could not be read within the project"] };
43061
+ }
43062
+ const graphReason = freshness.reasons.join("; ");
43063
+ return { graph: freshness.status === "fresh" ? "ready" : freshness.status, ...graphReason && { graphReason } };
43064
+ }
42969
43065
  async function metaprojectExplorer(projectRoot, request) {
42970
43066
  if ("version" in request) {
42971
43067
  return metaprojectExplorerV2(projectRoot, request, async (root, graphRequest) => {
42972
43068
  const observation = new ExplorerReadObservation(root);
42973
43069
  const graph = await loadExplorerGraph(root, graphRequest, observation);
42974
- return { graph, confirm: () => observation.confirm(), track: (target) => observation.track(target) };
43070
+ return { graph, freshness: () => explorerGraphFreshness(root, graph), confirm: () => observation.confirm(), track: (target) => observation.track(target) };
42975
43071
  });
42976
43072
  }
42977
- const model = await loadExplorerGraph(await realpath13(projectRoot), request);
42978
- const { base, nodes, edges, pages, graph, graphReason, hasSymbolLayer, hasWikiLayer, counts } = model;
43073
+ const root = await realpath13(projectRoot);
43074
+ const model = await loadExplorerGraph(root, request);
43075
+ const { base, nodes, edges, pages, hasSymbolLayer, hasWikiLayer, counts } = model;
42979
43076
  if (request.action === "catalog") {
42980
43077
  const boundedNodes = nodes.slice(0, CATALOG_NODES);
42981
43078
  const ids = new Set(boundedNodes.map((node) => node.id));
42982
43079
  const eligible = edges.filter((edge) => ids.has(edge.from) && ids.has(edge.to));
42983
- const catalog = { ...base, nodes: boundedNodes, edges: eligible.slice(0, CATALOG_EDGES), truncated: nodes.length > CATALOG_NODES || eligible.length > CATALOG_EDGES, graph, ...graphReason ? { graphReason } : {}, hasWikiLayer, hasSymbolLayer, counts };
43080
+ const catalog = { ...base, nodes: boundedNodes, edges: eligible.slice(0, CATALOG_EDGES), truncated: nodes.length > CATALOG_NODES || eligible.length > CATALOG_EDGES, ...await explorerGraphFreshness(root, model), hasWikiLayer, hasSymbolLayer, counts };
42984
43081
  return catalog;
42985
43082
  }
42986
43083
  if (request.action === "search") {
@@ -83781,17 +83878,21 @@ var init_desk_run_legacy = __esm(() => {
83781
83878
 
83782
83879
  // src/review/board-badges.ts
83783
83880
  function localBadge(runs, revision) {
83784
- runs = runs.filter((run) => run.decision?.action !== "archive" && run.decision?.action !== "delete");
83785
- const active = runs.filter((run) => run.source !== "existing" && runActive(run));
83881
+ runs = runs.filter((run) => run.source !== "existing" && run.decision?.action !== "archive" && run.decision?.action !== "delete");
83882
+ const active = runs.filter(runActive);
83786
83883
  const current = active.find((run) => sameRange(run, revision)) ?? active[0];
83787
- const latest = current ?? runs.find((run) => run.source !== "existing" && sameRange(run, revision));
83884
+ const latest = current ?? runs.find((run) => sameRange(run, revision));
83788
83885
  const same = !!latest && sameRange(latest, revision);
83789
83886
  const awaiting = latest?.awaitingAnswer ?? (latest?.pendingQuestions ? latest.pendingQuestions.length > 0 : !!latest?.pendingQuestion);
83790
83887
  const roster = same ? latest.reviewerProgress : undefined;
83888
+ const ready = runs.some((run) => runFinished(run) && !!run.result && sameRange(run.result.reviewed, revision));
83889
+ const stale = latest || ready ? undefined : runs.find((run) => runFinished(run) && !!run.result?.reviewed);
83890
+ const outdated = stale?.result?.reviewed ? { headSha: stale.result.reviewed.headSha, state: stale.state } : undefined;
83791
83891
  return {
83792
83892
  active: !!current,
83793
- ready: runs.some((run) => run.source !== "existing" && ["completed", "partial", "budget"].includes(run.state) && !!run.result && sameRange(run.result.reviewed, revision)),
83893
+ ready,
83794
83894
  ...latest ? { runState: same ? latest.state : "other-revision" } : {},
83895
+ ...outdated && { outdated },
83795
83896
  ...same && latest.state === "running" && latest.source === "manual" && awaiting && { awaitingAnswer: true },
83796
83897
  ...same && latest.publication === "pending" && sameRange(latest.result?.reviewed ?? null, revision) && { publicationPending: true },
83797
83898
  ...same && latest.state === "running" && latest.lastActivityAt && { lastActivityAt: latest.lastActivityAt },
@@ -83803,7 +83904,7 @@ function localBadge(runs, revision) {
83803
83904
  } } : {}
83804
83905
  };
83805
83906
  }
83806
- var runActive = (run) => run.state === "running" || run.state === "queued" || run.state === "cancelling", sameRange = (a, b) => a?.baseSha === b.baseSha && a.headSha === b.headSha;
83907
+ var runActive = (run) => run.state === "running" || run.state === "queued" || run.state === "cancelling", sameRange = (a, b) => a?.baseSha === b.baseSha && a.headSha === b.headSha, runFinished = (run) => run.state === "completed" || run.state === "partial" || run.state === "budget";
83807
83908
 
83808
83909
  // src/lib/hub-machine/errors.ts
83809
83910
  function machineFailure(cause, fallback = "machine-state-unavailable") {
@@ -84862,7 +84963,30 @@ Preview truncated. Full result: ` + path195.join(this.directory(run.id), "execut
84862
84963
  attachBadges(snapshot) {
84863
84964
  const tables = this.db.query("SELECT name FROM sqlite_schema WHERE type='table' AND name IN ('review_questions','reviewer_questions')").all();
84864
84965
  const pending = tables.map(({ name }) => `EXISTS(SELECT 1 FROM ${name} q WHERE q.run_id=r.id AND q.answer IS NULL)`).join(" OR ") || "0";
84966
+ const visible = (r) => `json_extract(${r}.details,'$.source') IN ('manual','scheduled')
84967
+ AND coalesce(json_extract(${r}.details,'$.decision.action'),'') NOT IN ('archive','delete')`;
84865
84968
  const query = this.db.query(`
84969
+ WITH scoped AS MATERIALIZED (
84970
+ SELECT w.key AS card, r.rowid AS seq, json_extract(r.details,'$.createdAt') AS created,
84971
+ r.state IN ('running','cancelling','queued') AS active, r.state IN ('completed','partial','budget') AS done,
84972
+ json_extract(r.details,'$.baseSha')=w.wb AND json_extract(r.details,'$.headSha')=w.wh AS requested,
84973
+ json_extract(r.details,'$.result.reviewed.baseSha') AS base,json_extract(r.details,'$.result.reviewed.headSha') AS head,
84974
+ w.wb, w.wh
84975
+ FROM (SELECT key,json_extract(value,'$.number') AS n,json_extract(value,'$.baseSha') AS wb,json_extract(value,'$.headSha') AS wh
84976
+ FROM json_each(?1)) w CROSS JOIN runs r
84977
+ WHERE r.repo=?2 AND r.viewer=?3 AND r.pr=w.n AND ${visible("r")}
84978
+ ), flagged AS (
84979
+ SELECT seq, created, card, coalesce(active OR requested,0) AS live, done, coalesce(base=wb AND head=wh,0) AS reviewed,
84980
+ done AND base IS NOT NULL AND head IS NOT NULL AS finished
84981
+ FROM scoped
84982
+ ), picked AS (
84983
+ SELECT seq, created, live OR reviewed AS kept, finished, live OR (done AND reviewed) AS supersedes, card
84984
+ FROM flagged
84985
+ ), ranked AS (
84986
+ SELECT seq, created, kept OR (finished AND NOT max(supersedes) OVER (PARTITION BY card) AND
84987
+ row_number() OVER (PARTITION BY card,finished ORDER BY created DESC,seq DESC)=1) AS wanted
84988
+ FROM picked
84989
+ )
84866
84990
  SELECT r.id, r.pr, CASE WHEN r.state='running' THEN ${pending} ELSE 0 END AS awaitingAnswer,
84867
84991
  CASE WHEN r.state='recoverable' THEN 'failed' ELSE r.state END AS state,
84868
84992
  json_extract(r.details,'$.source') AS source,
@@ -84880,23 +85004,20 @@ Preview truncated. Full result: ` + path195.join(this.directory(run.id), "execut
84880
85004
  FROM json_each(r.details,'$.reviewerProgress.sessions') s
84881
85005
  ) WHERE retry=1 AND outcome='completed'
84882
85006
  ) END) AS completed
84883
- FROM json_each(?) wanted CROSS JOIN runs r
84884
- WHERE r.repo=? AND r.viewer=? AND r.pr=json_extract(wanted.value,'$.number')
84885
- AND source IN ('manual','scheduled')
84886
- AND coalesce(json_extract(r.details,'$.decision.action'),'') NOT IN ('archive','delete') AND
84887
- (r.state IN ('running','cancelling','queued') OR
84888
- (baseSha=json_extract(wanted.value,'$.baseSha') AND headSha=json_extract(wanted.value,'$.headSha')) OR
84889
- (base=json_extract(wanted.value,'$.baseSha') AND head=json_extract(wanted.value,'$.headSha')))
84890
- ORDER BY json_extract(r.details,'$.createdAt') DESC,r.rowid DESC`);
85007
+ FROM ranked p JOIN runs r ON r.rowid=p.seq
85008
+ WHERE p.wanted
85009
+ ORDER BY p.created DESC,p.seq DESC`);
84891
85010
  for (let i = 0;i < snapshot.cards.length; i += 200) {
84892
85011
  const cards = snapshot.cards.slice(i, i + 200);
84893
85012
  const rows = query.all(JSON.stringify(cards.map(({ number, baseSha, headSha }) => ({ number, baseSha, headSha }))), snapshot.repositoryId, snapshot.viewer);
84894
85013
  const byPr = new Map;
85014
+ const cardByPr = new Map(cards.map((card) => [card.number, card]));
84895
85015
  for (const row of rows) {
84896
85016
  const runs = byPr.get(row.pr) ?? [];
84897
85017
  if (!runs.length)
84898
85018
  byPr.set(row.pr, runs);
84899
- const publication = row.base && row.head && this.publication(row.id, row.state, row.coverage);
85019
+ const card = cardByPr.get(row.pr);
85020
+ const publication = row.base && row.head && card?.baseSha === row.base && card.headSha === row.head && this.publication(row.id, row.state, row.coverage);
84900
85021
  runs.push({
84901
85022
  ...row,
84902
85023
  awaitingAnswer: !!row.awaitingAnswer,
@@ -371845,7 +371966,8 @@ function createHttpBotApi(options) {
371845
371966
  await call("answerCallbackQuery", body);
371846
371967
  },
371847
371968
  async getMe() {
371848
- return call("getMe", {});
371969
+ const { id, username } = await call("getMe", {});
371970
+ return username === undefined ? { id } : { id, username };
371849
371971
  },
371850
371972
  async getChat(params) {
371851
371973
  return call("getChat", { chat_id: params.chatId });
@@ -373996,7 +374118,7 @@ class UpdatePoller {
373996
374118
  try {
373997
374119
  updates = await this.api.getUpdates({
373998
374120
  ...confirm === undefined ? {} : { offset: confirm },
373999
- timeoutSec: this.timeoutSec,
374121
+ timeoutSec: this.resolveFirstPoll !== undefined && this.holdAfterFirstResponse !== undefined ? 0 : this.timeoutSec,
374000
374122
  signal
374001
374123
  });
374002
374124
  firstSuccess = this.resolveFirstPoll !== undefined;
@@ -376972,6 +377094,8 @@ class Pairing {
376972
377094
  bot;
376973
377095
  state = "waiting-for-user";
376974
377096
  code;
377097
+ forumCode;
377098
+ membership = { received: 0, last: "none" };
376975
377099
  expiresAt;
376976
377100
  ttlMs;
376977
377101
  earlyGroups = new Map;
@@ -376982,6 +377106,7 @@ class Pairing {
376982
377106
  problems = [];
376983
377107
  reason;
376984
377108
  candidate;
377109
+ candidateRequiresOperatorAdmin = false;
376985
377110
  poller;
376986
377111
  now;
376987
377112
  timers;
@@ -377047,6 +377172,8 @@ class Pairing {
377047
377172
  return {
377048
377173
  state: this.state,
377049
377174
  ...this.code === undefined ? {} : { code: this.code },
377175
+ ...this.forumCode === undefined ? {} : { forumCode: this.forumCode },
377176
+ ...this.options.requireConfirmation === true ? { membership: { ...this.membership } } : {},
377050
377177
  ...this.bot.username === undefined ? {} : { botUsername: this.bot.username },
377051
377178
  expiresAt: this.expiresAt,
377052
377179
  ...this.userId === undefined ? {} : { userId: this.userId },
@@ -377074,9 +377201,11 @@ class Pairing {
377074
377201
  if (this.state !== "waiting-for-confirmation" || this.userId === undefined)
377075
377202
  return;
377076
377203
  this.state = "waiting-for-group";
377204
+ this.forumCode = newPairingCode();
377077
377205
  this.expiresAt = this.now() + this.ttlMs;
377078
377206
  this.armExpiryTimer();
377079
377207
  confirmed = true;
377208
+ await this.replayGroupEvents();
377080
377209
  });
377081
377210
  return confirmed;
377082
377211
  }
@@ -377117,6 +377246,7 @@ class Pairing {
377117
377246
  this.state = state;
377118
377247
  if (FINAL.has(state)) {
377119
377248
  this.code = undefined;
377249
+ this.forumCode = undefined;
377120
377250
  if (this.expiryTimer !== undefined) {
377121
377251
  this.timers.clearTimeout(this.expiryTimer);
377122
377252
  this.expiryTimer = undefined;
@@ -377145,12 +377275,19 @@ class Pairing {
377145
377275
  this.expireIfDue();
377146
377276
  return;
377147
377277
  }
377278
+ if (update.my_chat_member !== undefined)
377279
+ this.membership.received += 1;
377148
377280
  if (this.state === "waiting-for-user") {
377149
377281
  if (this.options.requireConfirmation !== true)
377150
377282
  this.rememberGroupEvent(update);
377283
+ else if (update.my_chat_member !== undefined)
377284
+ this.membership.last = "before-claim";
377151
377285
  await this.takeCode(update);
377286
+ } else if (this.state === "waiting-for-confirmation") {
377287
+ this.deferGroupEvent(update);
377152
377288
  } else if (this.state === "waiting-for-group") {
377153
377289
  await this.takeGroup(update);
377290
+ await this.takeForumCommand(update);
377154
377291
  await this.takeMigration(update);
377155
377292
  }
377156
377293
  }
@@ -377185,6 +377322,9 @@ class Pairing {
377185
377322
  }).catch(() => {
377186
377323
  return;
377187
377324
  });
377325
+ await this.replayGroupEvents();
377326
+ }
377327
+ async replayGroupEvents() {
377188
377328
  const early = [...this.earlyGroups.values()];
377189
377329
  const earlyMoves = this.earlyMigrations;
377190
377330
  this.earlyGroups.clear();
@@ -377202,6 +377342,15 @@ class Pairing {
377202
377342
  await this.takeMigration(event);
377203
377343
  }
377204
377344
  }
377345
+ deferGroupEvent(update) {
377346
+ if (update.my_chat_member !== undefined) {
377347
+ const result = this.membershipResult(update.my_chat_member);
377348
+ this.membership.last = result === "inspecting" ? "deferred" : result;
377349
+ if (result !== "inspecting")
377350
+ return;
377351
+ }
377352
+ this.rememberGroupEvent(update);
377353
+ }
377205
377354
  rememberGroupEvent(update) {
377206
377355
  const message = update.message;
377207
377356
  if (message !== undefined && (typeof message.migrate_to_chat_id === "number" || typeof message.migrate_from_chat_id === "number")) {
@@ -377226,23 +377375,38 @@ class Pairing {
377226
377375
  }
377227
377376
  async takeGroup(update) {
377228
377377
  const change = update.my_chat_member;
377229
- if (change === undefined || change.from.id !== this.userId) {
377378
+ if (change === undefined)
377230
377379
  return;
377231
- }
377232
- const type = change.chat.type;
377233
- if (type !== "group" && type !== "supergroup") {
377234
- return;
377235
- }
377236
- const status = change.new_chat_member.status;
377237
- if (status !== "member" && status !== "administrator") {
377380
+ const result = this.membershipResult(change);
377381
+ this.membership.last = result;
377382
+ if (result !== "inspecting")
377238
377383
  return;
377239
- }
377240
377384
  this.candidate = change.chat.id;
377241
- if (change.chat.title !== undefined) {
377242
- this.chatTitle = change.chat.title;
377243
- }
377385
+ this.candidateRequiresOperatorAdmin = false;
377386
+ this.chatTitle = change.chat.title;
377244
377387
  await this.inspectGroup(change.chat.id);
377245
377388
  }
377389
+ membershipResult(change) {
377390
+ if (change.from.id !== this.userId)
377391
+ return "different-account";
377392
+ if (change.chat.type !== "group" && change.chat.type !== "supergroup")
377393
+ return "unsupported-chat";
377394
+ const role = change.new_chat_member.status;
377395
+ return role === "member" || role === "administrator" ? "inspecting" : "unsupported-role";
377396
+ }
377397
+ async takeForumCommand(update) {
377398
+ const message = update.message;
377399
+ if (this.state !== "waiting-for-group" || this.forumCode === undefined || message?.chat.type !== "supergroup" || message.from?.id !== this.userId || message.sender_chat !== undefined || message.forward_origin !== undefined || message.forward_date !== undefined || typeof message.text !== "string")
377400
+ return;
377401
+ const [command, code, extra] = message.text.trim().split(/\s+/);
377402
+ const addressed = this.bot.username && `/keryx_pair_forum@${this.bot.username.toLowerCase()}`;
377403
+ if (command?.toLowerCase() !== "/keryx_pair_forum" && command?.toLowerCase() !== addressed || code?.toUpperCase() !== this.forumCode || extra !== undefined)
377404
+ return;
377405
+ this.candidate = message.chat.id;
377406
+ this.candidateRequiresOperatorAdmin = true;
377407
+ this.chatTitle = undefined;
377408
+ await this.inspectGroup(message.chat.id);
377409
+ }
377246
377410
  async takeMigration(update) {
377247
377411
  const message = update.message;
377248
377412
  if (message === undefined || this.candidate === undefined || FINAL.has(this.state)) {
@@ -377279,6 +377443,12 @@ class Pairing {
377279
377443
  } else if (member.status === "administrator" && member.can_manage_topics !== true) {
377280
377444
  problems.push("Give the bot the Manage Topics right in the group's administrator settings.");
377281
377445
  }
377446
+ if (this.candidateRequiresOperatorAdmin && this.userId !== undefined && problems.length === 0) {
377447
+ const operator = await this.options.api.getChatMember({ chatId, userId: this.userId });
377448
+ if (operator.status !== "administrator" && operator.status !== "creator") {
377449
+ problems.push("The confirmed Telegram account must be an administrator of this forum.");
377450
+ }
377451
+ }
377282
377452
  } catch (error) {
377283
377453
  problems.push(`could not inspect the group: ${describe5(error)}`);
377284
377454
  }
@@ -377308,6 +377478,7 @@ var init_pairing = __esm(() => {
377308
377478
  class ChannelControl {
377309
377479
  options;
377310
377480
  fence;
377481
+ lastFailure;
377311
377482
  pending;
377312
377483
  constructor(options) {
377313
377484
  this.options = options;
@@ -377316,6 +377487,13 @@ class ChannelControl {
377316
377487
  pendingOperation() {
377317
377488
  return this.pending === undefined ? undefined : { operationId: this.pending.id, revision: this.pending.revision };
377318
377489
  }
377490
+ lastActivationFailure() {
377491
+ return this.lastFailure;
377492
+ }
377493
+ failActivation(reason) {
377494
+ this.lastFailure = { reason, at: Date.now() };
377495
+ return fail9(503, "activation-failed", reason);
377496
+ }
377319
377497
  async handle(request) {
377320
377498
  const body = await readJsonBody(request);
377321
377499
  if (!body.ok)
@@ -377458,22 +377636,26 @@ class ChannelControl {
377458
377636
  if (!sameBot && (!pairing.isReady() || snapshot.userId === undefined || snapshot.chatId === undefined) || token === undefined || api === undefined)
377459
377637
  return fail9(409, "pairing-incomplete", "Complete pairing before confirming.");
377460
377638
  this.pending.activating = true;
377461
- await pairing.stop();
377462
- const existing = loadChannelRecord(this.options.dir);
377463
- if (!existing.ok) {
377464
- this.clear(doc.operationId);
377465
- return fail9(503, "unavailable", existing.reason);
377466
- }
377467
- if (sameBot && (existing.value?.state !== "connected" || existing.value.bot?.id !== pairing.identity().id)) {
377639
+ try {
377640
+ await pairing.stop();
377641
+ const existing = loadChannelRecord(this.options.dir);
377642
+ if (!existing.ok)
377643
+ return this.failActivation(existing.reason);
377644
+ if (sameBot && (existing.value?.state !== "connected" || existing.value.bot?.id !== pairing.identity().id)) {
377645
+ this.lastFailure = { reason: "Channel identity changed.", at: Date.now() };
377646
+ return fail9(409, "conflict", this.lastFailure.reason);
377647
+ }
377648
+ const config = existing.value?.state === "connected" ? sameBot ? existing.value.config : { ...existing.value.config, chatId: snapshot.chatId, allowedUserIds: [snapshot.userId] } : { schemaVersion: REMOTE_CONFIG_SCHEMA_VERSION, chatId: snapshot.chatId, allowedUserIds: [snapshot.userId], orphanMs: DEFAULT_ORPHAN_MS, runTimeoutMs: DEFAULT_RUN_TIMEOUT_MS, permissionMode: DEFAULT_REMOTE_PERMISSION_MODE, approvalTimeoutMs: DEFAULT_APPROVAL_WAIT_MS };
377649
+ const result = await this.options.activate({ token, api, bot: pairing.identity(), config, expectedRevision: revision, stillOwned: () => this.fence.check(doc.operationId, revision).ok && this.pending?.pairing === pairing, stillActive: () => this.pending?.id === doc.operationId && this.pending?.pairing === pairing });
377650
+ if (!result.ok)
377651
+ return this.failActivation(result.reason);
377652
+ this.lastFailure = undefined;
377653
+ return ok4({ operationId: doc.operationId, revision: result.revision, state: "connected" });
377654
+ } catch {
377655
+ return this.failActivation("An unexpected local service error interrupted Telegram activation.");
377656
+ } finally {
377468
377657
  this.clear(doc.operationId);
377469
- return fail9(409, "conflict", "Channel identity changed.");
377470
377658
  }
377471
- const config = existing.value?.state === "connected" ? sameBot ? existing.value.config : { ...existing.value.config, chatId: snapshot.chatId, allowedUserIds: [snapshot.userId] } : { schemaVersion: REMOTE_CONFIG_SCHEMA_VERSION, chatId: snapshot.chatId, allowedUserIds: [snapshot.userId], orphanMs: DEFAULT_ORPHAN_MS, runTimeoutMs: DEFAULT_RUN_TIMEOUT_MS, permissionMode: DEFAULT_REMOTE_PERMISSION_MODE, approvalTimeoutMs: DEFAULT_APPROVAL_WAIT_MS };
377472
- const result = await this.options.activate({ token, api, bot: pairing.identity(), config, expectedRevision: revision, stillOwned: () => this.fence.check(doc.operationId, revision).ok && this.pending?.pairing === pairing, stillActive: () => this.pending?.id === doc.operationId && this.pending?.pairing === pairing });
377473
- this.clear(doc.operationId);
377474
- if (!result.ok)
377475
- return fail9(503, "activation-failed", result.reason);
377476
- return ok4({ operationId: doc.operationId, revision: result.revision, state: "connected" });
377477
377659
  }
377478
377660
  if (this.pending.sameBot)
377479
377661
  return ok4({ operationId: doc.operationId, revision, state: "same-bot-ready" });
@@ -377609,10 +377791,12 @@ class ChannelsController {
377609
377791
  if (record !== undefined && !record.ok)
377610
377792
  return fail9(503, "channel-record-invalid", record.reason);
377611
377793
  const pendingOperation = this.control?.pendingOperation();
377794
+ const lastActivationFailure = this.control?.lastActivationFailure();
377612
377795
  return ok4({
377613
377796
  machine: this.host.machine,
377614
377797
  ...record?.ok === true ? { capabilities: { desktopTelegram: 1 }, revision: record.value?.revision ?? null } : {},
377615
377798
  ...record !== undefined && pendingOperation !== undefined ? { pendingOperation } : {},
377799
+ ...lastActivationFailure === undefined ? {} : { lastActivationFailure },
377616
377800
  telegram: {
377617
377801
  state,
377618
377802
  ...reason === undefined ? {} : { reason },
package/dist/core.js CHANGED
@@ -14573,13 +14573,14 @@ var init_service = __esm(() => {
14573
14573
  });
14574
14574
 
14575
14575
  // src/integrations/metaproject-explorer-v2.ts
14576
- var CATALOG_METADATA_BYTES, SEARCH_ITEMS_BYTES;
14576
+ var CATALOG_METADATA_BYTES, SEARCH_ITEMS_BYTES, TREE_ITEMS_BYTES;
14577
14577
  var init_metaproject_explorer_v2 = __esm(() => {
14578
14578
  init_service();
14579
14579
  init_metaproject_explorer_contract();
14580
14580
  init_metaproject_projection();
14581
14581
  CATALOG_METADATA_BYTES = 128 * 1024;
14582
14582
  SEARCH_ITEMS_BYTES = 900 * 1024;
14583
+ TREE_ITEMS_BYTES = 900 * 1024;
14583
14584
  });
14584
14585
 
14585
14586
  // src/integrations/metaproject-explorer.ts
@@ -14847,13 +14847,14 @@ var init_service = __esm(() => {
14847
14847
  });
14848
14848
 
14849
14849
  // src/integrations/metaproject-explorer-v2.ts
14850
- var CATALOG_METADATA_BYTES, SEARCH_ITEMS_BYTES;
14850
+ var CATALOG_METADATA_BYTES, SEARCH_ITEMS_BYTES, TREE_ITEMS_BYTES;
14851
14851
  var init_metaproject_explorer_v2 = __esm(() => {
14852
14852
  init_service();
14853
14853
  init_metaproject_explorer_contract();
14854
14854
  init_metaproject_projection();
14855
14855
  CATALOG_METADATA_BYTES = 128 * 1024;
14856
14856
  SEARCH_ITEMS_BYTES = 900 * 1024;
14857
+ TREE_ITEMS_BYTES = 900 * 1024;
14857
14858
  });
14858
14859
 
14859
14860
  // src/integrations/metaproject-explorer.ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mrciphersmith/keryx",
3
- "version": "0.4.52",
3
+ "version": "0.4.54",
4
4
  "description": "Version-controlled project context for AI coding agents: code graph, architecture wiki, project memory, relevant tests, quality signals, and task flows.",
5
5
  "private": false,
6
6
  "publishConfig": {