archgraph-argo-beta 0.27.0-beta.11 → 0.27.0-beta.13

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.
@@ -134,7 +134,7 @@ const TOOLS = [
134
134
  },
135
135
  {
136
136
  name: 'getIntentElementContext',
137
- description: 'read-only query that returns an intent subgraph context for one element. Uses ArchiMate semantic dependency traversal with dependencyDepth and dependentDepth, preserving native subgraph elements, relationships, and views.',
137
+ description: 'read-only query that returns an intent subgraph context for one element. Uses ArchiMate semantic dependency traversal with dependencyDepth and dependentDepth, preserving native subgraph elements, relationships, and views. Output is bounded by maxBytes (default ARGO_CONTEXT_MAX_BYTES or 32000): beyond it non-focus members degrade to identity (id/type/name) with a complete id manifest under truncation, so the host never silently cuts the payload. On a large/hub element leave includeAttributes/includeTestcases off and prefer queryNeo4jGraph to locate ids, then read them narrowly.',
138
138
  inputSchema: intentElementContextInputSchema(),
139
139
  },
140
140
  {
@@ -149,18 +149,17 @@ const TOOLS = [
149
149
  },
150
150
  {
151
151
  name: 'addArchitectureElement',
152
- description: 'Use for one element. Creates a new element or adds an existing element to view_ids. view_ids is required so elements never exist outside views. element.id is REQUIRED: a non-empty, caller-assigned, stable string — there is no auto-id (reuse an existing id, or allocate the next one from the graph).',
152
+ description: 'Use for one element. Creates a new element or adds an existing element to view_ids. view_ids is required so elements never exist outside views. element.id is OPTIONAL: omit it and the server auto-allocates a unique id (returned in the result); provide it to pin a specific id (must not collide with a different element).',
153
153
  inputSchema: {
154
154
  type: 'object',
155
155
  required: ['element', 'view_ids'],
156
156
  properties: {
157
157
  element: {
158
158
  type: 'object',
159
- required: ['id'],
160
159
  properties: {
161
- id: { type: 'string', minLength: 1, description: 'Element id (non-empty, caller-assigned, stable). REQUIRED — the graph is written by id and there is NO auto-id: reuse an existing id (onConflict:"reuse" with the same (type,name)) or allocate the next one (e.g. MATCH (e:Element {graphKey:$graphKey}) RETURN max(toInteger(e.id))).' },
160
+ id: { type: 'string', description: 'Element id (OPTIONAL). Omit to let the server auto-allocate a unique id (a semantic slug from the name, e.g. "graph-wiki-federation-center", suffixed -002.. if taken). If provided it must not collide with a DIFFERENT element (a same (type,name) match is idempotent reuse).' },
162
161
  },
163
- description: 'The element to create/attach. MUST include a non-empty `id`.',
162
+ description: 'The element to create/attach. `id` is optional — omit it and the server allocates one (returned in the result).',
164
163
  },
165
164
  view_ids: { type: 'array', minItems: 1, items: { type: 'string' } },
166
165
  onConflict: { type: 'string', enum: ['reuse', 'allowDuplicate'], description: 'Dedup policy (default reuse). reuse: find-or-create — attach an existing exact (type, name) match; a same-type semantic near-duplicate also blocks creation. allowDuplicate: create anyway (even if a duplicate exists), requires a justification.' },
@@ -200,7 +199,7 @@ const TOOLS = [
200
199
  },
201
200
  {
202
201
  name: 'addArchitectureRelationship',
203
- description: 'Use for one relationship. Creates a new relationship or adds an existing relationship to view_ids. relationship.type is the ArchiMate 3.2 relationship type and is validated against endpoint element types.',
202
+ description: 'Use for one relationship. Creates a new relationship or adds an existing relationship to view_ids. relationship.type is the ArchiMate 3.2 relationship type and is validated against endpoint element types. relationship.id is OPTIONAL: omit it and the server auto-allocates a unique id (returned in the result).',
204
203
  inputSchema: {
205
204
  type: 'object',
206
205
  required: ['relationship', 'view_ids'],
@@ -244,7 +243,7 @@ const TOOLS = [
244
243
  },
245
244
  {
246
245
  name: 'addArchitectureView',
247
- description: 'Use for one view. The graph must have exactly one top-level view named SystemArchitecture; all sub-views must attach to an element with parent_element_id.',
246
+ description: 'Use for one view. The graph must have exactly one top-level view named SystemArchitecture; all sub-views must attach to an element with parent_element_id. view.view_id is OPTIONAL: omit it and the server auto-allocates a unique view_id (returned in the result).',
248
247
  inputSchema: {
249
248
  type: 'object',
250
249
  required: ['view'],
@@ -344,8 +343,9 @@ function intentElementContextInputSchema() {
344
343
  dependentDepth: { type: 'number', description: 'Default: 1. Semantic dependents that rely on the focus element.' },
345
344
  associationDepth: { type: 'number', description: 'Default: 1. Association neighbors are expanded at least one layer.' },
346
345
  associationNeighborDependencyDepth: { type: 'number', description: 'Default: 0. Optional dependency expansion from association neighbors.' },
347
- includeAttributes: { type: 'boolean', description: 'Default: false. Include `attributes` (commit/session/release ledgers) verbatim; omitted by default from this structural read (the focus element always keeps its own).' },
348
- includeTestcases: { type: 'boolean', description: 'Default: false. Include member `testcases` verbatim; omitted by default from this structural read.' },
346
+ includeAttributes: { type: 'boolean', description: 'Default: false. Include `attributes` (commit/session/release ledgers) verbatim; omitted by default from this structural read (the focus element always keeps its own). On a hub element this ledger can dominate the payload.' },
347
+ includeTestcases: { type: 'boolean', description: 'Default: false. Include member `testcases` verbatim; omitted by default from this structural read. On a hub element this can be large.' },
348
+ maxBytes: { type: 'number', description: 'Optional output budget in UTF-8 bytes. Default: ARGO_CONTEXT_MAX_BYTES env or 32000. 0 = unlimited. Above the budget, non-focus members degrade to identity (id/type/name) with a complete id manifest under `truncation`; the payload is never silently truncated by the host.' },
349
349
  },
350
350
  additionalProperties: false,
351
351
  };
@@ -101,6 +101,7 @@ const HOST_ONLY_ENV_KEYS = Object.freeze([
101
101
  'ARGO_SEMANTIC_DEDUP_THRESHOLD',
102
102
  'ARGO_COST_PROFILER',
103
103
  'ARGO_COST_TRACE_MAX_BYTES',
104
+ 'ARGO_CONTEXT_MAX_BYTES',
104
105
  ]);
105
106
  const PROHIBITED_RUNTIME_FIELD_KEYS = Object.freeze(['neo4jUri', 'embeddingCredential']);
106
107
  const SECRET_KEYS = new Set(['ARGO_NEO4J_DATABASE_PASSWORD', 'QWEN_KEY', 'ARGO_RERANK_API_KEY', EMBEDDING_API_KEY_KEY]);
@@ -227,12 +227,12 @@ const TOOLS = [
227
227
  },
228
228
  {
229
229
  name: 'getIntentElementContext',
230
- description: 'read-only query that returns an intent subgraph context for one element. Uses ArchiMate semantic dependency traversal with dependencyDepth and dependentDepth, preserving native subgraph elements, relationships, and views.',
230
+ description: 'read-only query that returns an intent subgraph context for one element. Uses ArchiMate semantic dependency traversal with dependencyDepth and dependentDepth, preserving native subgraph elements, relationships, and views. Output is bounded by maxBytes (default ARGO_CONTEXT_MAX_BYTES or 32000): beyond it non-focus members degrade to identity (id/type/name) and a complete id manifest is returned under truncation, so the host never silently cuts the payload. On a large/hub element leave includeAttributes/includeTestcases off (they are the ledger and can dominate the size) and prefer queryNeo4jGraph to locate ids, then read them narrowly.',
231
231
  inputSchema: intentElementContextInputSchema(),
232
232
  },
233
233
  {
234
234
  name: 'getArchitectureViewContext',
235
- description: 'read-only query that resolves one view by view_id into its complete membership: the view object, every member element (from included_elements), every member relationship (from included_relationships), the parent element, and optionally child sub-views declared by member elements. Resolves ids into full canonical objects instead of returning raw id lists. Optional includeEaGeometry (default false) additionally returns the EA diagram geometry of the resolved view: element boxes plus each connector ROUTE (t_diagramlinks.Path as `path` + parsed `points`, with the non-route Geometry override kept separately under `geometry`).',
235
+ description: 'read-only query that resolves one view by view_id into its complete membership: the view object, every member element (from included_elements), every member relationship (from included_relationships), the parent element, and optionally child sub-views declared by member elements. Resolves ids into full canonical objects instead of returning raw id lists. Output is bounded by maxBytes (default ARGO_CONTEXT_MAX_BYTES or 32000): beyond it members degrade to identity (id/type/name) with a complete id manifest under truncation. Optional includeEaGeometry (default false) additionally returns the EA diagram geometry of the resolved view: element boxes plus each connector ROUTE (t_diagramlinks.Path as `path` + parsed `points`, with the non-route Geometry override kept separately under `geometry`).',
236
236
  inputSchema: viewContextInputSchema(),
237
237
  },
238
238
  {
@@ -247,18 +247,17 @@ const TOOLS = [
247
247
  },
248
248
  {
249
249
  name: 'addArchitectureElement',
250
- description: 'Use for one element. Creates a new element or adds an existing element to view_ids. view_ids is required so elements never exist outside views. element.id is REQUIRED: a non-empty, caller-assigned, stable string — there is no auto-id (reuse an existing id, or allocate the next one from the graph). Set dryRun to preview without writing.',
250
+ description: 'Use for one element. Creates a new element or adds an existing element to view_ids. view_ids is required so elements never exist outside views. element.id is OPTIONAL: omit it and the server auto-allocates a unique id (returned in the result); provide it to pin a specific id (must not collide with a different element). Set dryRun to preview without writing.',
251
251
  inputSchema: {
252
252
  type: 'object',
253
253
  required: ['element', 'view_ids'],
254
254
  properties: {
255
255
  element: {
256
256
  type: 'object',
257
- required: ['id'],
258
257
  properties: {
259
- id: { type: 'string', minLength: 1, description: 'Element id (non-empty, caller-assigned, stable). REQUIRED — the graph is written by id and there is NO auto-id: reuse an existing id (onConflict:"reuse" with the same (type,name)) or allocate the next one (e.g. MATCH (e:Element {graphKey:$graphKey}) RETURN max(toInteger(e.id))).' },
258
+ id: { type: 'string', description: 'Element id (OPTIONAL). Omit to let the server auto-allocate a unique id (a semantic slug from the name, e.g. "graph-wiki-federation-center", suffixed -002.. if taken). If provided it must not collide with a DIFFERENT element (a same (type,name) match is idempotent reuse).' },
260
259
  },
261
- description: 'The element to create/attach. MUST include a non-empty `id`.',
260
+ description: 'The element to create/attach. `id` is optional — omit it and the server allocates one (returned in the result).',
262
261
  },
263
262
  view_ids: { type: 'array', minItems: 1, items: { type: 'string' } },
264
263
  onConflict: { type: 'string', enum: ['reuse', 'allowDuplicate'], description: 'Dedup policy (default reuse). reuse: find-or-create — attach an existing exact (type, name) match; a same-type semantic near-duplicate also blocks creation. allowDuplicate: create anyway (even if a duplicate exists), requires a justification.' },
@@ -301,7 +300,7 @@ const TOOLS = [
301
300
  },
302
301
  {
303
302
  name: 'addArchitectureRelationship',
304
- description: 'Use for one relationship. Creates a new relationship or adds an existing relationship to view_ids. relationship.type is the ArchiMate 3.2 relationship type and is validated against endpoint element types. Set dryRun to preview without writing.',
303
+ description: 'Use for one relationship. Creates a new relationship or adds an existing relationship to view_ids. relationship.type is the ArchiMate 3.2 relationship type and is validated against endpoint element types. relationship.id is OPTIONAL: omit it and the server auto-allocates a unique id (returned in the result). Set dryRun to preview without writing.',
305
304
  inputSchema: {
306
305
  type: 'object',
307
306
  required: ['relationship', 'view_ids'],
@@ -348,7 +347,7 @@ const TOOLS = [
348
347
  },
349
348
  {
350
349
  name: 'addArchitectureView',
351
- description: 'Use for one view. The graph must have exactly one top-level view named SystemArchitecture; all sub-views must attach to an element with parent_element_id. Set dryRun to preview without writing.',
350
+ description: 'Use for one view. The graph must have exactly one top-level view named SystemArchitecture; all sub-views must attach to an element with parent_element_id. view.view_id is OPTIONAL: omit it and the server auto-allocates a unique view_id (returned in the result). Set dryRun to preview without writing.',
352
351
  inputSchema: {
353
352
  type: 'object',
354
353
  required: ['view'],
@@ -484,8 +483,9 @@ function intentElementContextInputSchema() {
484
483
  dependentDepth: { type: 'number', description: 'Default: 1. Semantic dependents that rely on the focus element.' },
485
484
  associationDepth: { type: 'number', description: 'Default: 1. Association neighbors are expanded at least one layer.' },
486
485
  associationNeighborDependencyDepth: { type: 'number', description: 'Default: 0. Optional dependency expansion from association neighbors.' },
487
- includeAttributes: { type: 'boolean', description: 'Default: false. Include `attributes` (commit/session/release ledgers) verbatim. Omitted by default from this structural read; the focus element always keeps its own. Semantic retrieval embeds attributes, so semantic hits keep them.' },
488
- includeTestcases: { type: 'boolean', description: 'Default: false. Include member `testcases` verbatim. Omitted by default from this structural read (bookkeeping); pass true when you need acceptance cases. Semantic retrieval embeds testcase descriptions, so semantic hits keep them.' },
486
+ includeAttributes: { type: 'boolean', description: 'Default: false. Include `attributes` (commit/session/release ledgers) verbatim. Omitted by default from this structural read; the focus element always keeps its own. Semantic retrieval embeds attributes, so semantic hits keep them. On a hub element this ledger can dominate the payload — prefer leaving it off and reading bookkeeping narrowly.' },
487
+ includeTestcases: { type: 'boolean', description: 'Default: false. Include member `testcases` verbatim. Omitted by default from this structural read (bookkeeping); pass true when you need acceptance cases. Semantic retrieval embeds testcase descriptions, so semantic hits keep them. On a hub element this can be large — prefer leaving it off.' },
488
+ maxBytes: { type: 'number', description: 'Optional output budget in UTF-8 bytes (the exact serialized response). Default: ARGO_CONTEXT_MAX_BYTES env or 32000. 0 = unlimited. When the payload exceeds the budget, non-focus members degrade to identity (id/type/name) and a complete id manifest is returned under `truncation` — the payload is never silently truncated by the host.' },
489
489
  },
490
490
  additionalProperties: false,
491
491
  };
@@ -503,6 +503,7 @@ function viewContextInputSchema() {
503
503
  includeAttributes: { type: 'boolean', description: 'Default: false. Include member/relationship `attributes` (commit/session/release ledgers) verbatim. Omitted by default from this structural read (bookkeeping); pass true when you need provenance.' },
504
504
  includeTestcases: { type: 'boolean', description: 'Default: false. Include member `testcases` verbatim. Omitted by default from this structural read; pass true for acceptance-case lookups.' },
505
505
  includeEaGeometry: { type: 'boolean', description: 'Default: false (opt-in). When true, additionally resolve the diagram GEOMETRY (element boxes + connector line routes) for this view from the workspace EA model (.qea) and return it under a `geometry` field aligned by schema id with the resolved members. Each geometry relationship carries: `path` (the EA route from t_diagramlinks.Path, "" when EA auto-routes), `points` (the parsed [{x,y}] waypoints), `edge` (the EDGE route-style token or null) and `geometry` (the raw SX/SY/EX/EY override string, which contains NO waypoints). By default the EA model is never touched and no `geometry` field is returned; a missing EA model/diagram yields geometry.present=false, never an error.' },
506
+ maxBytes: { type: 'number', description: 'Optional output budget in UTF-8 bytes (the exact serialized response). Default: ARGO_CONTEXT_MAX_BYTES env or 32000. 0 = unlimited. When the payload exceeds the budget, members degrade to identity (id/type/name) and a complete id manifest is returned under `truncation` — the payload is never silently truncated by the host.' },
506
507
  },
507
508
  additionalProperties: false,
508
509
  };
@@ -687,6 +688,217 @@ function buildAgentProjection(omitted) {
687
688
  };
688
689
  }
689
690
 
691
+ // ---------------------------------------------------------------------------
692
+ // Context output budget (bounded, well-formed structural reads)
693
+ // ---------------------------------------------------------------------------
694
+ // A hub element/view can expand a semantic subgraph to tens of KB, which the
695
+ // HOST then cuts mid-JSON — the agent receives a malformed partial observation.
696
+ // This budget makes the ceiling the framework's, not the host's: above maxBytes
697
+ // the non-focus members degrade to identity (id/type/name), the focus element +
698
+ // boundary/explorationHints are kept, and EVERY included id is listed under
699
+ // `truncation` — so the payload is always valid JSON and always navigable.
700
+ // Default (or ARGO_CONTEXT_MAX_BYTES); 0 = unlimited. Semantic retrieval is NOT
701
+ // affected (only these two structural builders).
702
+ const DEFAULT_CONTEXT_MAX_BYTES = 32000;
703
+ const CONTEXT_BUDGET_NOTE =
704
+ 'The full payload exceeded maxBytes, so non-focus members are reduced to identity '
705
+ + '(id/type/name). The focus element and boundary/explorationHints are kept and every '
706
+ + 'included id is listed here. Raise maxBytes (0 = unlimited) or narrow the traversal '
707
+ + '(dependencyDepth/dependentDepth) to read details.';
708
+
709
+ function resolveContextMaxBytes(args = {}) {
710
+ const raw = args && args.maxBytes !== undefined ? args.maxBytes : process.env.ARGO_CONTEXT_MAX_BYTES;
711
+ if (raw === undefined || raw === null || raw === '') {
712
+ return DEFAULT_CONTEXT_MAX_BYTES;
713
+ }
714
+ const numeric = Number(raw);
715
+ if (!Number.isFinite(numeric) || numeric < 0) {
716
+ return DEFAULT_CONTEXT_MAX_BYTES;
717
+ }
718
+ return Math.floor(numeric);
719
+ }
720
+
721
+ // Budget is measured on the EXACT serialization the caller receives
722
+ // (`toolResult` pretty-prints with 2 spaces), in UTF-8 bytes.
723
+ function payloadByteLength(value) {
724
+ try { return Buffer.byteLength(JSON.stringify(value, null, 2)); } catch (_) { return 0; }
725
+ }
726
+
727
+ function identityElementRecord(element) {
728
+ return { id: element.id, name: element.name, type: element.type };
729
+ }
730
+
731
+ function identityRelationshipRecord(relationship) {
732
+ return {
733
+ id: relationship.id,
734
+ name: relationship.name,
735
+ type: relationship.type,
736
+ source_id: relationship.source_id,
737
+ target_id: relationship.target_id,
738
+ };
739
+ }
740
+
741
+ function identityViewRecord(view) {
742
+ return { view_id: view.view_id, view_name: view.view_name };
743
+ }
744
+
745
+ function budgetTruncationBase(result, maxBytes, fullBytes, ids) {
746
+ return {
747
+ truncated: true,
748
+ reason: 'context_budget_exceeded',
749
+ maxBytes,
750
+ fullBytes,
751
+ includedElementIds: ids.elements,
752
+ includedRelationshipIds: ids.relationships,
753
+ includedViewIds: ids.views,
754
+ note: CONTEXT_BUDGET_NOTE,
755
+ };
756
+ }
757
+
758
+ // Shrink the manifest id lists (last resort) so even a pathological hub stays
759
+ // within budget. The focus id is never dropped; `manifestTruncated` records any
760
+ // real loss of a listed id.
761
+ function trimManifestToBudget(result, maxBytes) {
762
+ const truncation = result.truncation;
763
+ const arrays = ['includedElementIds', 'includedRelationshipIds', 'includedViewIds'];
764
+ const focusId = result.focusElementId;
765
+ for (let ratio = 0.9; ratio >= 0; ratio -= 0.1) {
766
+ for (const key of arrays) {
767
+ const full = truncation[key] || [];
768
+ const kept = full.slice(0, Math.ceil(full.length * ratio));
769
+ if (key === 'includedElementIds' && focusId && !kept.includes(focusId)) {
770
+ kept.unshift(focusId);
771
+ }
772
+ truncation[key] = kept;
773
+ }
774
+ truncation.manifestTruncated = true;
775
+ if (payloadByteLength(result) <= maxBytes) return;
776
+ }
777
+ truncation.manifestTruncated = true;
778
+ }
779
+
780
+ function applyContextBudget(result, maxBytes) {
781
+ if (!result || result.status !== 'passed' || !maxBytes || maxBytes <= 0) {
782
+ return result;
783
+ }
784
+ const fullBytes = payloadByteLength(result);
785
+ if (fullBytes <= maxBytes) {
786
+ return result;
787
+ }
788
+
789
+ const subgraph = result.subgraph || {};
790
+ const elements = Array.isArray(subgraph.elements) ? subgraph.elements : [];
791
+ const relationships = Array.isArray(subgraph.relationships) ? subgraph.relationships : [];
792
+ const views = Array.isArray(subgraph.views) ? subgraph.views : [];
793
+ const focusId = result.focusElementId;
794
+ const ids = {
795
+ elements: elements.map((entry) => entry.id),
796
+ relationships: relationships.map((entry) => entry.id),
797
+ views: views.map((entry) => entry.view_id),
798
+ };
799
+ const truncated = (tier) => budgetTruncationBase(result, maxBytes, fullBytes, ids);
800
+ const nonFocusCount = elements.filter((entry) => entry.id !== focusId).length;
801
+
802
+ const compact = {
803
+ ...result,
804
+ subgraph: {
805
+ ...subgraph,
806
+ elements: elements.map((entry) => (entry.id === focusId ? entry : identityElementRecord(entry))),
807
+ relationships: relationships.map(identityRelationshipRecord),
808
+ views: views.map(identityViewRecord),
809
+ },
810
+ truncation: { ...truncated('identity'), omittedElementDetails: nonFocusCount },
811
+ };
812
+ if (payloadByteLength(compact) <= maxBytes) {
813
+ return compact;
814
+ }
815
+
816
+ const idsOnly = {
817
+ ...result,
818
+ subgraph: {
819
+ ...subgraph,
820
+ elements: elements.map((entry) => (entry.id === focusId ? entry : { id: entry.id })),
821
+ relationships: relationships.map((entry) => ({ id: entry.id })),
822
+ views: views.map((entry) => ({ view_id: entry.view_id })),
823
+ },
824
+ truncation: truncated('ids-only'),
825
+ };
826
+ if (payloadByteLength(idsOnly) <= maxBytes) {
827
+ return idsOnly;
828
+ }
829
+
830
+ const manifestOnly = {
831
+ ...result,
832
+ subgraph: {
833
+ elements: elements.filter((entry) => entry.id === focusId),
834
+ relationships: [],
835
+ views: [],
836
+ },
837
+ truncation: truncated('manifest-only'),
838
+ };
839
+ trimManifestToBudget(manifestOnly, maxBytes);
840
+ return manifestOnly;
841
+ }
842
+
843
+ function applyViewContextBudget(result, maxBytes) {
844
+ if (!result || result.status !== 'passed' || !maxBytes || maxBytes <= 0) {
845
+ return result;
846
+ }
847
+ const fullBytes = payloadByteLength(result);
848
+ if (fullBytes <= maxBytes) {
849
+ return result;
850
+ }
851
+
852
+ const elements = Array.isArray(result.elements) ? result.elements : [];
853
+ const relationships = Array.isArray(result.relationships) ? result.relationships : [];
854
+ const childViews = Array.isArray(result.childViews) ? result.childViews : [];
855
+ const ids = {
856
+ elements: elements.map((entry) => entry.id),
857
+ relationships: relationships.map((entry) => entry.id),
858
+ views: childViews.map((entry) => entry.view_id),
859
+ };
860
+ const strippedView = result.view
861
+ ? { ...result.view, included_elements: [], included_relationships: [] }
862
+ : result.view;
863
+ const truncated = (tier) => ({ ...budgetTruncationBase(result, maxBytes, fullBytes, ids), tier });
864
+
865
+ const compact = {
866
+ ...result,
867
+ elements: elements.map(identityElementRecord),
868
+ relationships: relationships.map(identityRelationshipRecord),
869
+ parentElement: result.parentElement ? identityElementRecord(result.parentElement) : result.parentElement,
870
+ childViews: childViews.map(identityViewRecord),
871
+ truncation: { ...truncated('identity'), omittedElementDetails: elements.length },
872
+ };
873
+ if (payloadByteLength(compact) <= maxBytes) {
874
+ return compact;
875
+ }
876
+
877
+ const idsOnly = {
878
+ ...result,
879
+ elements: elements.map((entry) => ({ id: entry.id })),
880
+ relationships: relationships.map((entry) => ({ id: entry.id })),
881
+ parentElement: result.parentElement ? { id: result.parentElement.id } : result.parentElement,
882
+ childViews: childViews.map((entry) => ({ view_id: entry.view_id })),
883
+ truncation: truncated('ids-only'),
884
+ };
885
+ if (payloadByteLength(idsOnly) <= maxBytes) {
886
+ return idsOnly;
887
+ }
888
+
889
+ const manifestOnly = {
890
+ ...result,
891
+ view: strippedView,
892
+ elements: [],
893
+ relationships: [],
894
+ parentElement: null,
895
+ childViews: [],
896
+ truncation: truncated('manifest-only'),
897
+ };
898
+ trimManifestToBudget(manifestOnly, maxBytes);
899
+ return manifestOnly;
900
+ }
901
+
690
902
  function buildIntentElementContext(context, args = {}) {
691
903
  const profile = args.profile || 'generic-agent';
692
904
  const focusResult = resolveFocusElement(context.document, args);
@@ -813,7 +1025,7 @@ function buildIntentElementContext(context, args = {}) {
813
1025
  };
814
1026
  const projection = buildAgentProjection(omitted);
815
1027
  if (projection) result.projection = projection;
816
- return result;
1028
+ return applyContextBudget(result, resolveContextMaxBytes(args));
817
1029
  }
818
1030
 
819
1031
  // ---------------------------------------------------------------------------
@@ -957,7 +1169,7 @@ function buildViewContext(context, args = {}) {
957
1169
  }
958
1170
  const projection = buildAgentProjection(omitted);
959
1171
  if (projection) result.projection = projection;
960
- return result;
1172
+ return applyViewContextBudget(result, resolveContextMaxBytes(args));
961
1173
  }
962
1174
 
963
1175
  function resolveFocusElement(document, args) {
@@ -1623,19 +1835,30 @@ function applyMutations(document, mutations, options = {}) {
1623
1835
  if (mutation.type === 'addElement') {
1624
1836
  requireObject(mutation.element, 'mutation.element');
1625
1837
  const scopedViews = requireViewScope(nextDocument.views, mutation.view_ids, 'mutation.view_ids');
1626
- if (typeof mutation.element.id !== 'string' || mutation.element.id === '') {
1627
- // Actionable: the caller must supply a stable id (issue #8). Not a generic
1628
- // requireId message — say what is missing and how to get one.
1629
- throw new Error(
1630
- "addElement requires element.id: a non-empty, caller-assigned, stable string. There is no auto-id — set `id` explicitly: " +
1631
- "reuse an existing element's id with onConflict:'reuse' (matched by the same (type,name)), or allocate the next id " +
1632
- '(e.g. MATCH (e:Element {graphKey:$graphKey}) RETURN max(toInteger(e.id))).',
1633
- );
1634
- }
1635
- const existingElement = findById(nextDocument.elements, mutation.element.id);
1636
- let targetElementId = mutation.element.id;
1637
- let reusedElement = false;
1638
- if (!existingElement) {
1838
+ const requestedElementId = typeof mutation.element.id === 'string' && mutation.element.id !== ''
1839
+ ? mutation.element.id
1840
+ : null;
1841
+ let targetElementId;
1842
+ let elementCreated = false;
1843
+ let elementReused = false;
1844
+
1845
+ const existingById = requestedElementId ? findById(nextDocument.elements, requestedElementId) : undefined;
1846
+ if (existingById) {
1847
+ // An explicit id that already exists: idempotent ONLY if it is the same
1848
+ // (type,name). Otherwise the caller picked a taken id — fail loudly instead
1849
+ // of silently attaching an unrelated element (issue #8 collision safety).
1850
+ const sameIdentity = existingById.type === mutation.element.type
1851
+ && normalizeDedupName(existingById.name) === normalizeDedupName(mutation.element.name);
1852
+ if (!sameIdentity) {
1853
+ throw new Error(
1854
+ `addElement id '${requestedElementId}' is already used by a different element `
1855
+ + `(type '${existingById.type}', name '${existingById.name}'). Choose another id (or omit id to auto-allocate one), `
1856
+ + `attach the existing element by using its id, or update it with updateArchitectureElement.`,
1857
+ );
1858
+ }
1859
+ targetElementId = requestedElementId;
1860
+ elementReused = true;
1861
+ } else {
1639
1862
  const candidates = findDuplicateElements(nextDocument.elements, mutation.element);
1640
1863
  const resolution = resolveDuplicateConflict({
1641
1864
  onConflict: mutation.onConflict,
@@ -1644,12 +1867,19 @@ function applyMutations(document, mutations, options = {}) {
1644
1867
  }, candidates);
1645
1868
  if (resolution.action === 'reuse') {
1646
1869
  targetElementId = resolution.existing.id;
1647
- reusedElement = true;
1870
+ elementReused = true;
1648
1871
  } else {
1649
- nextDocument.elements.push(clone(mutation.element));
1650
- syncViewsToElementSubdiagramViews(nextDocument, findById(nextDocument.elements, mutation.element.id));
1872
+ targetElementId = requestedElementId || allocateUniqueId(
1873
+ nextDocument.elements.map(entry => entry.id),
1874
+ mutation.element.name,
1875
+ slugifyId(mutation.element.type) || 'element',
1876
+ );
1877
+ nextDocument.elements.push({ ...clone(mutation.element), id: targetElementId });
1878
+ syncViewsToElementSubdiagramViews(nextDocument, findById(nextDocument.elements, targetElementId));
1879
+ elementCreated = true;
1651
1880
  }
1652
1881
  }
1882
+
1653
1883
  for (const view of scopedViews) {
1654
1884
  view.included_elements = addUnique(view.included_elements || [], [targetElementId]);
1655
1885
  touchedViewIds.add(view.view_id);
@@ -1660,8 +1890,10 @@ function applyMutations(document, mutations, options = {}) {
1660
1890
  type: mutation.type,
1661
1891
  id: targetElementId,
1662
1892
  view_ids: mutation.view_ids,
1663
- created: !existingElement && !reusedElement,
1664
- ...(reusedElement ? { reused: true, reusedId: targetElementId, requestedId: mutation.element.id } : {}),
1893
+ created: elementCreated,
1894
+ ...(elementReused ? { reused: true, reusedId: targetElementId } : {}),
1895
+ ...(requestedElementId === null && elementCreated ? { allocatedId: targetElementId } : {}),
1896
+ ...(elementReused && requestedElementId && requestedElementId !== targetElementId ? { requestedId: requestedElementId } : {}),
1665
1897
  });
1666
1898
  continue;
1667
1899
  }
@@ -1760,13 +1992,35 @@ function applyMutations(document, mutations, options = {}) {
1760
1992
  if (mutation.type === 'addRelationship') {
1761
1993
  requireObject(mutation.relationship, 'mutation.relationship');
1762
1994
  const scopedViews = requireViewScope(nextDocument.views, mutation.view_ids, 'mutation.view_ids');
1763
- requireId(mutation.relationship.id, 'mutation.relationship.id');
1764
- const existingRelationship = findById(nextDocument.relationships, mutation.relationship.id);
1765
- let targetRelationshipId = mutation.relationship.id;
1995
+ const requestedRelationshipId = typeof mutation.relationship.id === 'string' && mutation.relationship.id !== ''
1996
+ ? mutation.relationship.id
1997
+ : null;
1998
+ let targetRelationshipId;
1766
1999
  let sourceElementId = mutation.relationship.source_id;
1767
2000
  let targetEndpointId = mutation.relationship.target_id;
1768
- let reusedRelationship = false;
1769
- if (!existingRelationship) {
2001
+ let relationshipCreated = false;
2002
+ let relationshipReused = false;
2003
+
2004
+ const existingById = requestedRelationshipId ? findById(nextDocument.relationships, requestedRelationshipId) : undefined;
2005
+ if (existingById) {
2006
+ // Explicit id that already exists: idempotent only for the same natural key;
2007
+ // otherwise fail loudly instead of silently attaching an unrelated edge.
2008
+ const sameIdentity = existingById.source_id === mutation.relationship.source_id
2009
+ && existingById.type === mutation.relationship.type
2010
+ && existingById.target_id === mutation.relationship.target_id
2011
+ && normalizeDedupName(existingById.name) === normalizeDedupName(mutation.relationship.name);
2012
+ if (!sameIdentity) {
2013
+ throw new Error(
2014
+ `addRelationship id '${requestedRelationshipId}' is already used by a different relationship `
2015
+ + `(source '${existingById.source_id}', type '${existingById.type}', target '${existingById.target_id}'). `
2016
+ + 'Choose another id (or omit id to auto-allocate one), or update it with updateArchitectureRelationship.',
2017
+ );
2018
+ }
2019
+ targetRelationshipId = requestedRelationshipId;
2020
+ sourceElementId = existingById.source_id;
2021
+ targetEndpointId = existingById.target_id;
2022
+ relationshipReused = true;
2023
+ } else {
1770
2024
  const candidates = findDuplicateRelationships(nextDocument.relationships, mutation.relationship);
1771
2025
  const resolution = resolveDuplicateConflict({
1772
2026
  onConflict: mutation.onConflict,
@@ -1777,9 +2031,15 @@ function applyMutations(document, mutations, options = {}) {
1777
2031
  targetRelationshipId = resolution.existing.id;
1778
2032
  sourceElementId = resolution.existing.source_id;
1779
2033
  targetEndpointId = resolution.existing.target_id;
1780
- reusedRelationship = true;
2034
+ relationshipReused = true;
1781
2035
  } else {
1782
- nextDocument.relationships.push(clone(mutation.relationship));
2036
+ targetRelationshipId = requestedRelationshipId || allocateUniqueId(
2037
+ nextDocument.relationships.map(entry => entry.id),
2038
+ mutation.relationship.name || `${mutation.relationship.source_id}-${mutation.relationship.type}-${mutation.relationship.target_id}`,
2039
+ 'relationship',
2040
+ );
2041
+ nextDocument.relationships.push({ ...clone(mutation.relationship), id: targetRelationshipId });
2042
+ relationshipCreated = true;
1783
2043
  }
1784
2044
  }
1785
2045
  for (const view of scopedViews) {
@@ -1795,8 +2055,9 @@ function applyMutations(document, mutations, options = {}) {
1795
2055
  type: mutation.type,
1796
2056
  id: targetRelationshipId,
1797
2057
  view_ids: mutation.view_ids,
1798
- created: !existingRelationship && !reusedRelationship,
1799
- ...(reusedRelationship ? { reused: true, reusedId: targetRelationshipId, requestedId: mutation.relationship.id } : {}),
2058
+ created: relationshipCreated,
2059
+ ...(relationshipReused ? { reused: true, reusedId: targetRelationshipId } : {}),
2060
+ ...(requestedRelationshipId === null && relationshipCreated ? { allocatedId: targetRelationshipId } : {}),
1800
2061
  });
1801
2062
  continue;
1802
2063
  }
@@ -1880,38 +2141,65 @@ function applyMutations(document, mutations, options = {}) {
1880
2141
 
1881
2142
  if (mutation.type === 'addView') {
1882
2143
  requireObject(mutation.view, 'mutation.view');
1883
- if (findView(nextDocument.views, mutation.view.view_id)) {
1884
- throw new Error(`View '${mutation.view.view_id}' already exists`);
1885
- }
1886
- const candidates = findDuplicateViews(nextDocument.views, mutation.view);
1887
- const resolution = resolveDuplicateConflict({
1888
- onConflict: mutation.onConflict,
1889
- justification: mutation.justification,
1890
- label: `view (name '${mutation.view.view_name}')`,
1891
- }, candidates);
1892
- if (resolution.action === 'reuse') {
1893
- mutationSummaries.push({
1894
- type: mutation.type,
1895
- id: resolution.existing.view_id,
1896
- created: false,
1897
- reused: true,
1898
- reusedId: resolution.existing.view_id,
1899
- requestedId: mutation.view.view_id,
1900
- });
1901
- } else {
1902
- const newView = clone(mutation.view);
1903
- if (Array.isArray(newView.included_elements)) {
1904
- newView.included_elements = addUnique([], newView.included_elements);
2144
+ const requestedViewId = typeof mutation.view.view_id === 'string' && mutation.view.view_id !== ''
2145
+ ? mutation.view.view_id
2146
+ : null;
2147
+ let targetViewId;
2148
+ let viewCreated = false;
2149
+ let viewReused = false;
2150
+
2151
+ const existingById = requestedViewId ? findView(nextDocument.views, requestedViewId) : undefined;
2152
+ if (existingById) {
2153
+ // Explicit view_id that already exists: idempotent only for the same
2154
+ // (parent,name); otherwise fail loudly.
2155
+ const sameIdentity = (existingById.parent_element_id || '') === (mutation.view.parent_element_id || '')
2156
+ && normalizeDedupName(existingById.view_name) === normalizeDedupName(mutation.view.view_name);
2157
+ if (!sameIdentity) {
2158
+ throw new Error(
2159
+ `addView view_id '${requestedViewId}' is already used by a different view `
2160
+ + `(name '${existingById.view_name}', parent '${existingById.parent_element_id || ''}'). `
2161
+ + 'Choose another view_id (or omit it to auto-allocate one), or update it with updateArchitectureView.',
2162
+ );
1905
2163
  }
1906
- if (Array.isArray(newView.included_relationships)) {
1907
- newView.included_relationships = addUnique([], newView.included_relationships);
2164
+ targetViewId = requestedViewId;
2165
+ viewReused = true;
2166
+ } else {
2167
+ const candidates = findDuplicateViews(nextDocument.views, mutation.view);
2168
+ const resolution = resolveDuplicateConflict({
2169
+ onConflict: mutation.onConflict,
2170
+ justification: mutation.justification,
2171
+ label: `view (name '${mutation.view.view_name}')`,
2172
+ }, candidates);
2173
+ if (resolution.action === 'reuse') {
2174
+ targetViewId = resolution.existing.view_id;
2175
+ viewReused = true;
2176
+ } else {
2177
+ targetViewId = requestedViewId || allocateUniqueId(
2178
+ nextDocument.views.map(entry => entry.view_id),
2179
+ mutation.view.view_name,
2180
+ 'view',
2181
+ );
2182
+ const newView = { ...clone(mutation.view), view_id: targetViewId };
2183
+ if (Array.isArray(newView.included_elements)) {
2184
+ newView.included_elements = addUnique([], newView.included_elements);
2185
+ }
2186
+ if (Array.isArray(newView.included_relationships)) {
2187
+ newView.included_relationships = addUnique([], newView.included_relationships);
2188
+ }
2189
+ nextDocument.views.push(newView);
2190
+ upsertSubdiagramViewIntoElement(nextDocument, newView.parent_element_id, newView);
2191
+ touchedViewIds.add(newView.view_id);
2192
+ viewLimitCheckIds.add(newView.view_id);
2193
+ viewCreated = true;
1908
2194
  }
1909
- nextDocument.views.push(newView);
1910
- upsertSubdiagramViewIntoElement(nextDocument, newView.parent_element_id, newView);
1911
- touchedViewIds.add(newView.view_id);
1912
- viewLimitCheckIds.add(newView.view_id);
1913
- mutationSummaries.push({ type: mutation.type, id: newView.view_id });
1914
2195
  }
2196
+ mutationSummaries.push({
2197
+ type: mutation.type,
2198
+ id: targetViewId,
2199
+ created: viewCreated,
2200
+ ...(viewReused ? { reused: true, reusedId: targetViewId } : {}),
2201
+ ...(requestedViewId === null && viewCreated ? { allocatedId: targetViewId } : {}),
2202
+ });
1915
2203
  continue;
1916
2204
  }
1917
2205
 
@@ -1983,6 +2271,33 @@ function requireObject(value, label) {
1983
2271
  }
1984
2272
  }
1985
2273
 
2274
+ function slugifyId(seed) {
2275
+ return String(seed == null ? '' : seed)
2276
+ .toLowerCase()
2277
+ .replace(/[^a-z0-9]+/g, '-')
2278
+ .replace(/-{2,}/g, '-')
2279
+ .replace(/^-+|-+$/g, '');
2280
+ }
2281
+
2282
+ // One unified id strategy for the whole framework (issue #8): a semantic slug
2283
+ // derived from the entity's human name, made unique within its collection by a
2284
+ // numeric suffix. Callers MAY omit an id; the server allocates one. There is no
2285
+ // per-repository id strategy — ArchGraph has a single one.
2286
+ function allocateUniqueId(existingIds, seed, fallbackBase) {
2287
+ const taken = new Set((Array.isArray(existingIds) ? existingIds : []).map(String));
2288
+ const base = slugifyId(seed) || fallbackBase || 'item';
2289
+ if (!taken.has(base)) {
2290
+ return base;
2291
+ }
2292
+ for (let n = 2; n < 100000; n += 1) {
2293
+ const candidate = `${base}-${String(n).padStart(3, '0')}`;
2294
+ if (!taken.has(candidate)) {
2295
+ return candidate;
2296
+ }
2297
+ }
2298
+ return `${base}-${Date.now()}`;
2299
+ }
2300
+
1986
2301
  function requireId(value, label) {
1987
2302
  if (typeof value !== 'string' || value.length === 0) {
1988
2303
  throw new Error(`${label} must be a non-empty string`);
@@ -2877,6 +3192,18 @@ function compactMutationResponse(payload) {
2877
3192
  status: payload && payload.status,
2878
3193
  written: Boolean(payload && payload.written),
2879
3194
  };
3195
+ // A successful write must tell the caller which id was used/allocated and whether
3196
+ // it created or reused — otherwise an omitted (auto-allocated) id is invisible
3197
+ // and an id collision would look like a create. Kept to a few fields (issue #8).
3198
+ if (Array.isArray(payload && payload.mutations) && payload.mutations.length > 0) {
3199
+ compact.mutations = payload.mutations.map((entry) => ({
3200
+ type: entry.type,
3201
+ id: entry.id,
3202
+ created: entry.created,
3203
+ ...(entry.reused ? { reused: true, reusedId: entry.reusedId } : {}),
3204
+ ...(entry.allocatedId ? { allocatedId: entry.allocatedId } : {}),
3205
+ }));
3206
+ }
2880
3207
  if (payload && payload.embeddingLifecycle && payload.embeddingLifecycle.state) {
2881
3208
  compact.embeddingLifecycle = { state: payload.embeddingLifecycle.state };
2882
3209
  }
@@ -4749,6 +5076,9 @@ module.exports = {
4749
5076
  buildGetSystemArchitectureStructuredContent,
4750
5077
  TOOLS,
4751
5078
  applyMutations,
5079
+ applyContextBudget,
5080
+ applyViewContextBudget,
5081
+ resolveContextMaxBytes,
4752
5082
  buildBusinessSemanticSummary,
4753
5083
  buildSemanticDedupAdvisory,
4754
5084
  selectCreatedElementAdds,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "archgraph-argo-beta",
3
- "version": "0.27.0-beta.11",
3
+ "version": "0.27.0-beta.13",
4
4
  "description": "Deploy the ArchGraph ARGO toolchain, skills, and rules (schema, scripts, argo-init skill, global rule) with one command.",
5
5
  "license": "MIT",
6
6
  "bin": {