@memberjunction/integration-engine 6.2.0-edge.4 → 6.2.0-edge.6

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 (52) hide show
  1. package/dist/BaseIntegrationConnector.d.ts.map +1 -1
  2. package/dist/BaseIntegrationConnector.js +22 -4
  3. package/dist/BaseIntegrationConnector.js.map +1 -1
  4. package/dist/BaseRESTIntegrationConnector.d.ts +2 -2
  5. package/dist/BaseRESTIntegrationConnector.d.ts.map +1 -1
  6. package/dist/BaseRESTIntegrationConnector.js +34 -4
  7. package/dist/BaseRESTIntegrationConnector.js.map +1 -1
  8. package/dist/CatalogScope.d.ts +152 -0
  9. package/dist/CatalogScope.d.ts.map +1 -0
  10. package/dist/CatalogScope.js +399 -0
  11. package/dist/CatalogScope.js.map +1 -0
  12. package/dist/CatalogSource.d.ts +53 -0
  13. package/dist/CatalogSource.d.ts.map +1 -0
  14. package/dist/CatalogSource.js +82 -0
  15. package/dist/CatalogSource.js.map +1 -0
  16. package/dist/CatalogWriter.d.ts +216 -0
  17. package/dist/CatalogWriter.d.ts.map +1 -0
  18. package/dist/CatalogWriter.js +457 -0
  19. package/dist/CatalogWriter.js.map +1 -0
  20. package/dist/CompanyIntegrationCatalogStore.d.ts +109 -0
  21. package/dist/CompanyIntegrationCatalogStore.d.ts.map +1 -0
  22. package/dist/CompanyIntegrationCatalogStore.js +229 -0
  23. package/dist/CompanyIntegrationCatalogStore.js.map +1 -0
  24. package/dist/DiscoveryWatchdog.d.ts +38 -1
  25. package/dist/DiscoveryWatchdog.d.ts.map +1 -1
  26. package/dist/DiscoveryWatchdog.js +56 -1
  27. package/dist/DiscoveryWatchdog.js.map +1 -1
  28. package/dist/IntegrationActionGenerator.d.ts.map +1 -1
  29. package/dist/IntegrationActionGenerator.js +33 -26
  30. package/dist/IntegrationActionGenerator.js.map +1 -1
  31. package/dist/IntegrationConnectorCreationPipeline.d.ts +141 -4
  32. package/dist/IntegrationConnectorCreationPipeline.d.ts.map +1 -1
  33. package/dist/IntegrationConnectorCreationPipeline.js +521 -64
  34. package/dist/IntegrationConnectorCreationPipeline.js.map +1 -1
  35. package/dist/IntegrationEngine.d.ts +13 -0
  36. package/dist/IntegrationEngine.d.ts.map +1 -1
  37. package/dist/IntegrationEngine.js +257 -166
  38. package/dist/IntegrationEngine.js.map +1 -1
  39. package/dist/IntegrationSchemaSync.d.ts +97 -0
  40. package/dist/IntegrationSchemaSync.d.ts.map +1 -1
  41. package/dist/IntegrationSchemaSync.js +300 -49
  42. package/dist/IntegrationSchemaSync.js.map +1 -1
  43. package/dist/MatchEngine.d.ts.map +1 -1
  44. package/dist/MatchEngine.js +6 -0
  45. package/dist/MatchEngine.js.map +1 -1
  46. package/dist/index.d.ts +8 -0
  47. package/dist/index.d.ts.map +1 -1
  48. package/dist/index.js +6 -0
  49. package/dist/index.js.map +1 -1
  50. package/dist/types.d.ts +21 -0
  51. package/dist/types.d.ts.map +1 -1
  52. package/package.json +7 -7
@@ -12,9 +12,11 @@
12
12
  * for constraint columns (IsPrimaryKey, IsRequired, Description, etc.) and
13
13
  * dynamic wins for type/size columns (Type, Length, Precision, Scale).
14
14
  */
15
- import { CompositeKey, LogError, Metadata, RunView } from '@memberjunction/core';
15
+ import { LogError, Metadata, RunView } from '@memberjunction/core';
16
+ import { NormalizeUUID } from '@memberjunction/global';
16
17
  import { IntegrationEngineBase } from '@memberjunction/integration-engine-base';
17
18
  import { ReadFieldSyncDirective, WriteFieldSyncDirective } from './SyncDirectives.js';
19
+ import { PerConnectionCatalogWriter, SharedCatalogWriter } from './CatalogWriter.js';
18
20
  import { ActionMetadataGenerator } from './ActionMetadataGenerator.js';
19
21
  /**
20
22
  * Pure-function overlay rule for a single boolean attribute.
@@ -206,6 +208,75 @@ export function DecideSchemaLimitViolations(input) {
206
208
  export function decideSchemaLimitViolations(input) {
207
209
  return DecideSchemaLimitViolations(input);
208
210
  }
211
+ /**
212
+ * MJ-RUN-37 — the overlay attributes whose change makes an object's stored Pull watermark
213
+ * MEANINGLESS rather than merely stale.
214
+ *
215
+ * `IncrementalWatermarkField` names the source column the incremental filter is built from. Swap it
216
+ * and the stored cursor value — captured from the OLD column — is applied as a lower bound on the
217
+ * NEW one. Where the new column sorts later, every row below that value is filtered out at the
218
+ * source and never fetched again. Nothing reports it: the run's fetch-integrity check compares what
219
+ * arrived against what the source said matched the filter it was given, and those agree exactly.
220
+ * The result is silent, permanent absence with no artifact to find it in.
221
+ */
222
+ export const WATERMARK_INVALIDATING_ATTRIBUTES = ['IncrementalWatermarkField'];
223
+ /**
224
+ * Names of the objects whose persist-time overlay invalidated their Pull watermark.
225
+ *
226
+ * Pure, so the decision that matters — persist DETECTED it, evolution must ACT on it, and on
227
+ * nothing else — is pinnable without a database.
228
+ *
229
+ * Two exclusions, both guarding against OVER-firing. Resetting a watermark costs a full re-fetch of
230
+ * the object, so a rule that fires when nothing relevant changed quietly turns every refresh into a
231
+ * fleet-wide full sync:
232
+ *
233
+ * - a CREATED row is never a change. A brand-new object has no watermark to invalidate.
234
+ * - `restrictTo`, when given, limits the answer to that set (the evolution passes its CONTINUING
235
+ * entity maps). An object with no continuing map has no Pull watermark this run can reset, so
236
+ * reporting it would inflate the change set — and `HasChanges` — with a name nothing acts on.
237
+ * Matched case-insensitively, as every catalog-to-map reconciliation in this codebase is.
238
+ * Returned names keep the CATALOG's casing, which is what the source object is called.
239
+ */
240
+ export function ObjectsWithWatermarkFieldChange(log, restrictTo) {
241
+ const allowed = restrictTo === undefined ? undefined : new Set(restrictTo.map((n) => n.toLowerCase()));
242
+ const out = [];
243
+ for (const entry of log) {
244
+ if (entry.Created)
245
+ continue;
246
+ const changed = entry.ChangedAttributes ?? [];
247
+ if (!changed.some((a) => WATERMARK_INVALIDATING_ATTRIBUTES.includes(a)))
248
+ continue;
249
+ if (allowed && !allowed.has(entry.ObjectName.toLowerCase()))
250
+ continue;
251
+ out.push(entry.ObjectName);
252
+ }
253
+ return out;
254
+ }
255
+ /**
256
+ * The IntegrationObject columns an object upsert changed, as {@link ObjectMergeLog.ChangedAttributes}
257
+ * reports them: the columns rebased from the declaration plus the overlay's own entries.
258
+ *
259
+ * The watermark counts only on its NET change. On a per-connection row the rebase can move
260
+ * `IncrementalWatermarkField` to the declared value and the overlay can move it straight back to
261
+ * what discovery reports, so the step list says nothing reliable about whether it changed. Getting
262
+ * this wrong either way is costly: a declaration that moves it must reset the stored Pull cursor
263
+ * (see {@link ObjectsWithWatermarkFieldChange}), and a rebase the overlay undoes must not, or every
264
+ * refresh would re-fetch the object in full.
265
+ *
266
+ * Pure, so that rule is pinnable without a database.
267
+ *
268
+ * @param rebased Columns `RebaseFromDeclared` moved.
269
+ * @param overlay The upsert's own change log; its `rebased:` summary entry is ignored.
270
+ * @param watermarkBefore `IncrementalWatermarkField` before the rebase.
271
+ * @param watermarkAfter `IncrementalWatermarkField` after the overlay.
272
+ */
273
+ export function ObjectChangedAttributes(rebased, overlay, watermarkBefore, watermarkAfter) {
274
+ const out = [...new Set([...rebased, ...overlay.filter((c) => !c.startsWith('rebased:'))])]
275
+ .filter((c) => c !== 'IncrementalWatermarkField');
276
+ if (watermarkAfter !== watermarkBefore)
277
+ out.push('IncrementalWatermarkField');
278
+ return out;
279
+ }
209
280
  /**
210
281
  * Does the source actually STATE a type, or is this silence?
211
282
  *
@@ -340,13 +411,40 @@ export class IntegrationSchemaSync {
340
411
  // lightweight PK-only guess; a naming-heuristic FK guess over the sampled stream produced false edges that
341
412
  // skewed the sync DAG, so it was removed. Whatever FK info SourceSchema.Objects already carries flows
342
413
  // through the Declared/Discovered merge as-is. (EnrichSchemaConstraints remains exported for offline use.)
343
- // Load existing objects for this integration from cache
344
- const existingObjects = engine.GetIntegrationObjectsByIntegrationID(IntegrationID);
414
+ // Which catalog this discovery writes into. Refuse rather than fall back: writing one
415
+ // connection's discovery into the catalog every other connection reads is exactly the failure
416
+ // this design removes, and it would report success.
417
+ if (opts.CatalogSource === 'PerConnection' && !opts.CompanyIntegrationID) {
418
+ throw new Error('PER_CONNECTION_CATALOG_MISSING: CatalogSource is PerConnection but no CompanyIntegrationID '
419
+ + 'was supplied. Refusing to fall back to the shared catalog, which would persist this '
420
+ + "connection's discovery into every other connection of the same connector.");
421
+ }
422
+ const writer = opts.CatalogSource === 'PerConnection'
423
+ ? new PerConnectionCatalogWriter(md, opts.CompanyIntegrationID, IntegrationID, ContextUser, new Date())
424
+ : new SharedCatalogWriter(md, IntegrationID, ContextUser);
425
+ // Existing rows come from the DATABASE, not the engine cache. The cache is refreshed between
426
+ // discovery passes, not within one, so the second pass of a two-pass run must be able to see
427
+ // what the first pass persisted. It is also the only thing that works for the per-connection
428
+ // catalog: its cached rows are read-only projections with no Save().
429
+ const existingObjects = await writer.ObjectsInScope();
430
+ // The declared floor a discovery overlays is still looked up by CONNECTOR: a per-connection
431
+ // object records which declared row it was matched to, and that link is what makes
432
+ // "whose definition is this" answerable later.
433
+ const declaredByName = new Map();
434
+ // Explicitly the SHARED rows. That getter is scope-aware now, and inside a per-connection run
435
+ // it would hand back this connection's own rows — so the discovery would overlay its own
436
+ // previous output and the provenance link back to the declared definition would be lost.
437
+ for (const declared of engine.GetSharedIntegrationObjects(IntegrationID)) {
438
+ // The ROW, not just its id: a refresh rebases the connection's declared-owned columns from
439
+ // it, so an open-app upgrade reaches connections that already discovered once.
440
+ if (declared.ID)
441
+ declaredByName.set(declared.Name.toLowerCase(), declared);
442
+ }
345
443
  // Phase 1: upsert objects. Object upserts must complete before field upserts
346
444
  // (fields need ObjectID). Within this phase, upserts are independent so we
347
445
  // batch-execute via Promise.all (concurrency cap to avoid hammering the DB).
348
446
  const objectUpserts = SourceSchema.Objects.map((srcObj) => async () => {
349
- const objResult = await IntegrationSchemaSync.upsertObject(md, IntegrationID, srcObj, existingObjects, ContextUser);
447
+ const objResult = await IntegrationSchemaSync.upsertObject(writer, srcObj, existingObjects, declaredByName.get(srcObj.ExternalName.toLowerCase()) ?? null, SourceSchema.IsAuthoritative === true);
350
448
  return { srcObj, ...objResult };
351
449
  });
352
450
  const objectResults = useBatch ? await IntegrationSchemaSync.batchExec(objectUpserts, 8) : await IntegrationSchemaSync.serialExec(objectUpserts);
@@ -358,6 +456,7 @@ export class IntegrationSchemaSync {
358
456
  EffectiveSource: r.EffectiveSource,
359
457
  Created: r.Created,
360
458
  Updated: r.Updated,
459
+ ChangedAttributes: r.ChangedAttributes,
361
460
  });
362
461
  }
363
462
  // Build sibling name→ID map for FK resolution during field upserts.
@@ -378,7 +477,22 @@ export class IntegrationSchemaSync {
378
477
  const fieldUpsertJobs = objectResults
379
478
  .filter((r) => r.ObjectID)
380
479
  .map((r) => async () => {
381
- const existingFields = engine.GetIntegrationObjectFields(r.ObjectID);
480
+ const existingFields = await writer.FieldsForObject(r.ObjectID);
481
+ // The declared field rows this object's fields overlay, by lowercased name. Read from the
482
+ // engine cache because the DECLARED catalog is shared and unchanged by this run — only the
483
+ // per-connection copy is being written. Empty for an object with no declared counterpart,
484
+ // which is the ordinary case for something discovery found on its own.
485
+ const declaredObjectID = declaredByName.get(r.srcObj.ExternalName.toLowerCase())?.ID;
486
+ const declaredFieldByName = new Map();
487
+ const declaredFieldRowByName = new Map();
488
+ if (declaredObjectID) {
489
+ for (const df of engine.GetIntegrationObjectFields(declaredObjectID)) {
490
+ if (df.ID) {
491
+ declaredFieldByName.set(df.Name.toLowerCase(), df.ID);
492
+ declaredFieldRowByName.set(df.Name.toLowerCase(), df);
493
+ }
494
+ }
495
+ }
382
496
  // U1 / rsuplan line 29 — the primary key is EITHER declared OR streamed, NEVER unioned. If the
383
497
  // object already carries a primary key from its declared metadata, streamed discovery must not
384
498
  // promote a *different* field to PK: that fabricates a composite whose extra, often-nullable
@@ -386,11 +500,14 @@ export class IntegrationSchemaSync {
386
500
  // added component is NULL — the HubSpot `id` + `hs_object_id` failure). Streaming still runs for
387
501
  // every object to find columns/widths/customs; ONLY the PK promotion is gated. A prior *discovered*
388
502
  // PK does not count as the authoritative declared key (excluded so a re-run can't self-perpetuate).
389
- const objectHasDeclaredPK = existingFields.some(f => f.IsPrimaryKey === true && f.MetadataSource !== 'Discovered');
503
+ // MJ-CAT-17: on a first discovery the per-connection field list is empty, so the declared key
504
+ // must be read from the declaration itself or a streamed field would be promoted over it.
505
+ const objectHasDeclaredPK = existingFields.some(f => f.IsPrimaryKey === true && f.MetadataSource !== 'Discovered')
506
+ || [...declaredFieldRowByName.values()].some(f => f.IsPrimaryKey === true);
390
507
  const perObjectLogs = [];
391
508
  const perObjectStats = { created: 0, updated: 0 };
392
509
  for (const srcField of r.srcObj.Fields) {
393
- const fr = await IntegrationSchemaSync.upsertField(md, r.ObjectID, srcField, existingFields, ContextUser, siblingNameToID, objectHasDeclaredPK);
510
+ const fr = await IntegrationSchemaSync.upsertField(writer, r.ObjectID, srcField, existingFields, siblingNameToID, objectHasDeclaredPK, r.srcObj.FieldsAreAuthoritative ?? SourceSchema.IsAuthoritative === true, declaredFieldByName.get(srcField.Name.toLowerCase()) ?? null, declaredFieldRowByName.get(srcField.Name.toLowerCase()) ?? null);
394
511
  if (fr.Created)
395
512
  perObjectStats.created++;
396
513
  if (fr.Updated)
@@ -426,7 +543,17 @@ export class IntegrationSchemaSync {
426
543
  // enumerated the FULL gamut the credentials expose (SourceSchema.IsAuthoritative). A stubbed/empty or
427
544
  // cache-driven discovery has IsAuthoritative=false, so absence proves NOTHING and nothing is disabled
428
545
  // (else it would wrongly wipe the Declared metadata that is the only source). Deactivate, never delete.
429
- if (opts.DeactivateAbsent && SourceSchema.IsAuthoritative) {
546
+ //
547
+ // Object-level and field-level retirement are separately gateable (DeactivateAbsentObjects /
548
+ // DeactivateAbsentFields), because a STREAMING discovery needs them at different moments with
549
+ // opposite scopes: a per-object persist holds that object's FULL field list but sees only one
550
+ // object, and the final name pass sees every object but no fields. Both default to
551
+ // DeactivateAbsent, so every caller that sets neither behaves exactly as before. The PURE decider
552
+ // still decides both from one flag — its tests stay the cheapest correctness evidence here — and
553
+ // its OUTPUT is filtered instead of forking its logic.
554
+ const retireObjects = opts.DeactivateAbsentObjects ?? opts.DeactivateAbsent ?? false;
555
+ const retireFields = opts.DeactivateAbsentFields ?? opts.DeactivateAbsent ?? false;
556
+ if ((retireObjects || retireFields) && SourceSchema.IsAuthoritative) {
430
557
  // Gather the active set + per-discovered-object fields, then let the PURE decision
431
558
  // (decideAbsentDeactivations — unit-tested) choose what to Disable. The EFFECT (load + Save) is
432
559
  // applied here; the CHOICE lives in the pure function so it is testable without mocking the engine.
@@ -446,8 +573,7 @@ export class IntegrationSchemaSync {
446
573
  fieldsAuthoritativeByObject[r.srcObj.ExternalName] =
447
574
  r.srcObj.FieldsAreAuthoritative ?? SourceSchema.IsAuthoritative === true;
448
575
  objectIDByName[r.srcObj.ExternalName.toLowerCase()] = r.ObjectID;
449
- activeFieldsByObjectID[r.ObjectID] = engine
450
- .GetIntegrationObjectFields(r.ObjectID)
576
+ activeFieldsByObjectID[r.ObjectID] = (await writer.FieldsForObject(r.ObjectID))
451
577
  .filter((iof) => iof.Status === 'Active')
452
578
  .map((iof) => ({ ID: iof.ID, Name: iof.Name }));
453
579
  }
@@ -462,39 +588,54 @@ export class IntegrationSchemaSync {
462
588
  DiscoveredObjectNames: SourceSchema.Objects.map((o) => o.ExternalName),
463
589
  DiscoveredFieldNamesByObject: discoveredFieldNamesByObject,
464
590
  FieldsAuthoritativeByObject: fieldsAuthoritativeByObject,
465
- ActiveObjects: engine.GetActiveIntegrationObjects(IntegrationID).map((io) => ({ ID: io.ID, Name: io.Name })),
591
+ ActiveObjects: existingObjects.filter((io) => io.Status === 'Active').map((io) => ({ ID: io.ID, Name: io.Name })),
466
592
  ActiveFieldsByObjectID: activeFieldsByObjectID,
467
593
  ObjectIDByName: objectIDByName,
468
594
  });
469
595
  let deactivated = 0;
470
- for (const id of decision.ObjectIDsToDeactivate) {
471
- const obj = await md.GetEntityObject('MJ: Integration Objects', ContextUser);
472
- if (await obj.InnerLoad(CompositeKey.FromID(id))) {
473
- obj.Status = 'Disabled'; // deactivate (Active|Deprecated|Disabled enum); never delete
474
- if (await obj.Save()) {
475
- deactivated++;
476
- result.ObjectsDeactivated.push(obj.Name);
596
+ let removed = 0;
597
+ for (const id of retireObjects ? decision.ObjectIDsToDeactivate : []) {
598
+ const obj = await writer.LoadObject(id);
599
+ if (obj) {
600
+ // The WRITER decides disable-vs-delete: shared rows are the declared floor other
601
+ // connections read and are only disabled; a per-connection row is deleted outright,
602
+ // per plan.md ("Removed tables ... they just dont exist, its likely a cascade delete").
603
+ const name = obj.Name;
604
+ const outcome = await writer.RetireObject(obj);
605
+ if (outcome.ok) {
606
+ if (outcome.deleted)
607
+ removed++;
608
+ else
609
+ deactivated++;
610
+ result.ObjectsDeactivated.push(name);
611
+ }
612
+ else {
613
+ LogError(`[IntegrationSchemaSync] Failed to retire phantom object ${id}: ${obj.LatestResult?.CompleteMessage ?? 'unknown'}`);
477
614
  }
478
- else
479
- LogError(`[IntegrationSchemaSync] Failed to deactivate phantom object ${id}: ${obj.LatestResult?.CompleteMessage ?? 'unknown'}`);
480
615
  }
481
616
  }
482
617
  let fieldsDeactivated = 0;
483
- for (const id of decision.FieldIDsToDeactivate) {
484
- const f = await md.GetEntityObject('MJ: Integration Object Fields', ContextUser);
485
- if (await f.InnerLoad(CompositeKey.FromID(id))) {
486
- f.Status = 'Disabled'; // deactivate, never delete
487
- if (await f.Save()) {
618
+ // Name each retired field's owner from the rows this run already read. The engine cache would
619
+ // answer for the SHARED catalog only, so on a per-connection run it would silently miss and the
620
+ // log line would carry a bare id.
621
+ const objectNameByID = new Map(existingObjects.map((o) => [NormalizeUUID(o.ID), o.Name]));
622
+ for (const id of retireFields ? decision.FieldIDsToDeactivate : []) {
623
+ const f = await writer.LoadField(id);
624
+ if (f) {
625
+ const owner0 = f.IntegrationObjectID;
626
+ const fname = f.Name;
627
+ const outcome = await writer.RetireField(f);
628
+ if (outcome.ok) {
488
629
  fieldsDeactivated++;
489
- const owner = engine.GetIntegrationObjectByID(f.IntegrationObjectID)?.Name ?? f.IntegrationObjectID;
490
- result.FieldsDeactivated.push(`${owner}.${f.Name}`);
630
+ const owner = objectNameByID.get(NormalizeUUID(owner0)) ?? owner0;
631
+ result.FieldsDeactivated.push(`${owner}.${fname}`);
491
632
  }
492
633
  else
493
634
  LogError(`[IntegrationSchemaSync] Failed to deactivate phantom field ${id}: ${f.LatestResult?.CompleteMessage ?? 'unknown'}`);
494
635
  }
495
636
  }
496
- if (deactivated > 0 || fieldsDeactivated > 0)
497
- console.log(`[IntegrationSchemaSync] Deactivated ${deactivated} object(s) + ${fieldsDeactivated} field(s) absent from authoritative discovery for ${IntegrationID} (not materialized, not deleted).`);
637
+ if (deactivated > 0 || removed > 0 || fieldsDeactivated > 0)
638
+ console.log(`[IntegrationSchemaSync] Retired ${deactivated} disabled + ${removed} deleted object(s) and ${fieldsDeactivated} field(s) absent from authoritative discovery for ${IntegrationID}. Mirror tables and their data are untouched either way.`);
498
639
  }
499
640
  console.log(`[IntegrationSchemaSync] Persisted schema for ${IntegrationID}: ${result.ObjectsCreated} objects created, ${result.ObjectsUpdated} updated, ${result.FieldsCreated} fields created, ${result.FieldsUpdated} updated`);
500
641
  return result;
@@ -528,9 +669,36 @@ export class IntegrationSchemaSync {
528
669
  return out;
529
670
  }
530
671
  // ── Object upsert ────────────────────────────────────────────────
531
- static async upsertObject(md, integrationID, srcObj, existingObjects, contextUser) {
532
- const existing = existingObjects.find((o) => o.Name.toLowerCase() === srcObj.ExternalName.toLowerCase());
672
+ static async upsertObject(writer, srcObj, existingObjects,
673
+ /** The declared row this object was matched to, or null when it exists only here. */
674
+ declaredObject,
675
+ /** Whether the connector claims its object enumeration is complete. Decides provenance. */
676
+ discoveryIsAuthoritative) {
677
+ let existing = existingObjects.find((o) => o.Name.toLowerCase() === srcObj.ExternalName.toLowerCase());
678
+ // MJ-CAT-17. A per-connection catalog starts EMPTY, so on a connection's first discovery every
679
+ // declared object is "new" here even though the connector declared it. Creating it from the
680
+ // sample alone left APIPath = Name (every fetch 404'd), no pagination, no watermark field and no
681
+ // declared keys — observed on the sandbox 2026-09-11, first PheedLoop sync: 27 objects, 27 HTTP 404s,
682
+ // 0 rows. Seed the row FROM THE DECLARATION, then overlay exactly as for a row that already existed.
683
+ // On the shared catalog a declared object always IS the existing row, so this never fires there.
684
+ let seeded = false;
685
+ if (!existing && declaredObject) {
686
+ const row = await writer.NewObjectRow();
687
+ writer.StampNewObject(row, declaredObject.ID, 'Declared');
688
+ row.Name = declaredObject.Name;
689
+ row.Status = 'Active';
690
+ row.IsCustom = declaredObject.IsCustom;
691
+ row.MetadataSource = declaredObject.MetadataSource;
692
+ writer.RebaseFromDeclared(row, declaredObject, 'object');
693
+ existing = row;
694
+ seeded = true;
695
+ }
533
696
  if (existing) {
697
+ // The watermark column as it stood before this run touched the row. The rebase below can move
698
+ // it to the declared value and the overlay can move it straight back, so the step list in
699
+ // `changes` says nothing reliable about whether it CHANGED. ChangedAttributes reports it on its
700
+ // net change only (see the return below).
701
+ const watermarkBefore = existing.IncrementalWatermarkField ?? null;
534
702
  // Declared row exists. Overlay rule (external-wins-when-present): when the
535
703
  // EXTERNAL system returns a value for an attribute, that value overrides the curated
536
704
  // metadata; when the external system is SILENT on it, the curated value sticks. This is
@@ -540,6 +708,16 @@ export class IntegrationSchemaSync {
540
708
  // never overwritten; the spec inverts that precedence.)
541
709
  let dirty = false;
542
710
  const changes = [];
711
+ // plan.md: a refresh uses the DECLARATION as the source of truth and replaces what is in the
712
+ // per-connection row, rather than overlaying discovery onto that row's own previous output.
713
+ // Otherwise an open-app upgrade that changes a declared APIPath, page size or CRUD path never
714
+ // reaches a connection that has already discovered once. No-op for the shared catalog, where
715
+ // the row IS the declaration.
716
+ const rebased = writer.RebaseFromDeclared(existing, declaredObject, 'object');
717
+ if (rebased.length > 0) {
718
+ dirty = true;
719
+ changes.push(`rebased:${rebased.join('/')}`);
720
+ }
543
721
  const descOverlay = DecideSemanticOverlay(existing.Description, srcObj.Description);
544
722
  if (descOverlay.changed) {
545
723
  existing.Description = descOverlay.value ?? null;
@@ -571,12 +749,25 @@ export class IntegrationSchemaSync {
571
749
  dirty = true;
572
750
  changes.push('Status:reactivated');
573
751
  }
574
- if (dirty) {
752
+ if (dirty || seeded) {
753
+ // LastSeenAt rides the save we are already doing. It is deliberately NOT refreshed for an
754
+ // unchanged object: that would mean one extra round trip per object per run — 205 of them
755
+ // on the largest catalog here — to record a timestamp nothing currently reads. So it means
756
+ // "last run that changed this row", and the day something needs true last-seen it becomes
757
+ // a set-based UPDATE, not a per-row save.
758
+ writer.MarkSeen(existing, false);
759
+ // A failed save used to be swallowed whole. That is how a declared row silently kept a
760
+ // stale definition while the run reported success.
761
+ let saveError = null;
575
762
  try {
576
- await existing.Save();
763
+ if (!(await existing.Save()))
764
+ saveError = existing.LatestResult?.CompleteMessage ?? 'unknown validation failure';
765
+ }
766
+ catch (e) {
767
+ saveError = e instanceof Error ? e.message : String(e);
577
768
  }
578
- catch {
579
- /* ignore save failures on declared records */
769
+ if (saveError) {
770
+ LogError(`[IntegrationSchemaSync] Failed to update object '${srcObj.ExternalName}': ${saveError}`);
580
771
  }
581
772
  console.log(JSON.stringify({
582
773
  ts: new Date().toISOString(),
@@ -586,7 +777,12 @@ export class IntegrationSchemaSync {
586
777
  effectiveSource: 'Declared',
587
778
  fieldsTouched: changes,
588
779
  }));
589
- return { ObjectID: existing.ID, Created: false, Updated: true, EffectiveSource: 'Declared' };
780
+ // A row seeded from its declaration this run is CREATED, and a created row is never a change,
781
+ // so it reports none. Otherwise see ObjectChangedAttributes for why the watermark is netted.
782
+ const changedAttributes = seeded
783
+ ? []
784
+ : ObjectChangedAttributes(rebased, changes, watermarkBefore, existing.IncrementalWatermarkField ?? null);
785
+ return { ObjectID: existing.ID, Created: seeded, Updated: !seeded, EffectiveSource: 'Declared', ChangedAttributes: changedAttributes };
590
786
  }
591
787
  console.log(JSON.stringify({
592
788
  ts: new Date().toISOString(),
@@ -596,7 +792,7 @@ export class IntegrationSchemaSync {
596
792
  effectiveSource: 'Declared',
597
793
  reason: 'no-overlay-deltas',
598
794
  }));
599
- return { ObjectID: existing.ID, Created: false, Updated: false, EffectiveSource: 'Declared' };
795
+ return { ObjectID: existing.ID, Created: false, Updated: false, EffectiveSource: 'Declared', ChangedAttributes: [] };
600
796
  }
601
797
  // New row — mark as 'Discovered' by default. Vendor-signaled custom objects
602
798
  // (e.g. HubSpot namespace, Salesforce __c suffix) should be promoted to
@@ -604,9 +800,13 @@ export class IntegrationSchemaSync {
604
800
  // PersistDiscoveredSchema is called; absent a signal, 'Discovered' is the
605
801
  // safer label.
606
802
  try {
607
- const obj = await md.GetEntityObject('MJ: Integration Objects', contextUser);
608
- obj.NewRecord();
609
- obj.IntegrationID = integrationID;
803
+ const obj = await writer.NewObjectRow();
804
+ // Ownership and provenance. On the shared catalog this writes the integration id and nothing
805
+ // else, exactly as before. Provenance is coarse ON PURPOSE: a row is 'Declared' when a
806
+ // curated definition matched it, 'Endpoint' when the connector's own enumeration claimed to
807
+ // be complete, and 'Sampled' otherwise. The per-attribute truth lives in the merge log, not
808
+ // in this single column.
809
+ writer.StampNewObject(obj, declaredObject?.ID ?? null, declaredObject ? 'Declared' : (discoveryIsAuthoritative ? 'Endpoint' : 'Sampled'));
610
810
  obj.Name = srcObj.ExternalName;
611
811
  // APIPath is NOT NULL with no DB default. Declared objects get it from the metadata file;
612
812
  // a runtime-DISCOVERED object has no source APIPath (ExternalObjectSchema carries none),
@@ -633,7 +833,7 @@ export class IntegrationSchemaSync {
633
833
  effectiveSource: 'Discovered',
634
834
  metadataSource: 'Discovered',
635
835
  }));
636
- return { ObjectID: obj.ID, Created: true, Updated: false, EffectiveSource: 'Discovered' };
836
+ return { ObjectID: obj.ID, Created: true, Updated: false, EffectiveSource: 'Discovered', ChangedAttributes: [] };
637
837
  }
638
838
  // Save() returned false (validation/constraint failure) WITHOUT throwing — SURFACE it.
639
839
  // A silent false here is exactly how discovered objects vanished with zero signal.
@@ -642,18 +842,66 @@ export class IntegrationSchemaSync {
642
842
  catch (err) {
643
843
  console.warn(`[IntegrationSchemaSync] Failed to create IntegrationObject '${srcObj.ExternalName}': ${err instanceof Error ? err.message : err}`);
644
844
  }
645
- return { ObjectID: null, Created: false, Updated: false, EffectiveSource: 'Discovered' };
845
+ return { ObjectID: null, Created: false, Updated: false, EffectiveSource: 'Discovered', ChangedAttributes: [] };
646
846
  }
647
847
  // ── Field upsert ─────────────────────────────────────────────────
648
- static async upsertField(md, objectID, srcField, existingFields, contextUser, siblingNameToID, objectHasDeclaredPK = false) {
848
+ static async upsertField(writer, objectID, srcField, existingFields, siblingNameToID, objectHasDeclaredPK,
849
+ /** Whether the connector claims its field enumeration for this object is complete. */
850
+ fieldsAuthoritative,
851
+ /** The declared field this was matched to, or null when it exists only here. */
852
+ declaredFieldID = null,
853
+ /** The declared field ROW, when the caller has it — what a first discovery seeds from (MJ-CAT-17). */
854
+ declaredField = null) {
649
855
  const resolveFK = (target) => {
650
856
  if (!target || !siblingNameToID)
651
857
  return undefined;
652
858
  return siblingNameToID.get(target.toLowerCase());
653
859
  };
654
- const existing = existingFields.find((f) => f.Name.toLowerCase() === srcField.Name.toLowerCase());
860
+ let existing = existingFields.find((f) => f.Name.toLowerCase() === srcField.Name.toLowerCase());
861
+ // MJ-CAT-17 — see upsertObject. A declared field with no per-connection row yet is seeded from the
862
+ // declaration (type, width, key flags, sequence) and then overlaid like an existing row.
863
+ let seeded = false;
864
+ let fieldDirtyFromAdoption = false;
865
+ if (!existing && declaredField) {
866
+ const row = await writer.NewFieldRow();
867
+ writer.StampNewField(row, declaredField.ID, 'Declared');
868
+ row.IntegrationObjectID = objectID;
869
+ row.Name = declaredField.Name;
870
+ row.Status = 'Active';
871
+ row.IsCustom = declaredField.IsCustom;
872
+ row.MetadataSource = declaredField.MetadataSource;
873
+ writer.RebaseFromDeclared(row, declaredField, 'field');
874
+ existing = row;
875
+ seeded = true;
876
+ }
655
877
  const winners = {};
656
878
  if (existing) {
879
+ // MJ-CAT-21 — re-assert the DECLARATION on a row that already exists.
880
+ //
881
+ // upsertObject does this for objects (see its existing-row branch) under a comment that
882
+ // states the reason: a refresh uses the declaration as the source of truth for a
883
+ // per-connection row rather than overlaying discovery onto that row's own previous output.
884
+ // Fields never got the same treatment, so a connector release that changed a declared FIELD
885
+ // — its type, its width, its key flags — reached only connections that had never seen that
886
+ // field, and silently skipped every connection that already had it.
887
+ //
888
+ // Observed: PheedLoop 1.4.6 added `eventCode` to the Attendees primary key. A connection that
889
+ // had discovered `eventCode` from the source before 1.4.6 declared it already had the row, so
890
+ // the new key never landed — its catalog kept a single-column key while the declaration said
891
+ // two, and nothing reported a problem, because from the persist's point of view nothing
892
+ // changed.
893
+ //
894
+ // `AdoptDeclaration`, not `RebaseFromDeclared`: the rebase alone is not enough. The row still
895
+ // reads `MetadataSource = 'Discovered'`, and decidePKPromotion below uses exactly that to
896
+ // rule that a declared key cannot include this field — so the rebase would set IsPrimaryKey
897
+ // and have it demoted again before the row was ever saved. Adoption records that the row is
898
+ // declared now, which is what makes the decision downstream come out right.
899
+ if (!seeded && declaredField) {
900
+ const adopted = writer.AdoptDeclaration(existing, declaredField, 'field');
901
+ if (adopted.length > 0) {
902
+ fieldDirtyFromAdoption = true;
903
+ }
904
+ }
657
905
  // Declared row exists. Overlay rule — external-wins-when-present, per attribute:
658
906
  // - Describe wins for DDL-affecting attributes (Type, AllowsNull, IsRequired, IsPrimaryKey,
659
907
  // IsUniqueKey, IsReadOnly) whenever the source states an opinion; `undefined` = no opinion
@@ -667,7 +915,7 @@ export class IntegrationSchemaSync {
667
915
  // Returned attribute winners surface EXACTLY which source decided each
668
916
  // attribute so the caller (progress emitter, UI) can show structural
669
917
  // transparency on the merge.
670
- let dirty = false;
918
+ let dirty = fieldDirtyFromAdoption;
671
919
  // §7 REACTIVATE-on-rediscover: a field the source dropped (and we Disabled) that REAPPEARS flips
672
920
  // back to Active. existingFields includes Disabled rows, so it is reactivated, not duplicated.
673
921
  if (existing.Status !== 'Active') {
@@ -779,19 +1027,22 @@ export class IntegrationSchemaSync {
779
1027
  else if (existing.RelatedIntegrationObjectID) {
780
1028
  winners.ForeignKey = 'Declared';
781
1029
  }
782
- if (dirty) {
1030
+ if (dirty || seeded) {
783
1031
  const saved = await existing.Save();
784
1032
  if (!saved) {
785
1033
  console.warn(`[IntegrationSchemaSync] UpsertField save failed for '${srcField.Name}': ${existing.LatestResult?.CompleteMessage ?? 'unknown error'}`);
786
1034
  }
787
- return { Created: false, Updated: true, EffectiveSource: 'Declared', AttributeWinners: winners };
1035
+ return { Created: seeded, Updated: !seeded, EffectiveSource: 'Declared', AttributeWinners: winners };
788
1036
  }
789
1037
  return { Created: false, Updated: false, EffectiveSource: 'Declared', AttributeWinners: winners };
790
1038
  }
791
1039
  // New field — discovered for the first time
792
1040
  try {
793
- const field = await md.GetEntityObject('MJ: Integration Object Fields', contextUser);
794
- field.NewRecord();
1041
+ const field = await writer.NewFieldRow();
1042
+ writer.StampNewField(field, declaredFieldID, declaredFieldID ? 'Declared' : (fieldsAuthoritative ? 'Endpoint' : 'Sampled'));
1043
+ // On the per-connection catalog this column is a view alias of CompanyIntegrationObjectID and
1044
+ // the writer maps it; on the shared one it is the column itself. Either way the parent link
1045
+ // is written the same way here.
795
1046
  field.IntegrationObjectID = objectID;
796
1047
  field.Name = srcField.Name;
797
1048
  field.DisplayName = srcField.Label || srcField.Name;