@wowok/agent-mcp 2.3.14 → 2.3.18

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 (189) hide show
  1. package/dist/config/index.d.ts +1 -0
  2. package/dist/config/index.js +1 -0
  3. package/dist/config/runtime.d.ts +26 -0
  4. package/dist/config/runtime.js +217 -0
  5. package/dist/customer/index.d.ts +9 -0
  6. package/dist/customer/index.js +9 -0
  7. package/dist/customer/industry-risks.d.ts +40 -0
  8. package/dist/customer/industry-risks.js +438 -0
  9. package/dist/customer/info-puzzle.d.ts +102 -0
  10. package/dist/customer/info-puzzle.js +312 -0
  11. package/dist/customer/order-monitor.d.ts +75 -0
  12. package/dist/customer/order-monitor.js +327 -0
  13. package/dist/customer/order-strategy.d.ts +36 -0
  14. package/dist/customer/order-strategy.js +373 -0
  15. package/dist/customer/post-purchase.d.ts +42 -0
  16. package/dist/customer/post-purchase.js +350 -0
  17. package/dist/customer/reminder-system.d.ts +42 -0
  18. package/dist/customer/reminder-system.js +295 -0
  19. package/dist/customer/risk-assessment.d.ts +8 -0
  20. package/dist/customer/risk-assessment.js +337 -0
  21. package/dist/customer/types.d.ts +193 -0
  22. package/dist/customer/types.js +13 -0
  23. package/dist/customer/user-preferences.d.ts +70 -0
  24. package/dist/customer/user-preferences.js +460 -0
  25. package/dist/experience/experience-reuse.d.ts +10 -0
  26. package/dist/experience/experience-reuse.js +103 -0
  27. package/dist/experience/index.d.ts +6 -0
  28. package/dist/experience/index.js +5 -0
  29. package/dist/experience/intent-distill.d.ts +3 -0
  30. package/dist/experience/intent-distill.js +83 -0
  31. package/dist/experience/realtime-feedback.d.ts +5 -0
  32. package/dist/experience/realtime-feedback.js +94 -0
  33. package/dist/experience/types.d.ts +50 -0
  34. package/dist/experience/types.js +1 -0
  35. package/dist/experience/user-profile.d.ts +25 -0
  36. package/dist/experience/user-profile.js +171 -0
  37. package/dist/index.js +842 -371
  38. package/dist/knowledge/acquisition-flywheel.d.ts +53 -0
  39. package/dist/knowledge/acquisition-flywheel.js +192 -0
  40. package/dist/knowledge/arbitration-trust.d.ts +24 -0
  41. package/dist/knowledge/arbitration-trust.js +117 -0
  42. package/dist/knowledge/audit-rules.d.ts +28 -0
  43. package/dist/knowledge/audit-rules.js +141 -0
  44. package/dist/knowledge/demand-matching.d.ts +29 -0
  45. package/dist/knowledge/demand-matching.js +132 -0
  46. package/dist/knowledge/dynamic-pricing.d.ts +31 -0
  47. package/dist/knowledge/dynamic-pricing.js +87 -0
  48. package/dist/knowledge/flywheel-loop.d.ts +87 -0
  49. package/dist/knowledge/flywheel-loop.js +378 -0
  50. package/dist/knowledge/glossary.d.ts +18 -0
  51. package/dist/knowledge/glossary.js +209 -0
  52. package/dist/knowledge/guard-ledger.d.ts +19 -0
  53. package/dist/knowledge/guard-ledger.js +219 -0
  54. package/dist/knowledge/guard-puzzle.d.ts +93 -0
  55. package/dist/knowledge/guard-puzzle.js +278 -0
  56. package/dist/knowledge/guard-risk.d.ts +60 -0
  57. package/dist/knowledge/guard-risk.js +474 -0
  58. package/dist/knowledge/guard-translation.d.ts +46 -0
  59. package/dist/knowledge/guard-translation.js +487 -0
  60. package/dist/knowledge/index.d.ts +77 -0
  61. package/dist/knowledge/index.js +79 -0
  62. package/dist/knowledge/industry-evolution.d.ts +82 -0
  63. package/dist/knowledge/industry-evolution.js +323 -0
  64. package/dist/knowledge/industry-generalizer.d.ts +17 -0
  65. package/dist/knowledge/industry-generalizer.js +381 -0
  66. package/dist/knowledge/industry-registry.d.ts +48 -0
  67. package/dist/knowledge/industry-registry.js +187 -0
  68. package/dist/knowledge/intent-metrics.d.ts +42 -0
  69. package/dist/knowledge/intent-metrics.js +566 -0
  70. package/dist/knowledge/process-model.d.ts +24 -0
  71. package/dist/knowledge/process-model.js +160 -0
  72. package/dist/knowledge/reputation-rules.d.ts +42 -0
  73. package/dist/knowledge/reputation-rules.js +99 -0
  74. package/dist/knowledge/reward-templates.d.ts +25 -0
  75. package/dist/knowledge/reward-templates.js +125 -0
  76. package/dist/knowledge/safety-rules.d.ts +36 -0
  77. package/dist/knowledge/safety-rules.js +232 -0
  78. package/dist/knowledge/tool-constraints.d.ts +30 -0
  79. package/dist/knowledge/tool-constraints.js +175 -0
  80. package/dist/knowledge/trust-metrics.d.ts +37 -0
  81. package/dist/knowledge/trust-metrics.js +138 -0
  82. package/dist/loop-engineering/diagnose.d.ts +3 -2
  83. package/dist/loop-engineering/diagnose.js +94 -0
  84. package/dist/loop-engineering/improve.d.ts +1 -1
  85. package/dist/loop-engineering/improve.js +52 -1
  86. package/dist/project/graph.d.ts +71 -0
  87. package/dist/project/graph.js +314 -0
  88. package/dist/project/index.d.ts +62 -0
  89. package/dist/project/index.js +167 -0
  90. package/dist/project/namespace.d.ts +62 -0
  91. package/dist/project/namespace.js +181 -0
  92. package/dist/project/query.d.ts +40 -0
  93. package/dist/project/query.js +110 -0
  94. package/dist/safety/confirm-gate.d.ts +17 -0
  95. package/dist/safety/confirm-gate.js +88 -0
  96. package/dist/safety/index.d.ts +3 -0
  97. package/dist/safety/index.js +3 -0
  98. package/dist/safety/preview.d.ts +2 -0
  99. package/dist/safety/preview.js +36 -0
  100. package/dist/schema/call/allocation.d.ts +39 -14
  101. package/dist/schema/call/arbitration.d.ts +187 -162
  102. package/dist/schema/call/base.d.ts +1971 -87
  103. package/dist/schema/call/base.js +135 -3
  104. package/dist/schema/call/bridge-handler.js +15 -2
  105. package/dist/schema/call/bridge.d.ts +1478 -53
  106. package/dist/schema/call/bridge.js +50 -2
  107. package/dist/schema/call/contact.d.ts +25 -0
  108. package/dist/schema/call/demand.d.ts +79 -54
  109. package/dist/schema/call/guard.d.ts +125 -50
  110. package/dist/schema/call/handler.d.ts +3 -0
  111. package/dist/schema/call/handler.js +60 -14
  112. package/dist/schema/call/machine.d.ts +988 -938
  113. package/dist/schema/call/order.d.ts +25 -0
  114. package/dist/schema/call/payment.d.ts +25 -0
  115. package/dist/schema/call/permission.d.ts +244 -219
  116. package/dist/schema/call/personal.d.ts +25 -0
  117. package/dist/schema/call/progress.d.ts +25 -0
  118. package/dist/schema/call/proof.d.ts +62 -12
  119. package/dist/schema/call/proof.js +3 -3
  120. package/dist/schema/call/repository.d.ts +101 -76
  121. package/dist/schema/call/reward.d.ts +55 -30
  122. package/dist/schema/call/semantic.d.ts +10 -2
  123. package/dist/schema/call/semantic.js +616 -11
  124. package/dist/schema/call/service.d.ts +442 -417
  125. package/dist/schema/call/treasury.d.ts +25 -0
  126. package/dist/schema/common/index.js +3 -3
  127. package/dist/schema/config/index.d.ts +18 -0
  128. package/dist/schema/config/index.js +17 -0
  129. package/dist/schema/index.d.ts +6 -0
  130. package/dist/schema/index.js +5 -0
  131. package/dist/schema/local/index.d.ts +237 -81
  132. package/dist/schema/local/index.js +42 -6
  133. package/dist/schema/messenger/index.d.ts +1018 -79
  134. package/dist/schema/messenger/index.js +26 -17
  135. package/dist/schema/operations.d.ts +3192 -1746
  136. package/dist/schema/operations.js +93 -98
  137. package/dist/schema/project/index.d.ts +21 -0
  138. package/dist/schema/project/index.js +32 -0
  139. package/dist/schema/query/index.d.ts +2762 -1856
  140. package/dist/schema/query/index.js +38 -35
  141. package/dist/schema/schema-query/index.d.ts +33 -0
  142. package/dist/schema/schema-query/index.js +36 -0
  143. package/dist/schema/schema-version.d.ts +25 -0
  144. package/dist/schema/schema-version.js +76 -0
  145. package/dist/schema/trust/index.d.ts +407 -0
  146. package/dist/schema/trust/index.js +113 -0
  147. package/dist/schemas/account_operation.output.json +25 -16
  148. package/dist/schemas/account_operation.schema.json +1 -1
  149. package/dist/schemas/bridge_operation.output.json +744 -0
  150. package/dist/schemas/bridge_operation.schema.json +82 -8
  151. package/dist/schemas/config_operation.output.json +18 -0
  152. package/dist/schemas/config_operation.schema.json +34 -0
  153. package/dist/schemas/guard-node-schema.json +82 -0
  154. package/dist/schemas/guard2file.schema.json +23 -0
  155. package/dist/schemas/index.json +19 -1
  156. package/dist/schemas/local_info_operation.output.json +23 -0
  157. package/dist/schemas/local_info_operation.schema.json +1 -1
  158. package/dist/schemas/local_mark_operation.output.json +24 -1
  159. package/dist/schemas/local_mark_operation.schema.json +4 -4
  160. package/dist/schemas/machineNode2file.schema.json +23 -0
  161. package/dist/schemas/messenger_operation.output.json +752 -0
  162. package/dist/schemas/onchain_events.output.json +718 -0
  163. package/dist/schemas/onchain_operations.output.json +627 -18
  164. package/dist/schemas/onchain_operations.schema.json +115 -39
  165. package/dist/schemas/onchain_operations_allocation.schema.json +23 -0
  166. package/dist/schemas/onchain_operations_arbitration.schema.json +23 -0
  167. package/dist/schemas/onchain_operations_contact.schema.json +23 -0
  168. package/dist/schemas/onchain_operations_demand.schema.json +23 -0
  169. package/dist/schemas/onchain_operations_gen_passport.schema.json +46 -0
  170. package/dist/schemas/onchain_operations_guard.schema.json +26 -16
  171. package/dist/schemas/onchain_operations_machine.schema.json +89 -23
  172. package/dist/schemas/onchain_operations_order.schema.json +23 -0
  173. package/dist/schemas/onchain_operations_payment.schema.json +23 -0
  174. package/dist/schemas/onchain_operations_permission.schema.json +23 -0
  175. package/dist/schemas/onchain_operations_personal.schema.json +23 -0
  176. package/dist/schemas/onchain_operations_progress.schema.json +23 -0
  177. package/dist/schemas/onchain_operations_repository.schema.json +23 -0
  178. package/dist/schemas/onchain_operations_reward.schema.json +23 -0
  179. package/dist/schemas/onchain_operations_service.schema.json +23 -0
  180. package/dist/schemas/onchain_operations_treasury.schema.json +23 -0
  181. package/dist/schemas/onchain_table_data.output.json +939 -69
  182. package/dist/schemas/onchain_table_data.schema.json +2 -2
  183. package/dist/schemas/project_operation.output.json +18 -0
  184. package/dist/schemas/project_operation.schema.json +42 -0
  185. package/dist/schemas/query_toolkit.schema.json +360 -368
  186. package/dist/schemas/schema_query.schema.json +6 -3
  187. package/dist/schemas/trust_score.output.json +327 -0
  188. package/dist/schemas/trust_score.schema.json +46 -0
  189. package/package.json +2 -2
@@ -1,3 +1,4 @@
1
+ import { listIndustriesWithSignals, getIndustryEvolutionStatus, getPendingSuggestions, getIndustrySignalCount, } from "../knowledge/flywheel-loop.js";
1
2
  const THRESHOLDS = {
2
3
  UNKNOWN_ERROR_RATE_P0: 0.15,
3
4
  UNKNOWN_ERROR_RATE_P1: 0.08,
@@ -154,6 +155,98 @@ function diagnoseLatencyAnomalies(stats) {
154
155
  }
155
156
  return diagnoses;
156
157
  }
158
+ const INDUSTRY_HEALTH_THRESHOLDS = {
159
+ CRITICAL_HEALTH_SCORE: 45,
160
+ STRESSED_HEALTH_SCORE: 65,
161
+ HIGH_PENDING_SUGGESTIONS: 3,
162
+ STALE_SIGNAL_THRESHOLD: 20,
163
+ };
164
+ export function diagnoseIndustryHealth(industries) {
165
+ const targets = industries ?? listIndustriesWithSignals();
166
+ const diagnoses = [];
167
+ for (const industry of targets) {
168
+ const status = getIndustryEvolutionStatus(industry);
169
+ const pendingDetail = getPendingSuggestions(industry);
170
+ const signalCount = getIndustrySignalCount(industry);
171
+ if (status.health) {
172
+ const score = status.health.health_score;
173
+ if (score < INDUSTRY_HEALTH_THRESHOLDS.CRITICAL_HEALTH_SCORE) {
174
+ diagnoses.push({
175
+ diagnosis_id: `DIAG-IND-${Date.now()}-${industry}-critical`,
176
+ type: "industry_health_anomaly",
177
+ severity: "P0",
178
+ title: `Industry '${industry}' health critical (${score}/100, ${status.health.level})`,
179
+ description: `Industry health score is in the danger zone. Weaknesses: ${status.health.weaknesses.join("; ") || "none"}. Recommendations: ${status.health.recommendations.join("; ") || "none"}.`,
180
+ evidence: {
181
+ industry,
182
+ health_score: score,
183
+ health_level: status.health.level,
184
+ weaknesses: status.health.weaknesses,
185
+ recommendations: status.health.recommendations,
186
+ signal_count: signalCount,
187
+ },
188
+ target: `industry:${industry}`,
189
+ proposed_improvement_type: "industry_update_application",
190
+ });
191
+ }
192
+ else if (score < INDUSTRY_HEALTH_THRESHOLDS.STRESSED_HEALTH_SCORE) {
193
+ diagnoses.push({
194
+ diagnosis_id: `DIAG-IND-${Date.now()}-${industry}-stressed`,
195
+ type: "industry_health_anomaly",
196
+ severity: "P1",
197
+ title: `Industry '${industry}' health stressed (${score}/100, ${status.health.level})`,
198
+ description: `Industry health score is under pressure. Weaknesses: ${status.health.weaknesses.join("; ") || "none"}.`,
199
+ evidence: {
200
+ industry,
201
+ health_score: score,
202
+ health_level: status.health.level,
203
+ weaknesses: status.health.weaknesses,
204
+ signal_count: signalCount,
205
+ },
206
+ target: `industry:${industry}`,
207
+ proposed_improvement_type: "industry_update_application",
208
+ });
209
+ }
210
+ }
211
+ if (pendingDetail.length >= INDUSTRY_HEALTH_THRESHOLDS.HIGH_PENDING_SUGGESTIONS) {
212
+ const highPriority = pendingDetail.filter((s) => s.priority === "high");
213
+ diagnoses.push({
214
+ diagnosis_id: `DIAG-IND-${Date.now()}-${industry}-pending`,
215
+ type: "industry_health_anomaly",
216
+ severity: highPriority.length > 0 ? "P1" : "P2",
217
+ title: `Industry '${industry}' has ${pendingDetail.length} pending suggestions (${highPriority.length} high priority)`,
218
+ description: `Industry has ${pendingDetail.length} pending evolution suggestions unprocessed. Review and apply promptly to drive industry evolution.`,
219
+ evidence: {
220
+ industry,
221
+ pending_count: pendingDetail.length,
222
+ high_priority_count: highPriority.length,
223
+ suggestion_types: pendingDetail.map((s) => s.suggestion_type),
224
+ suggestion_summaries: pendingDetail.map((s) => ({ type: s.suggestion_type, field: s.field, priority: s.priority })),
225
+ },
226
+ target: `industry:${industry}:pending_suggestions`,
227
+ proposed_improvement_type: "industry_update_application",
228
+ });
229
+ }
230
+ if (signalCount >= INDUSTRY_HEALTH_THRESHOLDS.STALE_SIGNAL_THRESHOLD && !status.health) {
231
+ diagnoses.push({
232
+ diagnosis_id: `DIAG-IND-${Date.now()}-${industry}-stale`,
233
+ type: "industry_health_anomaly",
234
+ severity: "P2",
235
+ title: `Industry '${industry}' has ${signalCount} signals but no health report (evolution stale)`,
236
+ description: `Industry has accumulated ${signalCount} signals but health score has not been recalculated. May need to manually trigger updateIndustryCognition or check scheduling configuration.`,
237
+ evidence: {
238
+ industry,
239
+ signal_count: signalCount,
240
+ evolution_ready: status.evolution_ready,
241
+ version: status.version,
242
+ },
243
+ target: `industry:${industry}:cognition`,
244
+ proposed_improvement_type: "industry_update_application",
245
+ });
246
+ }
247
+ }
248
+ return diagnoses;
249
+ }
157
250
  export function diagnose(stats) {
158
251
  const all = [
159
252
  ...diagnoseRuleGaps(stats),
@@ -161,6 +254,7 @@ export function diagnose(stats) {
161
254
  ...diagnoseSkillNeeds(stats),
162
255
  ...diagnoseRecoveryIneffectiveness(stats),
163
256
  ...diagnoseLatencyAnomalies(stats),
257
+ ...diagnoseIndustryHealth(),
164
258
  ];
165
259
  const severityOrder = { P0: 0, P1: 1, P2: 2, P3: 3 };
166
260
  all.sort((a, b) => severityOrder[a.severity] - severityOrder[b.severity]);
@@ -1,5 +1,5 @@
1
1
  import type { DiagnosisReport } from "./diagnose.js";
2
- export type ProposalType = "error_rule_addition" | "intent_rule_addition" | "description_rewrite" | "skill_creation" | "recovery_priority_adjustment" | "investigation";
2
+ export type ProposalType = "error_rule_addition" | "intent_rule_addition" | "description_rewrite" | "skill_creation" | "recovery_priority_adjustment" | "investigation" | "industry_update_application";
3
3
  export type AutomationLevel = "full" | "semi" | "manual";
4
4
  export interface ImprovementProposal {
5
5
  proposal_id: string;
@@ -1,3 +1,4 @@
1
+ import { getPendingSuggestions } from "../knowledge/flywheel-loop.js";
1
2
  function proposeErrorRuleAddition(diagnosis) {
2
3
  const evidence = diagnosis.evidence;
3
4
  const topMessages = evidence.top_error_messages || [];
@@ -54,7 +55,7 @@ function proposeDescriptionRewrite(diagnosis) {
54
55
  current_semantic_hit_rate: evidence.semantic_hit_rate,
55
56
  target_semantic_hit_rate: 0.80,
56
57
  rewrite_guidelines: [
57
- "Follow 4-part format: 含义 + Constraint + Relation + Example",
58
+ "Follow 4-part format: Meaning + Constraint + Relation + Example",
58
59
  "Add explicit intent signals to INTENT_RULES",
59
60
  "Include concrete examples for common operation types",
60
61
  ],
@@ -139,6 +140,53 @@ function proposeInvestigation(diagnosis) {
139
140
  ab_test_recommended: false,
140
141
  };
141
142
  }
143
+ function proposeIndustryUpdate(diagnosis) {
144
+ const evidence = diagnosis.evidence;
145
+ const industry = evidence.industry ?? diagnosis.target.split(":")[1] ?? "unknown";
146
+ const pendingSuggestions = industry !== "unknown"
147
+ ? getPendingSuggestions(industry)
148
+ : [];
149
+ const changes = pendingSuggestions.map((s) => ({
150
+ suggestion_type: s.suggestion_type,
151
+ field: s.field,
152
+ suggested_value: s.suggested_value,
153
+ evidence: s.evidence,
154
+ confidence: s.confidence,
155
+ priority: s.priority,
156
+ }));
157
+ const isHealthCritical = evidence.health_score !== undefined && evidence.health_score < 45;
158
+ const hasHighPrioritySuggestions = (evidence.high_priority_count ?? 0) > 0;
159
+ return {
160
+ proposal_id: `PROP-IND-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
161
+ source_diagnosis_id: diagnosis.diagnosis_id,
162
+ type: "industry_update_application",
163
+ priority: diagnosis.severity,
164
+ automation: isHealthCritical ? "semi" : "manual",
165
+ title: `Apply ${pendingSuggestions.length} evolution suggestions for industry '${industry}'`,
166
+ description: `Industry '${industry}' has health anomaly (health score ${evidence.health_score ?? "N/A"}, level ${evidence.health_level ?? "N/A"}). ` +
167
+ `Has ${pendingSuggestions.length} pending evolution suggestions (${(evidence.high_priority_count ?? 0)} high priority). ` +
168
+ `Review and apply to drive industry cognition evolution. Weaknesses: ${(evidence.weaknesses ?? []).join("; ") || "none"}.`,
169
+ target: `industry:${industry}`,
170
+ proposed_change: {
171
+ action: "apply_industry_updates",
172
+ industry,
173
+ current_health_score: evidence.health_score,
174
+ current_health_level: evidence.health_level,
175
+ weaknesses: evidence.weaknesses ?? [],
176
+ recommendations: evidence.recommendations ?? [],
177
+ pending_suggestion_count: pendingSuggestions.length,
178
+ high_priority_count: evidence.high_priority_count ?? 0,
179
+ suggestions: changes,
180
+ auto_applicable_suggestions: changes.filter((c) => c.confidence >= 0.85 && c.priority === "high"),
181
+ apply_guidance: hasHighPrioritySuggestions
182
+ ? "Prioritize reviewing high-priority suggestions; high-confidence (≥0.85) suggestions can be semi-automatically applied"
183
+ : "No high-priority suggestions, review via normal process",
184
+ },
185
+ evidence: diagnosis.evidence,
186
+ review_status: "pending",
187
+ ab_test_recommended: false,
188
+ };
189
+ }
142
190
  export function generateImprovements(report) {
143
191
  const proposals = [];
144
192
  for (const diagnosis of report.diagnoses) {
@@ -156,6 +204,9 @@ export function generateImprovements(report) {
156
204
  case "recovery_priority_adjustment":
157
205
  proposal = proposeRecoveryAdjustment(diagnosis);
158
206
  break;
207
+ case "industry_update_application":
208
+ proposal = proposeIndustryUpdate(diagnosis);
209
+ break;
159
210
  default:
160
211
  proposal = proposeInvestigation(diagnosis);
161
212
  }
@@ -0,0 +1,71 @@
1
+ import type { ProjectObjectType } from "./namespace.js";
2
+ export type EdgeKind = "machine" | "order_allocators" | "arbitrations" | "compensation_fund" | "rewards" | "buy_guard" | "permission" | "guard" | "prev" | "next" | "forward" | "parent" | "service" | "progress" | "arbitration" | "sub_order" | "references";
3
+ export interface GraphNode {
4
+ id: string;
5
+ project?: string;
6
+ type?: ProjectObjectType;
7
+ address?: string;
8
+ decision_contexts?: GraphDecisionContext[];
9
+ }
10
+ export interface GraphDecisionContext {
11
+ id: string;
12
+ decided_at: number;
13
+ decider: "user" | "ai" | "system";
14
+ industry?: string;
15
+ intent?: string;
16
+ alternatives?: string[];
17
+ rationale?: string;
18
+ outcome?: "success" | "failed" | "pending";
19
+ }
20
+ export interface GraphEdge {
21
+ from: string;
22
+ to: string;
23
+ kind: EdgeKind;
24
+ }
25
+ export interface GraphSnapshot {
26
+ nodes: Record<string, GraphNode>;
27
+ edges: GraphEdge[];
28
+ cycles: string[][];
29
+ version: number;
30
+ updatedAt: number;
31
+ }
32
+ export declare class ProjectGraph {
33
+ private nodes;
34
+ private edges;
35
+ private outEdges;
36
+ private inEdges;
37
+ private cycles;
38
+ private updatedAt;
39
+ upsertNode(node: GraphNode): GraphNode;
40
+ addEdge(from: string, to: string, kind: EdgeKind): void;
41
+ removeNode(id: string): void;
42
+ getNode(id: string): GraphNode | undefined;
43
+ listNodes(projectPrefix?: string): GraphNode[];
44
+ getDependencies(id: string): GraphEdge[];
45
+ getReferencedBy(id: string): GraphEdge[];
46
+ detectCycles(): string[][];
47
+ findDanglingDependencies(): Array<{
48
+ from: string;
49
+ missing: string[];
50
+ }>;
51
+ snapshot(): GraphSnapshot;
52
+ restore(snap: GraphSnapshot): void;
53
+ clear(): void;
54
+ get nodeCount(): number;
55
+ get edgeCount(): number;
56
+ getEdges(): GraphEdge[];
57
+ attachDecisionContext(nodeId: string, ctx: Omit<GraphDecisionContext, "id" | "decided_at"> & Partial<Pick<GraphDecisionContext, "id" | "decided_at">>): GraphDecisionContext | undefined;
58
+ getDecisionContexts(nodeId: string): GraphDecisionContext[];
59
+ queryDecisionContextsByIndustry(industry: string): Array<{
60
+ node_id: string;
61
+ ctx: GraphDecisionContext;
62
+ }>;
63
+ backfillDecisionOutcome(decisionId: string, outcome: "success" | "failed" | "pending"): boolean;
64
+ }
65
+ export interface ExtractedReference {
66
+ field: string;
67
+ target: string;
68
+ kind: EdgeKind;
69
+ }
70
+ export declare function extractReferences(operation_type: string, data: any): ExtractedReference[];
71
+ export declare function nodeIdOf(name?: string, address?: string): string | undefined;
@@ -0,0 +1,314 @@
1
+ export class ProjectGraph {
2
+ nodes = new Map();
3
+ edges = [];
4
+ outEdges = new Map();
5
+ inEdges = new Map();
6
+ cycles = [];
7
+ updatedAt = Date.now();
8
+ upsertNode(node) {
9
+ const existing = this.nodes.get(node.id);
10
+ if (existing) {
11
+ this.nodes.set(node.id, {
12
+ ...existing,
13
+ ...node,
14
+ project: node.project ?? existing.project,
15
+ type: node.type ?? existing.type,
16
+ address: node.address ?? existing.address,
17
+ });
18
+ return this.nodes.get(node.id);
19
+ }
20
+ this.nodes.set(node.id, { ...node });
21
+ return node;
22
+ }
23
+ addEdge(from, to, kind) {
24
+ if (from === to)
25
+ return;
26
+ if (!this.nodes.has(from))
27
+ this.upsertNode({ id: from });
28
+ if (!this.nodes.has(to))
29
+ this.upsertNode({ id: to });
30
+ const dup = this.edges.some((e) => e.from === from && e.to === to && e.kind === kind);
31
+ if (dup)
32
+ return;
33
+ const idx = this.edges.length;
34
+ this.edges.push({ from, to, kind });
35
+ if (!this.outEdges.has(from))
36
+ this.outEdges.set(from, new Set());
37
+ this.outEdges.get(from).add(idx);
38
+ if (!this.inEdges.has(to))
39
+ this.inEdges.set(to, new Set());
40
+ this.inEdges.get(to).add(idx);
41
+ this.updatedAt = Date.now();
42
+ }
43
+ removeNode(id) {
44
+ if (!this.nodes.has(id))
45
+ return;
46
+ this.nodes.delete(id);
47
+ const outSet = this.outEdges.get(id);
48
+ const inSet = this.inEdges.get(id);
49
+ const indicesToRemove = new Set([
50
+ ...(outSet ?? []),
51
+ ...(inSet ?? []),
52
+ ]);
53
+ const newEdges = [];
54
+ const indexMap = new Map();
55
+ for (let i = 0; i < this.edges.length; i++) {
56
+ if (indicesToRemove.has(i))
57
+ continue;
58
+ indexMap.set(i, newEdges.length);
59
+ newEdges.push(this.edges[i]);
60
+ }
61
+ this.edges = newEdges;
62
+ this.outEdges.clear();
63
+ this.inEdges.clear();
64
+ for (let i = 0; i < this.edges.length; i++) {
65
+ const e = this.edges[i];
66
+ if (!this.outEdges.has(e.from))
67
+ this.outEdges.set(e.from, new Set());
68
+ this.outEdges.get(e.from).add(i);
69
+ if (!this.inEdges.has(e.to))
70
+ this.inEdges.set(e.to, new Set());
71
+ this.inEdges.get(e.to).add(i);
72
+ }
73
+ this.updatedAt = Date.now();
74
+ }
75
+ getNode(id) {
76
+ return this.nodes.get(id);
77
+ }
78
+ listNodes(projectPrefix) {
79
+ const all = Array.from(this.nodes.values());
80
+ if (!projectPrefix)
81
+ return all;
82
+ return all.filter((n) => n.project === projectPrefix);
83
+ }
84
+ getDependencies(id) {
85
+ const idxs = this.outEdges.get(id);
86
+ if (!idxs)
87
+ return [];
88
+ return Array.from(idxs).map((i) => this.edges[i]);
89
+ }
90
+ getReferencedBy(id) {
91
+ const idxs = this.inEdges.get(id);
92
+ if (!idxs)
93
+ return [];
94
+ return Array.from(idxs).map((i) => this.edges[i]);
95
+ }
96
+ detectCycles() {
97
+ const WHITE = 0, GRAY = 1, BLACK = 2;
98
+ const color = new Map();
99
+ for (const id of this.nodes.keys())
100
+ color.set(id, WHITE);
101
+ const cycles = [];
102
+ const stack = [];
103
+ const dfs = (u) => {
104
+ color.set(u, GRAY);
105
+ stack.push(u);
106
+ const outIdxs = this.outEdges.get(u);
107
+ if (outIdxs) {
108
+ for (const i of outIdxs) {
109
+ const v = this.edges[i].to;
110
+ if (color.get(v) === GRAY) {
111
+ const start = stack.indexOf(v);
112
+ if (start >= 0) {
113
+ cycles.push(stack.slice(start).concat(v));
114
+ }
115
+ }
116
+ else if (color.get(v) === WHITE) {
117
+ dfs(v);
118
+ }
119
+ }
120
+ }
121
+ stack.pop();
122
+ color.set(u, BLACK);
123
+ };
124
+ for (const id of this.nodes.keys()) {
125
+ if (color.get(id) === WHITE)
126
+ dfs(id);
127
+ }
128
+ this.cycles = cycles;
129
+ return cycles;
130
+ }
131
+ findDanglingDependencies() {
132
+ const result = [];
133
+ for (const [id, node] of this.nodes) {
134
+ const deps = this.getDependencies(id);
135
+ const missing = deps
136
+ .map((e) => this.nodes.get(e.to))
137
+ .filter((n) => !!n)
138
+ .filter((n) => !n.address && !n.project)
139
+ .map((n) => n.id);
140
+ if (missing.length > 0) {
141
+ result.push({ from: id, missing: Array.from(new Set(missing)) });
142
+ }
143
+ }
144
+ return result;
145
+ }
146
+ snapshot() {
147
+ return {
148
+ nodes: Object.fromEntries(this.nodes),
149
+ edges: this.edges,
150
+ cycles: this.cycles,
151
+ version: 1,
152
+ updatedAt: this.updatedAt,
153
+ };
154
+ }
155
+ restore(snap) {
156
+ this.nodes.clear();
157
+ this.edges = [];
158
+ this.outEdges.clear();
159
+ this.inEdges.clear();
160
+ for (const [id, node] of Object.entries(snap.nodes)) {
161
+ this.nodes.set(id, { ...node });
162
+ }
163
+ for (const e of snap.edges) {
164
+ this.addEdge(e.from, e.to, e.kind);
165
+ }
166
+ this.cycles = snap.cycles ?? [];
167
+ this.updatedAt = snap.updatedAt ?? Date.now();
168
+ }
169
+ clear() {
170
+ this.nodes.clear();
171
+ this.edges = [];
172
+ this.outEdges.clear();
173
+ this.inEdges.clear();
174
+ this.cycles = [];
175
+ this.updatedAt = Date.now();
176
+ }
177
+ get nodeCount() { return this.nodes.size; }
178
+ get edgeCount() { return this.edges.length; }
179
+ getEdges() {
180
+ return this.edges;
181
+ }
182
+ attachDecisionContext(nodeId, ctx) {
183
+ if (!nodeId)
184
+ return undefined;
185
+ const node = this.nodes.get(nodeId) ?? this.upsertNode({ id: nodeId });
186
+ const fullCtx = {
187
+ id: ctx.id ?? `${nodeId}_${Date.now()}`,
188
+ decided_at: ctx.decided_at ?? Date.now(),
189
+ decider: ctx.decider,
190
+ industry: ctx.industry,
191
+ intent: ctx.intent,
192
+ alternatives: ctx.alternatives,
193
+ rationale: ctx.rationale,
194
+ outcome: ctx.outcome,
195
+ };
196
+ if (!node.decision_contexts)
197
+ node.decision_contexts = [];
198
+ node.decision_contexts.push(fullCtx);
199
+ this.updatedAt = Date.now();
200
+ return fullCtx;
201
+ }
202
+ getDecisionContexts(nodeId) {
203
+ return this.nodes.get(nodeId)?.decision_contexts ?? [];
204
+ }
205
+ queryDecisionContextsByIndustry(industry) {
206
+ const results = [];
207
+ for (const [id, node] of this.nodes) {
208
+ if (!node.decision_contexts)
209
+ continue;
210
+ for (const ctx of node.decision_contexts) {
211
+ if (ctx.industry === industry) {
212
+ results.push({ node_id: id, ctx });
213
+ }
214
+ }
215
+ }
216
+ results.sort((a, b) => b.ctx.decided_at - a.ctx.decided_at);
217
+ return results;
218
+ }
219
+ backfillDecisionOutcome(decisionId, outcome) {
220
+ for (const node of this.nodes.values()) {
221
+ if (!node.decision_contexts)
222
+ continue;
223
+ const ctx = node.decision_contexts.find((c) => c.id === decisionId);
224
+ if (ctx) {
225
+ ctx.outcome = outcome;
226
+ this.updatedAt = Date.now();
227
+ return true;
228
+ }
229
+ }
230
+ return false;
231
+ }
232
+ }
233
+ export function extractReferences(operation_type, data) {
234
+ const refs = [];
235
+ if (!data || typeof data !== "object")
236
+ return refs;
237
+ const pushRef = (field, val, kind) => {
238
+ if (!val)
239
+ return;
240
+ if (typeof val === "string") {
241
+ if (val.trim())
242
+ refs.push({ field, target: val.trim(), kind });
243
+ }
244
+ else if (Array.isArray(val)) {
245
+ for (const v of val)
246
+ pushRef(field, v, kind);
247
+ }
248
+ else if (typeof val === "object") {
249
+ const name = val.name_or_address ?? val.name ?? val.address;
250
+ if (typeof name === "string" && name.trim()) {
251
+ refs.push({ field, target: name.trim(), kind });
252
+ }
253
+ }
254
+ };
255
+ if (operation_type === "service") {
256
+ pushRef("machine", data.machine, "machine");
257
+ pushRef("order_allocators", data.order_allocators, "order_allocators");
258
+ pushRef("arbitrations", data.arbitrations, "arbitrations");
259
+ pushRef("compensation_fund", data.compensation_fund, "compensation_fund");
260
+ pushRef("rewards", data.rewards, "rewards");
261
+ pushRef("buy_guard", data.buy_guard, "buy_guard");
262
+ pushRef("permission", data.permission, "permission");
263
+ }
264
+ if (operation_type === "order") {
265
+ pushRef("service", data.service, "service");
266
+ pushRef("progress", data.progress, "progress");
267
+ pushRef("arbitration", data.arbitration, "arbitration");
268
+ }
269
+ if (operation_type === "machine" && Array.isArray(data.node?.nodes)) {
270
+ for (const n of data.node.nodes) {
271
+ if (!n || typeof n !== "object")
272
+ continue;
273
+ const nodeName = n.name;
274
+ if (typeof nodeName !== "string")
275
+ continue;
276
+ if (Array.isArray(n.pairs)) {
277
+ for (const p of n.pairs) {
278
+ if (p && typeof p === "object") {
279
+ if (typeof p.prev === "string") {
280
+ refs.push({ field: `node.${nodeName}.prev`, target: p.prev, kind: "prev" });
281
+ }
282
+ if (typeof p.next === "string") {
283
+ refs.push({ field: `node.${nodeName}.next`, target: p.next, kind: "next" });
284
+ }
285
+ }
286
+ }
287
+ }
288
+ if (Array.isArray(n.forward)) {
289
+ for (const f of n.forward) {
290
+ if (f && typeof f === "object" && typeof f.next === "string") {
291
+ refs.push({ field: `node.${nodeName}.forward`, target: f.next, kind: "forward" });
292
+ }
293
+ }
294
+ }
295
+ }
296
+ }
297
+ if (operation_type === "progress" && data.parent) {
298
+ pushRef("parent", data.parent, "parent");
299
+ }
300
+ if (data.permission)
301
+ pushRef("permission", data.permission, "permission");
302
+ if (data.guard)
303
+ pushRef("guard", data.guard, "guard");
304
+ if (data.buy_guard)
305
+ pushRef("buy_guard", data.buy_guard, "buy_guard");
306
+ return refs;
307
+ }
308
+ export function nodeIdOf(name, address) {
309
+ if (name && typeof name === "string" && name.trim())
310
+ return name.trim();
311
+ if (address && typeof address === "string" && address.trim())
312
+ return address.trim();
313
+ return undefined;
314
+ }
@@ -0,0 +1,62 @@
1
+ import { type ProjectObjectType, type ProjectRole, type IndustryMode } from "./namespace.js";
2
+ import { ProjectGraph } from "./graph.js";
3
+ import { type ProjectInfo, type DependencyTrace, type ReverseTrace } from "./query.js";
4
+ export * from "./namespace.js";
5
+ export * from "./graph.js";
6
+ export * from "./query.js";
7
+ export declare function isProjectServiceEnabled(): boolean;
8
+ export declare function getGraph(): ProjectGraph;
9
+ export declare function setGraph(g: ProjectGraph): void;
10
+ export interface NormalizeCallInput {
11
+ operation_type: string;
12
+ data: any;
13
+ projectPrefix?: string;
14
+ role?: ProjectRole;
15
+ industry?: IndustryMode;
16
+ version?: string;
17
+ shareable?: boolean;
18
+ }
19
+ export interface NormalizeCallResult {
20
+ data: any;
21
+ warnings: string[];
22
+ project?: {
23
+ prefix: string;
24
+ type?: ProjectObjectType;
25
+ version?: string;
26
+ };
27
+ }
28
+ export declare function normalize(input: NormalizeCallInput): NormalizeCallResult;
29
+ export declare function observe(operation_type: string, data: any, result?: any): void;
30
+ export declare function queryProjects(): Promise<ProjectInfo[]>;
31
+ export declare function queryProjectObjects(prefix: string): Promise<{
32
+ name?: string;
33
+ address?: string;
34
+ type?: string;
35
+ }[]>;
36
+ export declare function queryShareableObjects(): Promise<{
37
+ name?: string;
38
+ address?: string;
39
+ type?: string;
40
+ project?: string;
41
+ }[]>;
42
+ export declare function queryDependencies(objectId: string): DependencyTrace;
43
+ export declare function queryReferencedBy(objectId: string): ReverseTrace;
44
+ export declare function queryPrePublishCheck(serviceId: string): string[];
45
+ export declare function queryCrossProjectReferences(): {
46
+ edge: import("./graph.js").GraphEdge;
47
+ fromProject?: string;
48
+ toProject?: string;
49
+ }[];
50
+ export declare function queryGraphStats(): {
51
+ nodeCount: number;
52
+ edgeCount: number;
53
+ cycles: string[][];
54
+ dangling: {
55
+ from: string;
56
+ missing: string[];
57
+ }[];
58
+ };
59
+ export declare function saveGraph(): string;
60
+ export declare function loadGraph(): boolean;
61
+ export declare function hasPersistedGraph(): boolean;
62
+ export declare const PROJECT_SERVICE_VERSION = 1;