archgraph-argo-beta 0.27.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +107 -0
  3. package/argo/.env.example +170 -0
  4. package/argo/defaults/EA-model-template.qea +0 -0
  5. package/argo/defaults/design/KG/SystemArchitecture.json +128 -0
  6. package/argo/mcp-bridges/graph-mcp-stdio.js +98 -0
  7. package/argo/package.json +8 -0
  8. package/argo/plugins/argo-cost-collector.js +35 -0
  9. package/argo/plugins/argo-wakeup.js +29 -0
  10. package/argo/rules/archgraph.instructions.md +189 -0
  11. package/argo/schema/ImplementationToCodingHandoff.schema.json +252 -0
  12. package/argo/schema/ImplementationToIntentTraceProposal.schema.json +180 -0
  13. package/argo/schema/IntentToImplementationHandoff.schema.json +75 -0
  14. package/argo/schema/SystemArchitecture.schema.json +378 -0
  15. package/argo/schema/archimate3.2.md +7153 -0
  16. package/argo/schema/argob-rules.json +12229 -0
  17. package/argo/schema/argob.config.json +20 -0
  18. package/argo/scripts/ARCHITECTURE.md +58 -0
  19. package/argo/scripts/agentSearchDiagnose.js +407 -0
  20. package/argo/scripts/archimate32-rules.js +12301 -0
  21. package/argo/scripts/argo-mcp-server.js +952 -0
  22. package/argo/scripts/argo-paths.js +168 -0
  23. package/argo/scripts/argob-schema.js +574 -0
  24. package/argo/scripts/ea-qea-sync-lib.js +1014 -0
  25. package/argo/scripts/ea-qea-sync.js +110 -0
  26. package/argo/scripts/ensureArgoHarnessEnvironment.js +451 -0
  27. package/argo/scripts/external-graph-query.js +162 -0
  28. package/argo/scripts/generateArchitectureDiffPlantuml.js +466 -0
  29. package/argo/scripts/graph-rag/ARCHITECTURE.md +192 -0
  30. package/argo/scripts/graph-rag/agentCostLog.js +179 -0
  31. package/argo/scripts/graph-rag/canonicalProjectionAuthority.js +45 -0
  32. package/argo/scripts/graph-rag/defaultSemanticRetrieval.js +1244 -0
  33. package/argo/scripts/graph-rag/embeddingProviderProfile.js +89 -0
  34. package/argo/scripts/graph-rag/embeddingQualificationGate.js +59 -0
  35. package/argo/scripts/graph-rag/externalProductionConfig.js +74 -0
  36. package/argo/scripts/graph-rag/hybridRetrieval.js +114 -0
  37. package/argo/scripts/graph-rag/liveEmbeddingIndexGate.js +128 -0
  38. package/argo/scripts/graph-rag/liveEmbeddingNeo4jBoundary.js +137 -0
  39. package/argo/scripts/graph-rag/liveEmbeddingProviderClient.js +49 -0
  40. package/argo/scripts/graph-rag/liveEmbeddingProviderConfig.js +571 -0
  41. package/argo/scripts/graph-rag/mcpCrashDiagnostics.js +137 -0
  42. package/argo/scripts/graph-rag/mutationEmbeddingVectorLifecycle.js +1266 -0
  43. package/argo/scripts/graph-rag/neo4jNativeRetrieval.js +37 -0
  44. package/argo/scripts/graph-rag/productionGraphRagRuntime.js +1633 -0
  45. package/argo/scripts/graph-rag/rerankRetrieval.js +201 -0
  46. package/argo/scripts/graph-rag/semantic-persistence/ARCHITECTURE.md +51 -0
  47. package/argo/scripts/graph-rag/semantic-persistence/productionSemanticBackfill.js +342 -0
  48. package/argo/scripts/graph-rag/semantic-persistence/productionSemanticCheckpointStore.js +99 -0
  49. package/argo/scripts/graph-rag/semantic-persistence/productionSemanticNeo4jAdapter.js +186 -0
  50. package/argo/scripts/graph-rag/semantic-persistence/productionSemanticProjectionStore.js +171 -0
  51. package/argo/scripts/graph-rag/semanticAlignmentLock.js +76 -0
  52. package/argo/scripts/graph-rag/semanticAlignmentRunner.js +131 -0
  53. package/argo/scripts/graph-rag/semanticInitConfiguration.js +24 -0
  54. package/argo/scripts/graph-rag/semanticOperatorError.js +38 -0
  55. package/argo/scripts/graph-rag/semanticOperatorJourney.js +459 -0
  56. package/argo/scripts/graph-rag/semanticReadinessAttestationStore.js +398 -0
  57. package/argo/scripts/graph-rag/semanticRecordText.js +75 -0
  58. package/argo/scripts/graph-rag/systemMetadataCommandAdapter.js +269 -0
  59. package/argo/scripts/graph-semantics.js +266 -0
  60. package/argo/scripts/lossless-write-gate.js +500 -0
  61. package/argo/scripts/neo4j-system-architecture-store.js +1066 -0
  62. package/argo/scripts/repair-subdiagram-views.js +288 -0
  63. package/argo/scripts/repositoryArgoEnvironment.js +101 -0
  64. package/argo/scripts/runArchitectureTests.js +591 -0
  65. package/argo/scripts/semanticOperatorJourneyCli.js +91 -0
  66. package/argo/scripts/syncSystemArchitectureToNeo4j.js +67 -0
  67. package/argo/scripts/systemarchitecture-mcp-server.js +4508 -0
  68. package/argo/scripts/test-executors/_template.js +58 -0
  69. package/argo/scripts/test-executors/default.js +199 -0
  70. package/argo/scripts/validateStageHandoff.js +459 -0
  71. package/argo/scripts/validateSystemArchitecture.js +261 -0
  72. package/argo/scripts/validateTraceProposal.js +181 -0
  73. package/argo/scripts/validator-mcp-server.js +347 -0
  74. package/argo/skills/agent-search-diagnosis/SKILL.md +60 -0
  75. package/argo/skills/argo-init/SKILL.md +86 -0
  76. package/argo/skills/ea-human-reconcile/SKILL.md +40 -0
  77. package/bin/argo-deploy.js +12 -0
  78. package/cordis.patch.yml +6 -0
  79. package/dsh-argo-wakeup/index.js +17 -0
  80. package/dsh-argo-wakeup/package.json +1 -0
  81. package/dsh-argo-workspace/index.js +142 -0
  82. package/dsh-argo-workspace/package.json +1 -0
  83. package/install-argo.ps1 +1162 -0
  84. package/package.json +56 -0
  85. package/vendor/neo4j-driver-6.2.0.tgz +0 -0
@@ -0,0 +1,20 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "title": "ArgoBument default schema bundle descriptor",
4
+ "description": "Descriptor for the default ARGO schema bundle (ArchiMate 3.2 + ARGO extensions). A repository may override this bundle by placing its own SystemArchitecture.schema.json (plus an optional argob.config.json / argob-rules.json) under <workspace>/.argo/schema.",
5
+ "language": "ArchiMate 3.2",
6
+ "elementTypeEnumKey": "archimateElementType",
7
+ "relationshipTypeEnumKey": "archimateRelationshipType",
8
+ "actorElementType": "Business Actor",
9
+ "guide": "archimate3.2.md",
10
+ "deliveryDependencies": {
11
+ "sourceDependsOnTarget": ["Access", "Assignment", "Specialization", "Composition", "Aggregation"],
12
+ "targetDependsOnSource": ["Serving", "Realization", "Flow", "Triggering", "Influence"]
13
+ },
14
+ "invariants": {
15
+ "statementGrammar": true,
16
+ "endpointMatrix": true,
17
+ "rootViewName": "SystemArchitecture",
18
+ "maxElementsPerView": 15
19
+ }
20
+ }
@@ -0,0 +1,58 @@
1
+ # Intent Query Runtime Contract
2
+
3
+ This local contract refines `OVERALL_ARCHITECTURE.md`.
4
+
5
+ ## Responsibilities
6
+
7
+ - `.argo/scripts/argo-mcp-server.js` owns transport-neutral tool registration, keeps canonical `initializeWorkspace`/argo init semantics explicit, privately invokes the canonical semantic lifecycle after initialization, and delegates `getSystemArchitecture` without interpreting query policy.
8
+ - `.argo/scripts/systemarchitecture-mcp-server.js` owns the deep query and canonical-write orchestration module: request validation, mode selection, canonical full reads, per-call persistent semantic readiness, exact touched-ID mutation dispatch, and durable lifecycle outcome attachment.
9
+ - View capacity validation is a canonical mutation validation responsibility. Prospective add/update View and element/relationship membership mutations must apply one global 15 included_elements hard maximum, count only included_elements, keep included_relationships outside quota, preserve endpoint coexistence, and avoid recomposing existing View memberships solely because the policy is active.
10
+ - The BP MCP semantic query contract adds request-shape validation and canonical subset response mapping to this module. Forbidden response-shape controls (`responseProfile`, `detail`, `outputMode`, and debug/full/evidence variants) must fail before retrieval with `QUERY_RESPONSE_SHAPE_CONTROL_FORBIDDEN` for ordinary semantic queries with or without anchors; successful ordinary semantic payloads expose a `document` whose root contains only canonical `elements`, `relationships`, and `views` collections without requiring `query.anchors` to activate the contract.
11
+ - `design/KG/SystemArchitecture.json` remains the canonical read source; no query mode may rewrite it.
12
+ - W6 semantic-query responses must expose the governing canonical graph version in query/result evidence and it must equal the canonical version or Harness-defined fingerprint of the same legacy graph read; missing or mismatched canonical-version evidence blocks coherent-result delivery even when the no-argument canonical read still succeeds.
13
+
14
+ ## Interface boundary
15
+
16
+ `getSystemArchitecture` accepts:
17
+
18
+ - `query`: REQUIRED. An omitted-query call is rejected with `QUERY_REQUIRED`; the legacy full-graph snapshot envelope is no longer exposed to agents.
19
+ - `query.purpose`: one of `general` or `audit` (`intent-decision`, `implementation-design`, `coding-repair`, and `graph-tidy` were removed from the agent-facing purpose enum; the runtime engine retains all of them as internal closure categories reachable only via the private journey/CLI, never the public tool — `general` binds to the internal `implementation-design` closure category);
20
+ - `query.intent`: required non-empty natural-language intent for an explicit query;
21
+ - `query.subject`: required non-empty audit subject when `purpose` is `audit`;
22
+ - optional deterministic anchors may be added without changing no-argument behavior.
23
+
24
+ Both purpose values remain legal agent-facing contract inputs. `general` (generic semantic/memory retrieval, loose threshold) and valid `audit` requests (strict proof-closure, subject required) invoke the semantic retrieval boundary. No agent-facing path reports `mode: "full-snapshot"` or `semanticRetrieval: "bypassed"`; the output contract mode is `semantic-query` or `error` only.
25
+
26
+ For W6, semantic query results must remain traceable to the canonical graph version used by the same no-argument legacy read. Endpoint, View, and provenance completion are delegated inward to the Graph RAG boundary, but the query service must surface their evidence without silently dropping or rewriting `canonicalVersion`, policy, index, or alignment fields.
27
+
28
+ For BP-MCP-SEM-PAYLOAD and BP-MCP-SEM-ELEMENT, semantic result mapping is object-set selection rather than field-level shaping. Returned Elements, Relationships, and Views must deep-equal their canonical objects. Element-only hits do not add adjacent relationships, endpoint neighbors, or owning Views unless independently selected or required by selected Relationship/View closure.
29
+
30
+ Validation occurs before retrieval and returns these stable categories:
31
+
32
+ - missing `query`: `QUERY_REQUIRED`;
33
+ - missing purpose: `QUERY_PURPOSE_REQUIRED`;
34
+ - purpose outside the legal enum: `QUERY_PURPOSE_INVALID`;
35
+ - missing or blank intent: `QUERY_INTENT_REQUIRED`;
36
+ - missing or blank audit subject: `AUDIT_SUBJECT_REQUIRED`.
37
+ - forbidden response-shape control: `QUERY_RESPONSE_SHAPE_CONTROL_FORBIDDEN`.
38
+
39
+ Public semantic `getSystemArchitecture` dispatch privately composes accepted WP-P2 readiness and retrieval on every ordinary query. No prior explicit readiness command or durable WP-P3 authorization record is required or publicly routable. This applies to exported System/unified `callTool` invocations and JSON-RPC handlers alike. Only the private raw semantic-query delegate accepts `semanticRetrievalBoundary.retrieve(request)` after the same invocation has freshly verified persistent readiness; it is not a public tool path or a missing-dependency fallback. No-argument and graph-tidy reads continue to bypass semantic work. System and unified JSON-RPC handlers preserve one exact readiness error object containing only `category`, `state`, `verified`, canonical/content/index versions, completed/missing/mismatched channels, `fullSnapshotFallback`, and `action`. Every value derives from its identically named approved error diagnostic under the frozen normalization, except literal-false `fullSnapshotFallback`; constants, cross-field substitutions, message, stack, secrets, unsafe source, and extras are prohibited.
40
+
41
+ `startNewProjectSemanticJourney`, `backfillSystemArchitectureSemanticProjection`, and `verifySystemArchitectureSemanticReadiness` are retired public names. They are absent from both `TOOLS` registries, both `tools/list` responses, `SYSTEM_ARCHITECTURE_TOOL_NAMES`, and all public `callTool` branches. Their WP-P1/WP-P2 operations remain private ports under canonical argo init and ordinary `getSystemArchitecture(query)`.
42
+
43
+ Every successful batch or focused canonical write clears readiness before semantic side effects and passes exact `touchedElementIds`, `touchedRelationshipIds`, and `touchedViewIds` to the durable incremental lifecycle. Preview/dry-run never enters that lifecycle. Canonical JSON remains written and authoritative when semantic work is disabled or fails; the response records Pending, Stale, or Failed with `fullSnapshotFallback: false`.
44
+
45
+ View capacity mutation validation uses `graph-semantics.js` `validateViewElementLimits(document, errors, { touchedViewIds })` from `systemarchitecture-mcp-server.js`. The validator is responsible for the `view15-global-limit-principle`, `view15-counting-semantics-requirement`, `view15-prospective-stability-constraint`, `view15-enforcement-completeness-requirement`, and `view15-active-authority-requirement` mappings; active policy comments, diagnostics, mutation/remediation guidance, graph descriptions, acceptance wording, current tests, and active MCP guidance in `design/mcp/意图架构 MCP 功能列表.md` use Fifteen/15 while historical records preserve their original seven-element semantics. `included_relationships` consume no quota, endpoint coexistence remains enforced by graph semantics, and every focused or batch addView, addElement-to-View, updateView, addRelationship, or updateRelationship route that can grow View membership uses the same prospective 15-element gate before persistence. Actual rejected write payloads must carry the same maximum-15 and observed-count-16 diagnostics that preview/dry-run payloads expose.
46
+
47
+ The cumulative canonical lifecycle target set remains `argo-mcp-server.js`, `systemarchitecture-mcp-server.js`, `graph-rag/semanticOperatorJourney.js`, `graph-rag/mutationEmbeddingVectorLifecycle.js`, and `graph-rag/defaultSemanticRetrieval.js`. The current SP-05 correction authorizes only `argo-mcp-server.js`, `systemarchitecture-mcp-server.js`, and `graph-rag/semanticOperatorJourney.js`: canonical init must expose and invoke the existing readiness store's invalidate/failure ports so every outcome transforms one stable identity/recordId/canonical-version record with increasing revision, and the gateway's init-specific failure path must map exact actionable redacted category/message/action without raw-secret leakage. Shared semantic-query error mapping, mutation behavior, WP-P2 algorithms, configuration, WP-P1 persistence/backfill/checkpoint/Neo4j adapters, runtime, provider, and every other module remain frozen inward dependencies.
48
+
49
+ ## Local dependencies
50
+
51
+ - The unified gateway may depend on `systemarchitecture-mcp-server.js` through `callTool` and one private post-initialize lifecycle port.
52
+ - The deep query module depends inward on the injected semantic retrieval boundary rather than constructing retrieval inside validation or mode selection.
53
+ - The query boundary may depend on graph/schema validation, canonical filesystem loading, and Neo4j synchronization support.
54
+ - Neither runtime module may depend on `tests/`, explicit entrypoints, or test-only fixtures.
55
+
56
+ ## Owned tests
57
+
58
+ Runtime behavior is accepted through the test-owned paths declared in `tests/ARCHITECTURE.md`. The BP MCP semantic query contract is accepted through `tests/explicit/entries/runMcpSemanticQueryContract.js` with graph-mounted `#anchor` fragments that also exercise no-anchor public `callTool` and unified MCP handler subcases for request-shape rejection and canonical subset payloads. View15 capacity policy is accepted through `tests/explicit/entries/runView15GlobalScope.js`, `tests/explicit/entries/runView15Relationships.js`, `tests/explicit/entries/runView15NoMigration.js`, `tests/explicit/entries/runView15Consistency.js`, `tests/explicit/entries/runView15IndirectGrowth.js`, and the frozen `tests/architecture/view-capacity-policy/` guards. This module owns no mutable test expectations.
@@ -0,0 +1,407 @@
1
+ 'use strict';
2
+ /**
3
+ * Agent search diagnosis (framework, zero-dependency).
4
+ *
5
+ * Turns ONE agent session into a self-contained diagnostic bundle so the user
6
+ * can hand it back for analysis:
7
+ *
8
+ * <workspace>/.argo/temp/diagnosis/<session-id>/
9
+ * ├─ diagnosis.md human-readable summary (incl. heuristic hints)
10
+ * ├─ metrics.json the numbers behind the summary
11
+ * ├─ session.ndjson the raw host session (full tool input/output)
12
+ * ├─ cost-log.slice.ndjson the matching slice of the background cost log
13
+ * └─ manifest.json file list + sizes + versions
14
+ *
15
+ * Data sources (user's choice: both):
16
+ * - PRIMARY: the host session NDJSON (opencode export / run --format json),
17
+ * which carries every tool's full input/output + timestamps + tokens.
18
+ * - SUPPLEMENT: the framework cost log <workspace>/.argo/temp/agent-cost-log.ndjson.
19
+ *
20
+ * Usage:
21
+ * node agentSearchDiagnose.js --session <session.ndjson> [--session-id ID]
22
+ * [--cost-log <path>] [--workspace <root>] [--out <dir>] [--json]
23
+ *
24
+ * Read-only except for writing the bundle dir. Never mutates the graph or repo.
25
+ */
26
+ const fs = require('node:fs');
27
+ const path = require('node:path');
28
+ const crypto = require('node:crypto');
29
+
30
+ const BUNDLE_VERSION = 'temp2.2';
31
+ const SCHEMA_VERSION = 1;
32
+ const GRAPH_TOOLS = ['getSystemArchitecture', 'getIntentElementContext', 'getArchitectureViewContext', 'queryNeo4jGraph', 'memory_search'];
33
+ const GRAPH_WRITE_TOOLS = ['previewSystemArchitectureMutation', 'applySystemArchitectureMutation', 'addArchitectureElement', 'updateArchitectureElement', 'removeArchitectureElement', 'addArchitectureRelationship', 'updateArchitectureRelationship', 'removeArchitectureRelationship', 'addArchitectureView', 'updateArchitectureView', 'removeArchitectureView'];
34
+ const VALIDATOR_TOOLS = ['validateSystemArchitecture', 'runArchitectureTests', 'initializeWorkspace'];
35
+ const REPO_TOOLS = ['read', 'grep', 'glob', 'list', 'bash', 'webfetch', 'edit', 'write'];
36
+
37
+ function backendOf(tool) {
38
+ const n = String(tool || '');
39
+ const hit = (l) => l.some(t => n.includes(t));
40
+ if (hit(GRAPH_WRITE_TOOLS)) return 'graph';
41
+ if (hit(GRAPH_TOOLS)) return 'graph';
42
+ if (hit(VALIDATOR_TOOLS)) return 'framework';
43
+ if (hit(REPO_TOOLS)) return 'repo';
44
+ return 'other';
45
+ }
46
+
47
+ function classifyQuery(tool, input) {
48
+ const n = String(tool || '');
49
+ if (n.includes('question')) return 'human-wait';
50
+ if (n.includes('task')) return 'subagent';
51
+ if (n.includes('bash')) return 'bash';
52
+ if (n.includes('getSystemArchitecture') || n.includes('memory_search')) return 'semantic';
53
+ if (n.includes('queryNeo4jGraph')) return 'structured-cypher';
54
+ if (n.includes('getIntentElementContext') || n.includes('getArchitectureViewContext')) return 'structured-context';
55
+ if (n.includes('validateSystemArchitecture') || n.includes('runArchitectureTests')) return 'validate';
56
+ if (n.includes('initializeWorkspace')) return 'init';
57
+ if (n.includes('previewSystemArchitectureMutation') || GRAPH_WRITE_TOOLS.some(t => n.includes(t))) return 'mutation';
58
+ if (n.includes('read')) return 'file-read';
59
+ if (n.includes('grep')) return 'grep';
60
+ if (n.includes('glob') || n.includes('list')) return 'list';
61
+ if (n.includes('edit') || n.includes('write')) return 'edit';
62
+ if (n.includes('todowrite')) return 'todo';
63
+ return 'other';
64
+ }
65
+
66
+ // Tools that block on a HUMAN (time spent waiting for the person, not the agent).
67
+ const HUMAN_WAIT_TOOLS = ['question'];
68
+ const CONTEXT_BLOWUP_TOKENS = 100000;
69
+
70
+ function estimateTokens(text) {
71
+ if (!text) return 0;
72
+ const s = String(text);
73
+ const cjk = (s.match(/[\u4e00-\u9fff\u3400-\u4dbf\u3000-\u303f\uff00-\uffef]/g) || []).length;
74
+ return cjk + Math.ceil((s.length - cjk) / 4);
75
+ }
76
+
77
+ function stableStringify(value) {
78
+ if (value === null || typeof value !== 'object') return JSON.stringify(value);
79
+ if (Array.isArray(value)) return '[' + value.map(stableStringify).join(',') + ']';
80
+ return '{' + Object.keys(value).sort().map(k => JSON.stringify(k) + ':' + stableStringify(value[k])).join(',') + '}';
81
+ }
82
+
83
+ function signature(tool, input) {
84
+ try { return crypto.createHash('sha1').update(String(tool) + '|' + stableStringify(input || {})).digest('hex').slice(0, 12); }
85
+ catch (_) { return 'unknown'; }
86
+ }
87
+
88
+ function inputPreview(tool, input) {
89
+ if (!input || typeof input !== 'object') return '';
90
+ const pick = input.query && (input.query.intent || input.query) || input.pattern || input.elementId || input.elementName || input.view_id || input.path || input.filePath || input.cypher || input.intent;
91
+ const s = typeof pick === 'string' ? pick : (pick ? JSON.stringify(pick) : JSON.stringify(input));
92
+ return String(s).slice(0, 160);
93
+ }
94
+
95
+ function eventTime(e) {
96
+ const cands = [e.time, e.part && e.part.time, e.part && e.part.state && e.part.state.time];
97
+ for (const t of cands) {
98
+ if (!t) continue;
99
+ if (typeof t === 'number') return t;
100
+ if (typeof t.start === 'number' && typeof t.end === 'number') return t.end;
101
+ if (typeof t.start === 'number') return t.start;
102
+ if (typeof t.end === 'number') return t.end;
103
+ }
104
+ return typeof e.timestamp === 'number' ? e.timestamp : null;
105
+ }
106
+
107
+ function isExportJson(text) {
108
+ const t = String(text || '').trim();
109
+ if (!t.startsWith('{')) return false;
110
+ try { const j = JSON.parse(t); return !!(j && Array.isArray(j.messages)); } catch (_) { return false; }
111
+ }
112
+
113
+ // Accept BOTH the live event stream (opencode run --format json, NDJSON) and the
114
+ // session export JSON (opencode export -> { info, messages:[{info, parts:[...]}] }).
115
+ function exportToNdjson(text) {
116
+ const j = JSON.parse(text);
117
+ const ev = [];
118
+ for (const m of j.messages || []) {
119
+ const info = m.info || {};
120
+ const ts = info.time && (info.time.created || info.time.completed);
121
+ for (const p of m.parts || []) {
122
+ if (!p || typeof p !== 'object') continue;
123
+ if (p.type === 'tool') ev.push({ type: 'tool', timestamp: (p.state && p.state.time && p.state.time.end) || ts, part: p });
124
+ else if (p.type === 'step-start') ev.push({ type: 'step_start', timestamp: ts, part: p });
125
+ else if (p.type === 'text') ev.push({ type: 'text', timestamp: ts, part: p });
126
+ }
127
+ if (info.role === 'assistant' && info.tokens) ev.push({ type: 'step_finish', timestamp: info.time && info.time.completed, part: { tokens: info.tokens, cost: info.cost } });
128
+ }
129
+ return ev.map(e => JSON.stringify(e)).join('\n') + '\n';
130
+ }
131
+
132
+ function parseSession(text) {
133
+ const raw = String(text || '');
134
+ const toolCalls = [];
135
+ const usages = [];
136
+ let steps = 0; let tMin = null; let tMax = null; let cost = 0;
137
+ const texts = [];
138
+ for (const line of raw.split('\n')) {
139
+ const t = line.trim();
140
+ if (!t.startsWith('{')) continue;
141
+ let e; try { e = JSON.parse(t); } catch (_) { continue; }
142
+ const part = e.part || e;
143
+ if (part && part.type === 'text' && part.text) texts.push(part.text);
144
+ if (part && part.type === 'tool') {
145
+ const tool = part.tool || part.name || (part.state && part.state.tool) || 'tool';
146
+ const st = part.state || {};
147
+ const tm = st.time || {};
148
+ const out = st.output != null ? String(st.output) : '';
149
+ toolCalls.push({
150
+ tool, backend: backendOf(tool), queryClass: classifyQuery(tool, st.input),
151
+ durationMs: (typeof tm.start === 'number' && typeof tm.end === 'number') ? Math.max(0, tm.end - tm.start) : null,
152
+ ok: st.status ? st.status !== 'error' : true,
153
+ error: st.error ? String(st.error).slice(0, 200) : null,
154
+ signature: signature(tool, st.input), inputPreview: inputPreview(tool, st.input),
155
+ outputBytes: out.length, outputTokens: estimateTokens(out),
156
+ path: (st.input && (st.input.filePath || st.input.path || st.input.file)) || null,
157
+ });
158
+ }
159
+ if (e.type === 'step_start') steps += 1;
160
+ if (e.type === 'step_finish') {
161
+ const fin = (e.part && e.part.finish) ? e.part.finish : (e.part || e);
162
+ if (fin && typeof fin.cost === 'number') cost += fin.cost;
163
+ const tk = fin && (fin.tokens || (fin.finish && fin.finish.tokens));
164
+ if (tk) usages.push({ input: tk.input || 0, output: tk.output || 0, reasoning: tk.reasoning || 0, cacheRead: (tk.cache && tk.cache.read) || 0, cacheWrite: (tk.cache && tk.cache.write) || 0 });
165
+ }
166
+ const time = eventTime(e);
167
+ if (time !== null) { tMin = tMin === null ? time : Math.min(tMin, time); tMax = tMax === null ? time : Math.max(tMax, time); }
168
+ }
169
+ const tokensIn = usages.reduce((a, u) => a + u.input, 0);
170
+ const tokensOut = usages.reduce((a, u) => a + u.output, 0);
171
+ const tokensReasoning = usages.reduce((a, u) => a + u.reasoning, 0);
172
+ return { toolCalls, usages, texts, steps, cost, wallMs: (tMin !== null && tMax !== null && tMax >= tMin) ? tMax - tMin : null, tokensIn, tokensOut, tokensReasoning, tokens: tokensIn + tokensOut + tokensReasoning };
173
+ }
174
+
175
+ function countRoundTrips(toolCalls) {
176
+ const seq = toolCalls.map(c => c.backend).filter(b => b === 'graph' || b === 'repo');
177
+ let n = 0;
178
+ for (let i = 1; i < seq.length; i++) if (seq[i] !== seq[i - 1]) n += 1;
179
+ return n;
180
+ }
181
+
182
+ function diagnose(session, opts = {}) {
183
+ const tc = session.toolCalls;
184
+ const byTool = {};
185
+ const byBackend = { graph: { calls: 0, ms: 0 }, repo: { calls: 0, ms: 0 }, framework: { calls: 0, ms: 0 }, other: { calls: 0, ms: 0 } };
186
+ const byQueryClass = {};
187
+ const sigCount = {};
188
+ const pathReads = {};
189
+ let toolMs = 0; let humanWaitMs = 0; let errors = 0; let empty = 0;
190
+ for (const c of tc) {
191
+ const isHuman = c.queryClass === 'human-wait' || HUMAN_WAIT_TOOLS.some(t => String(c.tool).includes(t));
192
+ const bt = byTool[c.tool] || (byTool[c.tool] = { calls: 0, ms: 0, tokens: 0, errors: 0 });
193
+ bt.calls += 1; bt.ms += c.durationMs || 0; bt.tokens += c.outputTokens || 0;
194
+ if (isHuman) {
195
+ humanWaitMs += c.durationMs || 0; // human time is NOT agent/tool work
196
+ } else {
197
+ const b = byBackend[c.backend] || (byBackend[c.backend] = { calls: 0, ms: 0 });
198
+ b.calls += 1; b.ms += c.durationMs || 0;
199
+ toolMs += c.durationMs || 0;
200
+ }
201
+ if (c.ok === false) { bt.errors += 1; errors += 1; }
202
+ if ((c.outputBytes || 0) < 2) empty += 1;
203
+ byQueryClass[c.queryClass] = (byQueryClass[c.queryClass] || 0) + 1;
204
+ sigCount[c.signature] = (sigCount[c.signature] || 0) + 1;
205
+ if (c.queryClass === 'file-read' && c.path) pathReads[c.path] = (pathReads[c.path] || 0) + 1;
206
+ }
207
+ const duplicates = [];
208
+ const seen = new Set();
209
+ for (const c of tc) {
210
+ if (seen.has(c.signature)) continue;
211
+ seen.add(c.signature);
212
+ if (sigCount[c.signature] > 1) duplicates.push({ tool: c.tool, queryClass: c.queryClass, count: sigCount[c.signature], preview: c.inputPreview });
213
+ }
214
+ const repeatedReads = Object.entries(pathReads).filter(([, n]) => n > 1).map(([p, n]) => ({ path: p, count: n }));
215
+ // longest no-progress streak: consecutive calls that were empty/failed/duplicate
216
+ let streak = 0; let best = 0;
217
+ for (const c of tc) {
218
+ const bad = c.ok === false || (c.outputBytes || 0) < 2 || sigCount[c.signature] > 1;
219
+ streak = bad ? streak + 1 : 0;
220
+ if (streak > best) best = streak;
221
+ }
222
+ const cumulativeInput = [];
223
+ let acc = 0;
224
+ for (const u of session.usages) { acc += u.input; cumulativeInput.push(u.input); }
225
+ const topByMs = [...tc].sort((a, b) => (b.durationMs || 0) - (a.durationMs || 0)).slice(0, 5).map(c => ({ tool: c.tool, ms: c.durationMs, ok: c.ok, preview: c.inputPreview }));
226
+ const topByTokens = [...tc].sort((a, b) => (b.outputTokens || 0) - (a.outputTokens || 0)).slice(0, 5).map(c => ({ tool: c.tool, tokens: c.outputTokens, preview: c.inputPreview }));
227
+
228
+ const wallMs = opts.wallMs != null ? opts.wallMs : session.wallMs;
229
+ const modelMs = wallMs != null ? Math.max(0, wallMs - toolMs - humanWaitMs) : null;
230
+ const blowups = cumulativeInput.map((v, i) => ({ step: i, input: v })).filter(x => x.input >= CONTEXT_BLOWUP_TOKENS).sort((a, b) => b.input - a.input);
231
+
232
+ return {
233
+ schemaVersion: SCHEMA_VERSION, bundleVersion: BUNDLE_VERSION, generatedAt: new Date().toISOString(),
234
+ workspace: opts.workspace || null, sessionId: opts.sessionId || null,
235
+ overview: {
236
+ steps: session.steps, toolCalls: tc.length, roundTrips: countRoundTrips(tc),
237
+ wallMs, modelMs, mcpMs: byBackend.graph.ms, repoToolMs: byBackend.repo.ms, toolMs, humanWaitMs,
238
+ tokensIn: session.tokensIn, tokensOut: session.tokensOut, tokensReasoning: session.tokensReasoning, tokens: session.tokens,
239
+ cost: session.cost, toolErrors: errors, emptyResults: empty,
240
+ distinctSignatures: new Set(tc.map(c => c.signature)).size,
241
+ contextBlowup: { thresholdTokens: CONTEXT_BLOWUP_TOKENS, count: blowups.length, max: blowups.length ? blowups[0].input : 0, top: blowups.slice(0, 5) },
242
+ },
243
+ byTool, byBackend, byQueryClass,
244
+ tokenGrowth: { perStepInput: cumulativeInput, steps: cumulativeInput.length },
245
+ overSearch: {
246
+ duplicateCalls: duplicates,
247
+ repeatedReads,
248
+ emptyOrError: errors + empty,
249
+ noProgressStreak: best,
250
+ },
251
+ topOffendersByTime: topByMs,
252
+ topOffendersByTokens: topByTokens,
253
+ hints: buildHints({ toolCalls: tc.length, duplicates: duplicates.length, emptyOrError: errors + empty, repeatedReads: repeatedReads.length, noProgressStreak: best, modelMs, mcpMs: byBackend.graph.ms, repoToolMs: byBackend.repo.ms, roundTrips: countRoundTrips(tc), blowups: blowups.length, blowupMax: blowups.length ? blowups[0].input : 0 }),
254
+ };
255
+ }
256
+
257
+ function buildHints(m) {
258
+ const hints = [];
259
+ if (m.blowups > 0) hints.push(`上下文尖峰 ${m.blowups} 个 step(最大 ${m.blowupMax} tokens)→ 多由大工具输出造成;优先考虑截断/分页/摘要工具输出(observation masking)、先摘要后精读(对所有场景统一生效,勿只针对单会话)。`);
260
+ if (m.duplicates > 0) hints.push(`重复/近似重复调用 ${m.duplicates} 组 → 考虑结果缓存或查询归一(同参不重搜)。`);
261
+ if (m.emptyOrError > 0) hints.push(`空结果/失败 ${m.emptyOrError} 次 → 考虑改进查询构造/回退策略,避免"空手→换词→再搜"的循环。`);
262
+ if (m.repeatedReads > 0) hints.push(`同一文件被重复读 ${m.repeatedReads} 处 → 考虑读取缓存或先摘要后精读。`);
263
+ if (m.noProgressStreak >= 3) hints.push(`最长"无进展"连续 ${m.noProgressStreak} 次 → 缺停止判据/预算,建议显式设停止条件。`);
264
+ if (m.roundTrips >= 2) hints.push(`图↔仓往返 ${m.roundTrips} 次 → 检查是否可在一次规划内并发取数。`);
265
+ if (m.modelMs != null && m.modelMs > (m.mcpMs + m.repoToolMs)) hints.push(`模型耗时主导(${m.modelMs}ms > 工具 ${(m.mcpMs + m.repoToolMs)}ms)→ 考虑上下文压缩/减少轮次。`);
266
+ if (hints.length === 0) hints.push('未发现明显过度搜索信号。');
267
+ return hints;
268
+ }
269
+
270
+ function renderDiagnosis(m, meta) {
271
+ const L = [];
272
+ L.push(`# Agent 搜索诊断报告`);
273
+ L.push('');
274
+ L.push(`- 生成时间:${m.generatedAt}`);
275
+ L.push(`- 会话:${m.sessionId || '(unknown)'} 工作区:${m.workspace || '(unknown)'}`);
276
+ L.push(`- bundle 版本:${m.bundleVersion} schema:${m.schemaVersion}`);
277
+ L.push('');
278
+ L.push(`## 概览`);
279
+ L.push('');
280
+ L.push(`| 指标 | 值 |`);
281
+ L.push(`|---|---|`);
282
+ L.push(`| 轮次 steps | ${m.overview.steps} |`);
283
+ L.push(`| 工具调用 | ${m.overview.toolCalls}(去重签名 ${m.overview.distinctSignatures}) |`);
284
+ L.push(`| 图↔仓往返 | ${m.overview.roundTrips} |`);
285
+ L.push(`| 墙钟 | ${fmtMs(m.overview.wallMs)} = 模型 ${fmtMs(m.overview.modelMs)} + MCP ${fmtMs(m.overview.mcpMs)} + 仓 ${fmtMs(m.overview.repoToolMs)} + 人类等待 ${fmtMs(m.overview.humanWaitMs)} |`);
286
+ L.push(`| tokens | 总 ${m.overview.tokens}(in ${m.overview.tokensIn} / out ${m.overview.tokensOut} / reason ${m.overview.tokensReasoning}) |`);
287
+ L.push(`| 工具失败 / 空结果 | ${m.overview.toolErrors} / ${m.overview.emptyResults} |`);
288
+ L.push('');
289
+ L.push(`## 过度搜索信号`);
290
+ L.push('');
291
+ L.push(`- 重复调用组:${m.overSearch.duplicateCalls.length}`);
292
+ for (const d of m.overSearch.duplicateCalls.slice(0, 10)) L.push(` - ×${d.count} ${d.tool} [${d.queryClass}] ${d.preview}`);
293
+ L.push(`- 重复读同一文件:${m.overSearch.repeatedReads.length}`);
294
+ for (const r of m.overSearch.repeatedReads.slice(0, 10)) L.push(` - ×${r.count} ${r.path}`);
295
+ L.push(`- 空结果/失败合计:${m.overSearch.emptyOrError}`);
296
+ L.push(`- 最长无进展连续:${m.overSearch.noProgressStreak}`);
297
+ L.push('');
298
+ L.push(`## 后端 / 查询类分布`);
299
+ L.push('');
300
+ L.push(`- 后端:` + Object.entries(m.byBackend).map(([k, v]) => `${k}=${v.calls}`).join(' '));
301
+ L.push(`- 查询类:` + Object.entries(m.byQueryClass).map(([k, v]) => `${k}=${v}`).join(' '));
302
+ L.push('');
303
+ L.push(`## 最贵调用(按耗时)`);
304
+ L.push('');
305
+ for (const c of m.topOffendersByTime) L.push(`- ${fmtMs(c.ms)} ${c.tool}${c.ok ? '' : ' (error)'} ${c.preview}`);
306
+ L.push('');
307
+ L.push(`## token 随轮次`);
308
+ L.push('');
309
+ L.push(`每步 input tokens(累计上下文规模):${m.tokenGrowth.perStepInput.join(', ') || '(无)'}`);
310
+ L.push('');
311
+ const cb = m.overview.contextBlowup || { count: 0, max: 0, top: [] };
312
+ L.push(`## 上下文尖峰(≥ ${cb.thresholdTokens} tokens 的 step)`);
313
+ L.push('');
314
+ L.push(`- 尖峰数:${cb.count} 最大:${cb.max} tokens`);
315
+ for (const b of cb.top) L.push(` - step ${b.step}: ${b.input} input tokens`);
316
+ L.push('');
317
+ L.push(`## 诊断建议(启发式,供 Agent 复核)`);
318
+ L.push('');
319
+ for (const h of m.hints) L.push(`- ${h}`);
320
+ L.push('');
321
+ L.push(`---`);
322
+ L.push(`> 本报告由 agentSearchDiagnose 自动生成;请 Agent 结合 metrics.json 与会话片段复核并补充解读。`);
323
+ L.push('');
324
+ return L.join('\n');
325
+ }
326
+
327
+ function fmtMs(ms) {
328
+ if (ms == null) return 'n/a';
329
+ return ms >= 1000 ? `${(ms / 1000).toFixed(1)}s` : `${ms}ms`;
330
+ }
331
+
332
+ function writeBundle(opts) {
333
+ const workspace = opts.workspace || process.cwd();
334
+ const rawInput = fs.readFileSync(opts.session, 'utf8');
335
+ const sessionText = isExportJson(rawInput) ? exportToNdjson(rawInput) : rawInput;
336
+ const session = parseSession(sessionText);
337
+ const sessionId = opts.sessionId || inferSessionId(sessionText) || 'session';
338
+ const outDir = opts.out || path.join(workspace, '.argo', 'temp', 'diagnosis', sessionId);
339
+ fs.mkdirSync(outDir, { recursive: true });
340
+
341
+ const costLogPath = opts.costLog || path.join(workspace, '.argo', 'temp', 'agent-cost-log.ndjson');
342
+ const costLogText = readMaybe(costLogPath);
343
+
344
+ const metrics = diagnose(session, { workspace, sessionId, wallMs: opts.wallMs });
345
+ const files = [];
346
+ const write = (name, body) => { const p = path.join(outDir, name); fs.writeFileSync(p, body); files.push({ path: name, bytes: Buffer.byteLength(body) }); };
347
+
348
+ write('session.ndjson', sessionText);
349
+ write('cost-log.slice.ndjson', sliceCostLog(costLogText, sessionId));
350
+ write('metrics.json', JSON.stringify(metrics, null, 2) + '\n');
351
+ write('diagnosis.md', renderDiagnosis(metrics, { costLogPath }));
352
+
353
+ const manifest = {
354
+ schemaVersion: SCHEMA_VERSION, bundleVersion: BUNDLE_VERSION, generatedAt: metrics.generatedAt,
355
+ workspace, sessionId, sources: { session: path.resolve(opts.session), costLog: costLogPath },
356
+ files,
357
+ };
358
+ fs.writeFileSync(path.join(outDir, 'manifest.json'), JSON.stringify(manifest, null, 2) + '\n');
359
+ return { outDir, metrics, manifest };
360
+ }
361
+
362
+ function readMaybe(file) { try { return fs.readFileSync(file, 'utf8'); } catch (_) { return ''; } }
363
+
364
+ function inferSessionId(text) {
365
+ const m = String(text).match(/"sessionID"\s*:\s*"([^"]+)"/);
366
+ return m ? m[1] : null;
367
+ }
368
+
369
+ function sliceCostLog(text, sessionId) {
370
+ if (!text) return '';
371
+ const lines = text.split('\n').filter(Boolean);
372
+ const hit = lines.filter(l => !sessionId || l.includes(sessionId));
373
+ return (hit.length ? hit : []).join('\n') + (hit.length ? '\n' : '');
374
+ }
375
+
376
+ function parseArgs(argv) {
377
+ const a = { session: null, sessionId: null, costLog: null, workspace: process.cwd(), out: null, json: false };
378
+ for (let i = 0; i < argv.length; i++) {
379
+ const k = argv[i];
380
+ if (k === '--session') a.session = argv[++i];
381
+ else if (k === '--session-id') a.sessionId = argv[++i];
382
+ else if (k === '--cost-log') a.costLog = argv[++i];
383
+ else if (k === '--workspace') a.workspace = argv[++i];
384
+ else if (k === '--out') a.out = argv[++i];
385
+ else if (k === '--json') a.json = true;
386
+ }
387
+ return a;
388
+ }
389
+
390
+ function main(argv) {
391
+ const args = parseArgs(argv || process.argv.slice(2));
392
+ if (!args.session || !fs.existsSync(args.session)) {
393
+ console.error('agentSearchDiagnose: --session <session.ndjson> is required');
394
+ return 2;
395
+ }
396
+ const { outDir, metrics, manifest } = writeBundle(args);
397
+ if (args.json) { console.log(JSON.stringify({ outDir, overview: metrics.overview, hints: metrics.hints }, null, 2)); return 0; }
398
+ console.log(`diagnosis bundle -> ${outDir}`);
399
+ console.log(`files: ${manifest.files.map(f => f.path).join(', ')}`);
400
+ console.log(`overview: steps=${metrics.overview.steps} tools=${metrics.overview.toolCalls} roundTrips=${metrics.overview.roundTrips} tokens=${metrics.overview.tokens} model=${fmtMs(metrics.overview.modelMs)} mcp=${fmtMs(metrics.overview.mcpMs)} repo=${fmtMs(metrics.overview.repoToolMs)}`);
401
+ for (const h of metrics.hints) console.log(`hint: ${h}`);
402
+ return 0;
403
+ }
404
+
405
+ module.exports = { BUNDLE_VERSION, SCHEMA_VERSION, parseSession, classifyQuery, backendOf, signature, diagnose, renderDiagnosis, writeBundle, sliceCostLog, isExportJson, exportToNdjson, main };
406
+
407
+ if (require.main === module) process.exit(main());