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,500 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Lossless Write Gate (无损写入门禁), framework-level.
5
+ *
6
+ * Invariant: NO SILENT LOSS. A write must never reduce stored content unless the
7
+ * caller explicitly acknowledges it (and, for major loss, justifies it). Two
8
+ * mechanisms make this possible:
9
+ *
10
+ * G1 structured fields MERGE (omission never means deletion): updateElement
11
+ * .testcases (by name), updateRelationship .attributes (by name),
12
+ * updateView membership (delta {add,remove}); explicit op:'remove' deletes.
13
+ * G2 scalar text GUARDED: description / statement / document / name / view_name
14
+ * are full-value fields; a value that drops prior segments is blocked unless
15
+ * the mutation carries acknowledgeLoss:true (and lossJustification for major
16
+ * loss). Pure additions/expansions are always allowed.
17
+ * G3 destructive removals ACKNOWLEDGED + RECOVERABLE: removeElement /
18
+ * removeRelationship / removeView require acknowledgeLoss:true and snapshot
19
+ * the full removed object into a tombstone ledger (nothing is truly lost).
20
+ * G5 every response carries a loss report (text/testcases/members/objects +
21
+ * the removed samples), on preview as well as apply.
22
+ *
23
+ * The gate is enforced at the single funnel buildMutationResult (apply +
24
+ * preview + all single-object helpers), so every MCP write interface is covered.
25
+ */
26
+
27
+ const fs = require('node:fs');
28
+ const path = require('node:path');
29
+
30
+ const LOSS_ACK_FIELD = 'acknowledgeLoss';
31
+ const LOSS_JUSTIFICATION_FIELD = 'lossJustification';
32
+
33
+ // A text loss is "major" (justification, not just acknowledgement, required)
34
+ // when it removes this many characters or this share of the original text.
35
+ const MAJOR_REMOVED_CHARS = 200;
36
+ const MAJOR_REMOVED_RATIO = 0.5;
37
+
38
+ // A changed segment is a "modification" (not a loss) when its token overlap with
39
+ // some new segment is at least this high — "reworded, not dropped".
40
+ const MODIFICATION_SIMILARITY = 0.5;
41
+
42
+ // Tokens that carry structured identity (ids, numbers, hashes, paths): if one is
43
+ // gone it is always a loss, even when the surrounding sentence was only reworded.
44
+ const TOKEN_RE = /[A-Za-z0-9_@#./\\:-]+|[\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff]/g;
45
+
46
+ // Full-value text fields per mutation type. Editing any of these can silently
47
+ // drop prior content, so they are loss-guarded.
48
+ const TEXT_FIELDS_BY_MUTATION = Object.freeze({
49
+ updateElement: Object.freeze(['description', 'name']),
50
+ updateRelationship: Object.freeze(['statement', 'name', 'description', 'document']),
51
+ updateView: Object.freeze(['view_name', 'description']),
52
+ });
53
+
54
+ function normalizeForCompare(value) {
55
+ return String(value === undefined || value === null ? '' : value)
56
+ .normalize('NFKC')
57
+ .replace(/\s+/g, ' ')
58
+ .trim();
59
+ }
60
+
61
+ function normalizeSegments(text) {
62
+ return String(text === undefined || text === null ? '' : text)
63
+ .split(/\r?\n/)
64
+ .map(normalizeForCompare)
65
+ .filter(segment => segment.length > 0);
66
+ }
67
+
68
+ function tokenize(segment) {
69
+ const normalized = String(segment === undefined || segment === null ? '' : segment).normalize('NFKC');
70
+ const matches = normalized.match(TOKEN_RE);
71
+ return matches ? matches.map(token => token.toLowerCase()) : [];
72
+ }
73
+
74
+ // A "structured identity" token whose silent loss matters: commit hashes, ids,
75
+ // versions, dates, path-like strings. Bare separators ("/") and short plain
76
+ // numbers are NOT structured — treating them so made benign edits false-block.
77
+ function isStructuredToken(token) {
78
+ if (!token) return false;
79
+ if (/^[0-9a-f]{7,40}$/i.test(token)) return true; // commit hash / long hex
80
+ if (/[/\\]/.test(token) && /[a-z]/i.test(token)) return true; // path-like (has a letter)
81
+ if (/[a-z]/i.test(token) && /\d/.test(token) && /[-_]/.test(token)) return true; // id-like AT-rules-04
82
+ if (/^[a-z]*\d+(?:\.\d+)+$/i.test(token)) return true; // version-like stix2.1 / v2.1 / 1.2.3
83
+ if (/^\d{4}-\d{2}(?:-\d{2})?$/.test(token)) return true; // date-like 2026-09-15
84
+ if (/^\d{5,}$/.test(token)) return true; // long numeric id
85
+ return false;
86
+ }
87
+
88
+ // NFKC + strip all whitespace + lowercase: tolerant haystack for the "is this
89
+ // structured token still present anywhere in the new text?" substring check.
90
+ // This drops false positives from separator joins (769465c:bc7f418) and spacing
91
+ // (STIX2.1 -> STIX 2.1) while still catching a genuinely removed token.
92
+ function normalizeForTokenSearch(value) {
93
+ return String(value === undefined || value === null ? '' : value).normalize('NFKC').replace(/\s+/g, '').toLowerCase();
94
+ }
95
+
96
+ // Separator-insensitive form: also drop the punctuation that joins structured
97
+ // tokens, so "A/B" -> "A、B" or "v2.1" -> "v2 1" is still recognised as the same
98
+ // token (same content, punctuation changed) and not mistaken for a loss.
99
+ function comparableTokenForm(value) {
100
+ return normalizeForTokenSearch(value).replace(/[/\\:.\-_]/g, '');
101
+ }
102
+
103
+ // Sørensen–Dice coefficient over token sets (deterministic, no network).
104
+ function diceCoefficient(aTokens, bTokens) {
105
+ if (aTokens.length === 0 && bTokens.length === 0) return 1;
106
+ if (aTokens.length === 0 || bTokens.length === 0) return 0;
107
+ const a = new Set(aTokens);
108
+ const b = new Set(bTokens);
109
+ let intersection = 0;
110
+ for (const token of a) if (b.has(token)) intersection += 1;
111
+ return (2 * intersection) / (a.size + b.size);
112
+ }
113
+
114
+ // Deterministic loss detector. A changed segment is classified as a MODIFICATION
115
+ // (kept, just reworded) when it is similar enough to some new segment; otherwise
116
+ // it is a LOSS (dropped or substantially rewritten). Structured tokens (ids,
117
+ // numbers, hashes, paths) that disappear are always a loss. Pure additions and
118
+ // reorderings report nothing.
119
+ function detectTextLoss(oldText, newText) {
120
+ const oldSegments = normalizeSegments(oldText);
121
+ if (oldSegments.length === 0) {
122
+ return { removedSegments: [], modifiedSegments: [], removedChars: 0, oldChars: 0, ratio: 0, structuredTokensRemoved: [] };
123
+ }
124
+ const newSegments = normalizeSegments(newText);
125
+ const newNormalized = normalizeForCompare(newText);
126
+ const newHaystack = comparableTokenForm(newText);
127
+ const newSegmentTokens = newSegments.map(tokenize);
128
+ const removedSegments = [];
129
+ const modifiedSegments = [];
130
+ const structuredTokensRemoved = [];
131
+ for (const segment of oldSegments) {
132
+ const segmentTokens = tokenize(segment);
133
+ for (const token of segmentTokens) {
134
+ if (isStructuredToken(token) && !newHaystack.includes(comparableTokenForm(token))) structuredTokensRemoved.push(token);
135
+ }
136
+ if (newNormalized.includes(segment)) continue; // kept verbatim
137
+ const best = newSegmentTokens.reduce((max, tokens) => Math.max(max, diceCoefficient(segmentTokens, tokens)), 0);
138
+ if (best >= MODIFICATION_SIMILARITY) modifiedSegments.push(segment);
139
+ else removedSegments.push(segment);
140
+ }
141
+ const removedChars = removedSegments.reduce((sum, segment) => sum + segment.length, 0);
142
+ const oldChars = oldSegments.reduce((sum, segment) => sum + segment.length, 0);
143
+ return {
144
+ removedSegments,
145
+ modifiedSegments,
146
+ removedChars,
147
+ oldChars,
148
+ ratio: oldChars > 0 ? removedChars / oldChars : 0,
149
+ structuredTokensRemoved: [...new Set(structuredTokensRemoved)],
150
+ };
151
+ }
152
+
153
+ // G1: merge testcases by their stable key (name). Untouched testcases survive;
154
+ // only an explicit {name, op:'remove'} deletes one.
155
+ function mergeTestcasesPatch(existing, patchEntries) {
156
+ if (!Array.isArray(patchEntries)) {
157
+ throw new Error('patch.testcases must be an array of { name, ... } entries');
158
+ }
159
+ const result = Array.isArray(existing) ? existing.map(entry => ({ ...entry })) : [];
160
+ for (const entry of patchEntries) {
161
+ if (!entry || typeof entry !== 'object' || typeof entry.name !== 'string' || entry.name.trim() === '') {
162
+ throw new Error('patch.testcases entries must have a non-empty string name (the stable merge key)');
163
+ }
164
+ const index = result.findIndex(existingEntry => existingEntry.name === entry.name);
165
+ if (entry.op === 'remove') {
166
+ if (index >= 0) result.splice(index, 1);
167
+ continue;
168
+ }
169
+ const next = { ...entry };
170
+ delete next.op;
171
+ if (index >= 0) result[index] = next;
172
+ else result.push(next);
173
+ }
174
+ return result;
175
+ }
176
+
177
+ // G1: merge relationship attributes by name ({ name, description }). Unmentioned
178
+ // attributes survive; op:'remove' deletes by name.
179
+ function mergeRelationshipAttributesPatch(existing, patchEntries) {
180
+ if (!Array.isArray(patchEntries)) {
181
+ throw new Error('patch.attributes must be an array of { name, ... } entries');
182
+ }
183
+ const result = Array.isArray(existing) ? existing.map(entry => ({ ...entry })) : [];
184
+ for (const entry of patchEntries) {
185
+ if (!entry || typeof entry !== 'object' || typeof entry.name !== 'string' || entry.name.trim() === '') {
186
+ throw new Error('patch.attributes entries must have a non-empty string name');
187
+ }
188
+ const index = result.findIndex(attr => attr.name === entry.name);
189
+ if (entry.op === 'remove') {
190
+ if (index >= 0) result.splice(index, 1);
191
+ continue;
192
+ }
193
+ const next = { name: entry.name };
194
+ for (const field of ['value', 'description', 'content']) {
195
+ if (Object.prototype.hasOwnProperty.call(entry, field)) next[field] = entry[field];
196
+ }
197
+ if (index >= 0) result[index] = next;
198
+ else result.push(next);
199
+ }
200
+ return result;
201
+ }
202
+
203
+ // G1: apply a view membership patch as either a full list (legacy replace) or a
204
+ // lossless delta { add, remove }. Returns the resulting list.
205
+ function applyViewMembershipPatch(current, patchValue) {
206
+ const base = Array.isArray(current) ? current : [];
207
+ if (Array.isArray(patchValue)) {
208
+ return { list: dedupe(patchValue), explicitRemove: null };
209
+ }
210
+ if (patchValue && typeof patchValue === 'object') {
211
+ const remove = Array.isArray(patchValue.remove) ? patchValue.remove : [];
212
+ const add = Array.isArray(patchValue.add) ? patchValue.add : [];
213
+ const kept = base.filter(id => !remove.includes(id));
214
+ return { list: dedupe([...kept, ...add]), explicitRemove: remove };
215
+ }
216
+ throw new Error('view membership patch must be an array or { add, remove }');
217
+ }
218
+
219
+ function dedupe(entries) {
220
+ const seen = new Set();
221
+ const result = [];
222
+ for (const entry of entries) {
223
+ if (seen.has(entry)) continue;
224
+ seen.add(entry);
225
+ result.push(entry);
226
+ }
227
+ return result;
228
+ }
229
+
230
+ function findById(entries, id) {
231
+ return Array.isArray(entries) ? entries.find(entry => entry && entry.id === id) : undefined;
232
+ }
233
+
234
+ function findView(views, viewId) {
235
+ return Array.isArray(views) ? views.find(view => view && view.view_id === viewId) : undefined;
236
+ }
237
+
238
+ function isAcknowledged(mutation, lossAck) {
239
+ return (Boolean(mutation) && mutation[LOSS_ACK_FIELD] === true)
240
+ || (Boolean(lossAck) && lossAck[LOSS_ACK_FIELD] === true);
241
+ }
242
+
243
+ function hasJustification(mutation, lossAck) {
244
+ const text = (mutation && mutation[LOSS_JUSTIFICATION_FIELD])
245
+ || (lossAck && lossAck[LOSS_JUSTIFICATION_FIELD]);
246
+ return typeof text === 'string' && text.trim() !== '';
247
+ }
248
+
249
+ // G5+enforcement: compute every content reduction a mutation set would cause,
250
+ // with per-item acknowledgement state, and whether the set must be blocked.
251
+ // `lossAck` is an optional batch-level acknowledgement (applySystemArchitectureMutation
252
+ // top level) that counts for every mutation in the set.
253
+ function buildLossReport({ baseDocument, mutations, nextDocument, lossAck }) {
254
+ const base = baseDocument || {};
255
+ const next = nextDocument || {};
256
+ const report = {
257
+ blocked: false,
258
+ acknowledged: true,
259
+ reasons: [],
260
+ text: [],
261
+ modifications: [],
262
+ membersRemoved: [],
263
+ testcasesRemoved: [],
264
+ attributesRemoved: [],
265
+ objectsRemoved: [],
266
+ };
267
+
268
+ const pushReason = (reason) => {
269
+ report.blocked = true;
270
+ report.acknowledged = false;
271
+ if (!report.reasons.includes(reason)) report.reasons.push(reason);
272
+ };
273
+
274
+ const guardText = (mutation, kind, id, field, oldValue, newValue) => {
275
+ const loss = detectTextLoss(oldValue, newValue);
276
+ if (loss.modifiedSegments.length > 0) {
277
+ // Reworded, not dropped: reported for transparency, never blocked.
278
+ report.modifications.push({ kind, id, field, modifiedLines: loss.modifiedSegments.length, sample: loss.modifiedSegments.slice(0, 3) });
279
+ }
280
+ const hasLoss = loss.removedSegments.length > 0 || loss.structuredTokensRemoved.length > 0;
281
+ if (!hasLoss) return;
282
+ // "Major" only when the removed volume is substantial; a large share of a
283
+ // tiny value is not major (avoids forcing justification for short edits).
284
+ const major = loss.removedChars > MAJOR_REMOVED_CHARS
285
+ || (loss.oldChars > MAJOR_REMOVED_CHARS && loss.ratio > MAJOR_REMOVED_RATIO);
286
+ const acknowledged = isAcknowledged(mutation, lossAck) && (!major || hasJustification(mutation, lossAck));
287
+ const item = {
288
+ kind,
289
+ id,
290
+ field,
291
+ removedChars: loss.removedChars,
292
+ removedLines: loss.removedSegments.length,
293
+ structuredTokensRemoved: loss.structuredTokensRemoved,
294
+ ratio: Number(loss.ratio.toFixed(3)),
295
+ major,
296
+ acknowledged,
297
+ removedSample: loss.removedSegments.slice(0, 3),
298
+ };
299
+ report.text.push(item);
300
+ if (!acknowledged) {
301
+ const why = major && !hasJustification(mutation, lossAck)
302
+ ? ' (major loss requires a non-empty lossJustification)'
303
+ : '';
304
+ const structured = loss.structuredTokensRemoved.length > 0
305
+ ? ` [structured tokens removed: ${loss.structuredTokensRemoved.slice(0, 5).join(', ')}]`
306
+ : '';
307
+ pushReason(
308
+ `Unacknowledged text loss: ${kind} '${id}' field '${field}' would remove ${loss.removedChars} char(s) / ${loss.removedSegments.length} line(s)${structured}${why}. `
309
+ + 'Read the current value first, then pass acknowledgeLoss:true (and lossJustification) to confirm an intentional rewrite, or use an additive edit that keeps the prior content.',
310
+ );
311
+ }
312
+ };
313
+
314
+ for (const mutation of mutations || []) {
315
+ if (mutation.type === 'updateElement' || mutation.type === 'updateRelationship') {
316
+ const collection = mutation.type === 'updateElement' ? 'elements' : 'relationships';
317
+ const kind = mutation.type === 'updateElement' ? 'element' : 'relationship';
318
+ const baseEntry = findById(base[collection], mutation.id);
319
+ const nextEntry = findById(next[collection], mutation.id);
320
+ if (!baseEntry || !nextEntry) continue;
321
+ for (const field of TEXT_FIELDS_BY_MUTATION[mutation.type]) {
322
+ guardText(mutation, kind, mutation.id, field, baseEntry[field], nextEntry[field]);
323
+ }
324
+ if (mutation.type === 'updateElement' && Array.isArray(baseEntry.testcases)) {
325
+ const nextNames = new Set((nextEntry.testcases || []).map(tc => tc && tc.name));
326
+ for (const tc of baseEntry.testcases) {
327
+ if (tc && tc.name && !nextNames.has(tc.name)) {
328
+ report.testcasesRemoved.push({ id: mutation.id, name: tc.name });
329
+ }
330
+ }
331
+ }
332
+ } else if (mutation.type === 'updateView') {
333
+ const viewId = mutation.view_id || mutation.id;
334
+ const baseView = findView(base.views, viewId);
335
+ const nextView = findView(next.views, viewId);
336
+ if (!baseView || !nextView) continue;
337
+ for (const field of TEXT_FIELDS_BY_MUTATION.updateView) {
338
+ guardText(mutation, 'view', viewId, field, baseView[field], nextView[field]);
339
+ }
340
+ const baseElements = new Set(baseView.included_elements || []);
341
+ const removedElements = [...baseElements].filter(id => !(nextView.included_elements || []).includes(id));
342
+ const baseRelationships = new Set(baseView.included_relationships || []);
343
+ const removedRelationships = [...baseRelationships].filter(id => !(nextView.included_relationships || []).includes(id));
344
+ if (removedElements.length > 0 || removedRelationships.length > 0) {
345
+ // A channel with no removals is trivially covered; a channel with removals
346
+ // is explicit only when patched via the delta { remove } form.
347
+ const elementsExplicit = removedElements.length === 0
348
+ || isExplicitRemovePatch(mutation.patch, 'included_elements');
349
+ const relationshipsExplicit = removedRelationships.length === 0
350
+ || isExplicitRemovePatch(mutation.patch, 'included_relationships');
351
+ const explicit = elementsExplicit && relationshipsExplicit;
352
+ const acknowledged = explicit || isAcknowledged(mutation, lossAck);
353
+ report.membersRemoved.push({
354
+ view_id: viewId,
355
+ elements: removedElements,
356
+ relationships: removedRelationships,
357
+ explicit,
358
+ acknowledged,
359
+ });
360
+ if (!acknowledged) {
361
+ pushReason(
362
+ `Unacknowledged membership removal in view '${viewId}': ${removedElements.length} element(s) and ${removedRelationships.length} relationship(s) would be dropped. `
363
+ + 'Use the delta form included_elements:{remove:[...]} for explicit removal, or pass acknowledgeLoss:true.',
364
+ );
365
+ }
366
+ }
367
+ } else if (mutation.type === 'removeElement' || mutation.type === 'removeRelationship' || mutation.type === 'removeView') {
368
+ const spec = {
369
+ removeElement: { collection: 'elements', id: mutation.id },
370
+ removeRelationship: { collection: 'relationships', id: mutation.id },
371
+ removeView: { collection: 'views', id: mutation.view_id },
372
+ }[mutation.type];
373
+ const id = spec.id;
374
+ const baseEntry = mutation.type === 'removeView'
375
+ ? findView(base.views, id)
376
+ : findById(base[spec.collection], id);
377
+ const stillPresent = mutation.type === 'removeView'
378
+ ? Boolean(findView(next.views, id))
379
+ : Boolean(findById(next[spec.collection], id));
380
+ if (!baseEntry || stillPresent) continue;
381
+ const acknowledged = isAcknowledged(mutation, lossAck);
382
+ report.objectsRemoved.push({
383
+ kind: mutation.type.replace(/^remove/, '').toLowerCase(),
384
+ id,
385
+ name: baseEntry.name || baseEntry.view_name,
386
+ acknowledged,
387
+ });
388
+ if (!acknowledged) {
389
+ pushReason(
390
+ `Unacknowledged destructive removal: ${mutation.type} '${id}' ('${baseEntry.name || baseEntry.view_name}') deletes the object permanently. `
391
+ + 'Pass acknowledgeLoss:true (a full tombstone snapshot is recorded for recovery).',
392
+ );
393
+ }
394
+ }
395
+ }
396
+
397
+ return report;
398
+ }
399
+
400
+ function isExplicitRemovePatch(patch, field) {
401
+ if (!patch || !Object.prototype.hasOwnProperty.call(patch, field)) return false;
402
+ const value = patch[field];
403
+ return Boolean(value) && !Array.isArray(value) && typeof value === 'object' && Array.isArray(value.remove);
404
+ }
405
+
406
+ // G3: append full removed objects to an NDJSON tombstone ledger. Each append is a
407
+ // single O(1) line write (no read/rewrite of prior content). When the active file
408
+ // exceeds the size cap (~5k entries) it is rotated aside (rename, O(1)) so the
409
+ // active file and its git diff stay bounded.
410
+ const TOMBSTONE_ACTIVE_BASENAME = 'SystemArchitecture.tombstones.ndjson';
411
+ const TOMBSTONE_ROTATE_BYTES = 2 * 1024 * 1024;
412
+
413
+ function tombstoneFilePath(graphAbsolutePath) {
414
+ return path.join(path.dirname(graphAbsolutePath), TOMBSTONE_ACTIVE_BASENAME);
415
+ }
416
+
417
+ function appendTombstones(graphAbsolutePath, entries, options = {}) {
418
+ const file = tombstoneFilePath(graphAbsolutePath);
419
+ const rotateBytes = Number.isFinite(options.rotateBytes) ? options.rotateBytes : TOMBSTONE_ROTATE_BYTES;
420
+ const list = Array.isArray(entries) ? entries : [];
421
+ if (list.length === 0) return { path: file, count: 0, rotatedTo: null };
422
+ let rotatedTo = null;
423
+ try {
424
+ if (rotateBytes > 0 && fs.statSync(file).size >= rotateBytes) {
425
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-');
426
+ rotatedTo = path.join(path.dirname(file), `SystemArchitecture.tombstones.${stamp}.ndjson`);
427
+ fs.renameSync(file, rotatedTo);
428
+ }
429
+ } catch {
430
+ // No active file yet (first append) — nothing to rotate.
431
+ }
432
+ const at = new Date().toISOString();
433
+ const lines = list.map(entry => JSON.stringify({
434
+ at,
435
+ op: entry.op || ('remove' + entry.kind),
436
+ kind: entry.kind,
437
+ id: entry.id,
438
+ object: entry.object,
439
+ }));
440
+ fs.appendFileSync(file, `${lines.join('\n')}\n`, 'utf8');
441
+ return { path: file, count: list.length, rotatedTo };
442
+ }
443
+
444
+ // Read back the NDJSON tombstone ledger (recovery / audit). Malformed lines are
445
+ // skipped rather than throwing, so a partially written tail never blocks reads.
446
+ function readTombstones(file) {
447
+ try {
448
+ return fs.readFileSync(file, 'utf8')
449
+ .split(/\r?\n/)
450
+ .filter(line => line.trim() !== '')
451
+ .map(line => {
452
+ try {
453
+ return JSON.parse(line);
454
+ } catch {
455
+ return null;
456
+ }
457
+ })
458
+ .filter(Boolean);
459
+ } catch {
460
+ return [];
461
+ }
462
+ }
463
+
464
+ // Collect the full base objects for every global removal in a mutation set.
465
+ function collectRemovedObjects(baseDocument, mutations, nextDocument) {
466
+ const removed = [];
467
+ for (const mutation of mutations || []) {
468
+ if (mutation.type === 'removeElement') {
469
+ const obj = findById((baseDocument || {}).elements, mutation.id);
470
+ if (obj && !findById((nextDocument || {}).elements, mutation.id)) removed.push({ op: mutation.type, kind: 'element', id: mutation.id, object: obj });
471
+ } else if (mutation.type === 'removeRelationship') {
472
+ const obj = findById((baseDocument || {}).relationships, mutation.id);
473
+ if (obj && !findById((nextDocument || {}).relationships, mutation.id)) removed.push({ op: mutation.type, kind: 'relationship', id: mutation.id, object: obj });
474
+ } else if (mutation.type === 'removeView') {
475
+ const obj = findView((baseDocument || {}).views, mutation.view_id);
476
+ if (obj && !findView((nextDocument || {}).views, mutation.view_id)) removed.push({ op: mutation.type, kind: 'view', id: mutation.view_id, object: obj });
477
+ }
478
+ }
479
+ return removed;
480
+ }
481
+
482
+ module.exports = {
483
+ LOSS_ACK_FIELD,
484
+ LOSS_JUSTIFICATION_FIELD,
485
+ MAJOR_REMOVED_CHARS,
486
+ MAJOR_REMOVED_RATIO,
487
+ TEXT_FIELDS_BY_MUTATION,
488
+ normalizeSegments,
489
+ detectTextLoss,
490
+ mergeTestcasesPatch,
491
+ mergeRelationshipAttributesPatch,
492
+ applyViewMembershipPatch,
493
+ buildLossReport,
494
+ appendTombstones,
495
+ readTombstones,
496
+ tombstoneFilePath,
497
+ TOMBSTONE_ACTIVE_BASENAME,
498
+ TOMBSTONE_ROTATE_BYTES,
499
+ collectRemovedObjects,
500
+ };