@useorgx/wizard 0.1.39 → 0.1.41

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
@@ -7765,6 +7765,72 @@ function hash2(value, length = 16) {
7765
7765
  function clamp(value, min = 0, max = 1) {
7766
7766
  return Math.max(min, Math.min(max, value));
7767
7767
  }
7768
+ function compactText(value) {
7769
+ return value.replace(/\s+/g, " ").trim();
7770
+ }
7771
+ function stripSourceSyntax(value) {
7772
+ return compactText(
7773
+ value.replace(/[`*_#>]/g, "").replace(/\b[A-Z]+:\s*\[[^\]]+\]/g, "").replace(/\[[^\]]*(?:brief|placeholder|todo|impact|summary)[^\]]*\]/gi, "").replace(/\b(?:Impact|Summary|Result|TODO)\s*:\s*$/i, "")
7774
+ );
7775
+ }
7776
+ function isPlaceholderIntent(value) {
7777
+ const text2 = value.trim();
7778
+ return /\[(?:brief|placeholder|todo|impact|summary)[^\]]*\]/i.test(text2) || /^(?:impact|summary|result|todo)\s*:\s*(?:$|\[[^\]]+\])/i.test(text2);
7779
+ }
7780
+ function isCodeFragmentIntent(value) {
7781
+ const text2 = value.trim();
7782
+ if (/^[{[\]}(),:;'"`|\\/-]+/.test(text2)) return true;
7783
+ if (/[{};]/.test(text2) && text2.length < 180) return true;
7784
+ if (/^[a-zA-Z_$][\w$]*\s*[:,]/.test(text2) && /[,{}]/.test(text2)) return true;
7785
+ if (/^(?:true|false|null|undefined|\d+)$/.test(text2)) return true;
7786
+ return false;
7787
+ }
7788
+ function isLowQualityIntent(value) {
7789
+ const text2 = value.trim();
7790
+ return text2.length < 18 || isPlaceholderIntent(text2) || isCodeFragmentIntent(text2) || /^[\W_]+$/.test(text2);
7791
+ }
7792
+ function cleanLoopIntent(value, fallback = "Unclassified AI work loop") {
7793
+ const cleaned = stripSourceSyntax(value).replace(/\bmcporgx\b/gi, "OrgX MCP").replace(/\bmcp__orgx__([a-z0-9_]+)/gi, "OrgX MCP $1").replace(/_/g, " ");
7794
+ if (!cleaned || isLowQualityIntent(cleaned)) return fallback;
7795
+ return cleaned.slice(0, 160);
7796
+ }
7797
+ function loopTopicKey(loop) {
7798
+ const intent = cleanLoopIntent(loop.origin.intent, "");
7799
+ const text2 = `${intent} ${loop.path.tools_used.join(" ")} ${loop.bottleneck.class ?? ""}`.toLowerCase();
7800
+ const topicRules = [
7801
+ [/\blist entities\b|\blist_entities\b|\bschema validation\b|\bzod\b/, "orgx-list-entities-schema"],
7802
+ [/\bscaffold\b|\binitiative\b|\boperation qa loop\b/, "scaffold-initiative-loop"],
7803
+ [/\bship batch\b|\bship_batch\b|\bartifacturl\b|\bexternalurl\b/, "ship-batch-artifact-contract"],
7804
+ [/\bruntime hook\b|\bwriteback\b|\brecord outcome\b|\bsubmit learning\b/, "runtime-writeback"],
7805
+ [/\b64\b.*\btools\b|\bmcp tools\b|\btool catalog\b/, "mcp-tool-catalog"],
7806
+ [/\banthropic\b|\bapi credits\b|\bbilling\b|\bquota\b/, "provider-auth-billing"],
7807
+ [/\bgithub\b|\bcommit\b|\bpr\b|\bproof\b/, "github-proof"],
7808
+ [/\bpublic profile\b|\bwork graph\b|\bmirror\b|\bclaim\b/, "work-graph-profile"],
7809
+ [/\bcursor\b/, "cursor-client"],
7810
+ [/\bcodex\b/, "codex-client"],
7811
+ [/\bclaude\b/, "claude-code-client"]
7812
+ ];
7813
+ for (const [pattern, topic] of topicRules) {
7814
+ if (pattern.test(text2)) return topic;
7815
+ }
7816
+ if (!intent) return `unclassified:${hash2(loop.loop_id, 10)}`;
7817
+ return `topic:${hash2(intent.toLowerCase(), 10)}`;
7818
+ }
7819
+ function bestFamilyCentroid(group) {
7820
+ const candidates = group.map((loop) => cleanLoopIntent(loop.origin.intent, "")).filter(Boolean).map((intent) => {
7821
+ let score = 0;
7822
+ if (!isLowQualityIntent(intent)) score += 20;
7823
+ if (/\borgx|mcp|codex|claude|cursor|github|slack|runtime|hook|scaffold|profile|wizard/i.test(intent)) score += 8;
7824
+ if (intent.length >= 32 && intent.length <= 120) score += 4;
7825
+ if (/[{}\[\];]/.test(intent)) score -= 20;
7826
+ if (/^(?:impact|summary|result)\s*:/i.test(intent)) score -= 16;
7827
+ return { intent, score };
7828
+ }).sort((left, right) => right.score - left.score);
7829
+ return candidates[0]?.intent || "A repeated AI work loop needs durable writeback";
7830
+ }
7831
+ function articleFor(value) {
7832
+ return /^[aeiou]/i.test(value.trim()) ? "an" : "a";
7833
+ }
7768
7834
  function countBy(values) {
7769
7835
  const counts = /* @__PURE__ */ new Map();
7770
7836
  for (const value of values) counts.set(value, (counts.get(value) ?? 0) + 1);
@@ -7958,6 +8024,11 @@ function buildWorkLoops(input) {
7958
8024
  const matchedFindings = trail.evidence_refs.map((ref) => findingsByRef.get(ref)).filter((finding) => Boolean(finding));
7959
8025
  const firstFinding = matchedFindings[0];
7960
8026
  const eventIds = matchedEvents.map((event) => event.event_id);
8027
+ const intent = cleanLoopIntent(
8028
+ trail.title,
8029
+ `${trail.subject_entity_type.replace(/_/g, " ")} work loop needs review`
8030
+ );
8031
+ const intentQualityOk = !isLowQualityIntent(trail.title) && !isLowQualityIntent(intent);
7961
8032
  const text2 = [
7962
8033
  trail.title,
7963
8034
  trail.summary,
@@ -7974,7 +8045,7 @@ function buildWorkLoops(input) {
7974
8045
  origin: {
7975
8046
  event_id: eventIds[0] ?? `evt_missing_${index}`,
7976
8047
  timestamp: matchedEvents[0]?.timestamp ?? trail.created_at,
7977
- intent: trail.title.slice(0, 160),
8048
+ intent,
7978
8049
  intent_class: firstFinding ? intentClassForFinding(firstFinding) : "unclear"
7979
8050
  },
7980
8051
  path: {
@@ -8001,7 +8072,7 @@ function buildWorkLoops(input) {
8001
8072
  },
8002
8073
  confidence,
8003
8074
  survived_critic: confidence >= 0.6 && eventIds.length > 0,
8004
- public_surface: confidence >= 0.6 && eventIds.length > 0
8075
+ public_surface: confidence >= 0.6 && eventIds.length > 0 && intentQualityOk
8005
8076
  };
8006
8077
  });
8007
8078
  }
@@ -8009,7 +8080,8 @@ function loopFamilyKey(loop) {
8009
8080
  return [
8010
8081
  loop.origin.intent_class,
8011
8082
  loop.terminal.state,
8012
- loop.bottleneck.class ?? "none"
8083
+ loop.bottleneck.class ?? "none",
8084
+ loopTopicKey(loop)
8013
8085
  ].join(":");
8014
8086
  }
8015
8087
  function shapeForFamily(loops) {
@@ -8057,7 +8129,9 @@ function buildLoopFamilies(loops, events, impact) {
8057
8129
  const familyId = `family_${hash2(key, 16)}`;
8058
8130
  const timestamps = group.map((loop) => Date.parse(loop.origin.timestamp)).filter(Number.isFinite);
8059
8131
  const spanDays = timestamps.length > 1 ? Math.max(1, Math.ceil((Math.max(...timestamps) - Math.min(...timestamps)) / 864e5)) : 0;
8060
- const divergenceScore = group.length >= 3 ? 0.32 : 0.5;
8132
+ const publicLoopCount = group.filter((loop) => loop.public_surface).length;
8133
+ const semanticCentroid = bestFamilyCentroid(group);
8134
+ const divergenceScore = group.length >= 3 && publicLoopCount >= 3 ? 0.32 : 0.5;
8061
8135
  return {
8062
8136
  family_id: familyId,
8063
8137
  shared_intent_class: group[0]?.origin.intent_class ?? "unclear",
@@ -8067,7 +8141,7 @@ function buildLoopFamilies(loops, events, impact) {
8067
8141
  appearances: group.length,
8068
8142
  span_days: spanDays,
8069
8143
  shape: shapeForFamily(group),
8070
- semantic_centroid: group[0]?.origin.intent ?? "Work loop family",
8144
+ semantic_centroid: semanticCentroid,
8071
8145
  divergence_score: divergenceScore,
8072
8146
  cross_source_confluence: sourceIds.size >= 2,
8073
8147
  orgx_repair: repairForFamily(group, impact),
@@ -8076,8 +8150,8 @@ function buildLoopFamilies(loops, events, impact) {
8076
8150
  "The apparent recurrence may be a planned multi-step implementation rather than unresolved work."
8077
8151
  ],
8078
8152
  alternative_rejected_because: group.length >= 3 ? ["Shared intent class, terminal state, and bottleneck class recur across multiple evidence events."] : ["Kept as a non-public single/weak family until more chronology exists."],
8079
- survived_critic: group.length >= 3 && divergenceScore < 0.5,
8080
- public_surface: group.length >= 3 && divergenceScore < 0.5
8153
+ survived_critic: group.length >= 3 && publicLoopCount >= 3 && divergenceScore < 0.5,
8154
+ public_surface: group.length >= 3 && publicLoopCount >= 3 && divergenceScore < 0.5
8081
8155
  };
8082
8156
  });
8083
8157
  const familyMap = new Map(families.map((family) => [family.family_id, family]));
@@ -8550,13 +8624,15 @@ function buildRepairPlan(input) {
8550
8624
  return actions.slice(0, 3);
8551
8625
  }
8552
8626
  function buildMirror(input) {
8553
- const topFamily = input.families.find((family) => family.public_surface) ?? input.families[0];
8554
- const topLoop = input.loops[0];
8627
+ const topFamily = input.families.find((family) => family.public_surface);
8628
+ const topLoop = input.loops.find((loop) => loop.public_surface) ?? input.loops[0];
8555
8629
  const sourceCount = input.corpus.sources.filter((source) => source.status === "connected" || source.status === "partial").length;
8556
8630
  const dropped = input.loops.filter((loop) => !loop.survived_critic).length;
8631
+ const terminal = topFamily?.shared_terminal_state ?? "ongoing";
8632
+ const terminalPhrase = `${articleFor(terminal)} ${terminal}`;
8557
8633
  const text2 = [
8558
8634
  `You have AI-assisted work spread across ${sourceCount} connected or partial source${sourceCount === 1 ? "" : "s"}, but the execution record is still incomplete.`,
8559
- topFamily ? `The clearest repeated loop is "${topFamily.semantic_centroid}", with ${topFamily.appearances} appearance${topFamily.appearances === 1 ? "" : "s"} and a ${topFamily.shared_terminal_state} terminal state.` : topLoop ? `The clearest work loop is "${topLoop.origin.intent}", but it still needs more chronology before OrgX should call it recurring.` : "The corpus did not produce a verified work loop yet.",
8635
+ topFamily ? `The clearest repeated loop is ${topFamily.semantic_centroid}: ${topFamily.appearances} appearance${topFamily.appearances === 1 ? "" : "s"} with ${terminalPhrase} state.` : topLoop ? `The clearest work loop is "${topLoop.origin.intent}", but it still needs more chronology before OrgX should call it recurring.` : "The corpus did not produce a verified work loop yet.",
8560
8636
  input.counterfactuals[0] ? `OrgX can point to the exact event where it would have called ${input.counterfactuals[0].orgx_capability.tool} and what entity it would have created.` : "Counterfactual repair is waiting on a higher-confidence loop with resolved citations.",
8561
8637
  `The current estimate is ${input.impact.time_saved_hours_per_week} recoverable hours/week, grounded in ${input.impact.basis[0] ?? "resolved work-loop evidence"}.`,
8562
8638
  dropped > 0 ? `${dropped} weak signal${dropped === 1 ? " was" : "s were"} kept out of the public readout because the citations or critic score did not clear the bar.` : "Every surfaced loop cleared citation verification and the critic floor."
@@ -11316,8 +11392,46 @@ function renderWorkGraphMarkdown(report) {
11316
11392
  }
11317
11393
 
11318
11394
  // src/lib/work-graph-publish.ts
11395
+ import { createHash as createHash7, randomUUID as randomUUID2 } from "crypto";
11319
11396
  import { gzipSync } from "zlib";
11320
- var WORK_GRAPH_REPORT_GZIP_THRESHOLD_BYTES = 96e3;
11397
+ var WORK_GRAPH_REPORT_GZIP_THRESHOLD_BYTES = 4e6;
11398
+ var WORK_GRAPH_REPORT_CHUNK_UPLOAD_THRESHOLD_BYTES = 5e5;
11399
+ var WORK_GRAPH_REPORT_CHUNK_CHARS = 3e4;
11400
+ function hashText(value) {
11401
+ return createHash7("sha256").update(value).digest("hex");
11402
+ }
11403
+ function buildWorkGraphReportPostPayload(report, options = {}) {
11404
+ return {
11405
+ report,
11406
+ ...options.workspaceId ? { workspace_id: options.workspaceId } : {},
11407
+ ...options.initiativeId ? { initiative_id: options.initiativeId } : {},
11408
+ ...options.entityType ? { entity_type: options.entityType } : {},
11409
+ ...options.entityId ? { entity_id: options.entityId } : {},
11410
+ ...options.artifactUrl ? { artifact_url: options.artifactUrl } : {},
11411
+ attach_artifact: Boolean(options.attachArtifact),
11412
+ public_share: Boolean(options.publicShare)
11413
+ };
11414
+ }
11415
+ function createWorkGraphReportUploadChunks(payload, options = {}) {
11416
+ const chunkChars = options.chunkChars ?? WORK_GRAPH_REPORT_CHUNK_CHARS;
11417
+ const json = JSON.stringify(payload);
11418
+ const chunks = [];
11419
+ for (let offset = 0; offset < json.length; offset += chunkChars) {
11420
+ const chunkText = json.slice(offset, offset + chunkChars);
11421
+ chunks.push({
11422
+ chunkIndex: chunks.length,
11423
+ chunkText,
11424
+ chunkSha256: hashText(chunkText)
11425
+ });
11426
+ }
11427
+ return {
11428
+ uploadId: options.uploadId ?? `wgrup_${randomUUID2()}`,
11429
+ reportSha256: hashText(json),
11430
+ totalBytes: Buffer.byteLength(json),
11431
+ json,
11432
+ chunks
11433
+ };
11434
+ }
11321
11435
  function encodeWorkGraphReportPostBody(payload, thresholdBytes = WORK_GRAPH_REPORT_GZIP_THRESHOLD_BYTES) {
11322
11436
  const json = JSON.stringify(payload);
11323
11437
  const byteLength = Buffer.byteLength(json);
@@ -11348,22 +11462,106 @@ async function parseResponse(response) {
11348
11462
  return text2;
11349
11463
  }
11350
11464
  }
11465
+ async function postWorkGraphReportJson({
11466
+ auth,
11467
+ body,
11468
+ signal,
11469
+ url
11470
+ }) {
11471
+ const requestInit = {
11472
+ method: "POST",
11473
+ headers: {
11474
+ Authorization: `Bearer ${auth.apiKey}`,
11475
+ "Content-Type": "application/json"
11476
+ },
11477
+ body: JSON.stringify(body)
11478
+ };
11479
+ if (signal) requestInit.signal = signal;
11480
+ return fetch(url, requestInit);
11481
+ }
11482
+ async function publishWorkGraphReportInChunks({
11483
+ auth,
11484
+ payload,
11485
+ signal,
11486
+ url
11487
+ }) {
11488
+ const upload = createWorkGraphReportUploadChunks(payload);
11489
+ const uploadSignal = signal ?? AbortSignal.timeout(6e4);
11490
+ const startResponse = await postWorkGraphReportJson({
11491
+ auth,
11492
+ body: {
11493
+ action: "start",
11494
+ upload_id: upload.uploadId,
11495
+ chunk_count: upload.chunks.length,
11496
+ total_bytes: upload.totalBytes,
11497
+ report_sha256: upload.reportSha256
11498
+ },
11499
+ signal: uploadSignal,
11500
+ url
11501
+ });
11502
+ if (!startResponse.ok) {
11503
+ return {
11504
+ ok: false,
11505
+ status: startResponse.status,
11506
+ url,
11507
+ data: await parseResponse(startResponse)
11508
+ };
11509
+ }
11510
+ for (const chunk of upload.chunks) {
11511
+ const chunkResponse = await postWorkGraphReportJson({
11512
+ auth,
11513
+ body: {
11514
+ action: "chunk",
11515
+ upload_id: upload.uploadId,
11516
+ chunk_index: chunk.chunkIndex,
11517
+ chunk_text: chunk.chunkText,
11518
+ chunk_sha256: chunk.chunkSha256
11519
+ },
11520
+ signal: uploadSignal,
11521
+ url
11522
+ });
11523
+ if (!chunkResponse.ok) {
11524
+ return {
11525
+ ok: false,
11526
+ status: chunkResponse.status,
11527
+ url,
11528
+ data: await parseResponse(chunkResponse)
11529
+ };
11530
+ }
11531
+ }
11532
+ const completeResponse = await postWorkGraphReportJson({
11533
+ auth,
11534
+ body: {
11535
+ action: "complete",
11536
+ upload_id: upload.uploadId
11537
+ },
11538
+ signal: uploadSignal,
11539
+ url
11540
+ });
11541
+ return {
11542
+ ok: completeResponse.ok,
11543
+ status: completeResponse.status,
11544
+ url,
11545
+ data: await parseResponse(completeResponse)
11546
+ };
11547
+ }
11351
11548
  async function publishWorkGraphReport(report, options = {}) {
11352
11549
  const auth = await resolveOrgxAuth();
11353
11550
  if (!auth) {
11354
11551
  throw new Error("OrgX auth is required to publish a Work Graph. Run `orgx-wizard auth login` or set ORGX_API_KEY.");
11355
11552
  }
11356
11553
  const url = buildOrgxApiUrl("/client/work-graph/reports", auth.baseUrl);
11357
- const encoded = encodeWorkGraphReportPostBody({
11358
- report,
11359
- ...options.workspaceId ? { workspace_id: options.workspaceId } : {},
11360
- ...options.initiativeId ? { initiative_id: options.initiativeId } : {},
11361
- ...options.entityType ? { entity_type: options.entityType } : {},
11362
- ...options.entityId ? { entity_id: options.entityId } : {},
11363
- ...options.artifactUrl ? { artifact_url: options.artifactUrl } : {},
11364
- attach_artifact: Boolean(options.attachArtifact),
11365
- public_share: Boolean(options.publicShare)
11366
- });
11554
+ const payload = buildWorkGraphReportPostPayload(report, options);
11555
+ const payloadBytes = Buffer.byteLength(JSON.stringify(payload));
11556
+ if (payloadBytes >= WORK_GRAPH_REPORT_CHUNK_UPLOAD_THRESHOLD_BYTES) {
11557
+ return publishWorkGraphReportInChunks({
11558
+ auth,
11559
+ payload,
11560
+ url,
11561
+ ...options.signal ? { signal: options.signal } : {}
11562
+ });
11563
+ }
11564
+ const encoded = encodeWorkGraphReportPostBody(payload);
11367
11565
  const response = await fetch(url, {
11368
11566
  method: "POST",
11369
11567
  headers: {
@@ -11407,7 +11605,7 @@ async function publishWorkGraphEvents(fingerprint, patch, options = {}) {
11407
11605
  }
11408
11606
 
11409
11607
  // src/lib/work-graph-hook-events.ts
11410
- import { createHash as createHash7 } from "crypto";
11608
+ import { createHash as createHash8 } from "crypto";
11411
11609
  import { existsSync as existsSync7, readFileSync as readFileSync5 } from "fs";
11412
11610
  var SOURCE_CLIENTS = [
11413
11611
  "codex",
@@ -11442,7 +11640,7 @@ function asStringArray(value) {
11442
11640
  return value.filter((item) => typeof item === "string" && item.trim().length > 0);
11443
11641
  }
11444
11642
  function stableHash(value) {
11445
- return createHash7("sha256").update(value).digest("hex").slice(0, 20);
11643
+ return createHash8("sha256").update(value).digest("hex").slice(0, 20);
11446
11644
  }
11447
11645
  function normalizeSourceClient2(value) {
11448
11646
  const raw = asString2(value)?.toLowerCase();
@@ -13496,7 +13694,7 @@ function printDoctorReport(report, assessment) {
13496
13694
  async function main() {
13497
13695
  const program = new Command();
13498
13696
  program.name("orgx-wizard").description("Add OrgX MCP configs, skills/rules, and companion plugins to your local AI tools.").showHelpAfterError();
13499
- const pkgVersion = true ? "0.1.39" : void 0;
13697
+ const pkgVersion = true ? "0.1.41" : void 0;
13500
13698
  program.version(pkgVersion ?? "unknown", "-V, --version");
13501
13699
  program.hook("preAction", (_thisCommand, actionCommand) => {
13502
13700
  if (Boolean(actionCommand.optsWithGlobals().json)) return;