instar 1.3.774 → 1.3.776

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 (64) hide show
  1. package/dist/commands/server.d.ts.map +1 -1
  2. package/dist/commands/server.js +222 -1
  3. package/dist/commands/server.js.map +1 -1
  4. package/dist/config/ConfigDefaults.d.ts.map +1 -1
  5. package/dist/config/ConfigDefaults.js +28 -0
  6. package/dist/config/ConfigDefaults.js.map +1 -1
  7. package/dist/core/CoherenceJournal.d.ts +1 -1
  8. package/dist/core/CoherenceJournal.d.ts.map +1 -1
  9. package/dist/core/CoherenceJournal.js +9 -2
  10. package/dist/core/CoherenceJournal.js.map +1 -1
  11. package/dist/core/OrchestratorActuator.d.ts +90 -0
  12. package/dist/core/OrchestratorActuator.d.ts.map +1 -0
  13. package/dist/core/OrchestratorActuator.js +88 -0
  14. package/dist/core/OrchestratorActuator.js.map +1 -0
  15. package/dist/core/OscillationBreaker.d.ts +46 -0
  16. package/dist/core/OscillationBreaker.d.ts.map +1 -0
  17. package/dist/core/OscillationBreaker.js +52 -0
  18. package/dist/core/OscillationBreaker.js.map +1 -0
  19. package/dist/core/PostUpdateMigrator.d.ts +1 -0
  20. package/dist/core/PostUpdateMigrator.d.ts.map +1 -1
  21. package/dist/core/PostUpdateMigrator.js +175 -0
  22. package/dist/core/PostUpdateMigrator.js.map +1 -1
  23. package/dist/core/SeamlessOrchestratorEngine.d.ts +167 -0
  24. package/dist/core/SeamlessOrchestratorEngine.d.ts.map +1 -0
  25. package/dist/core/SeamlessOrchestratorEngine.js +251 -0
  26. package/dist/core/SeamlessOrchestratorEngine.js.map +1 -0
  27. package/dist/core/WorkingSetArtifactManager.d.ts +104 -0
  28. package/dist/core/WorkingSetArtifactManager.d.ts.map +1 -0
  29. package/dist/core/WorkingSetArtifactManager.js +174 -0
  30. package/dist/core/WorkingSetArtifactManager.js.map +1 -0
  31. package/dist/core/WorkingSetArtifactReplicatedStore.d.ts +203 -0
  32. package/dist/core/WorkingSetArtifactReplicatedStore.d.ts.map +1 -0
  33. package/dist/core/WorkingSetArtifactReplicatedStore.js +384 -0
  34. package/dist/core/WorkingSetArtifactReplicatedStore.js.map +1 -0
  35. package/dist/core/WorkingSetManifest.d.ts +5 -0
  36. package/dist/core/WorkingSetManifest.d.ts.map +1 -1
  37. package/dist/core/WorkingSetManifest.js +10 -0
  38. package/dist/core/WorkingSetManifest.js.map +1 -1
  39. package/dist/core/WorkingSetPull.d.ts +5 -0
  40. package/dist/core/WorkingSetPull.d.ts.map +1 -1
  41. package/dist/core/WorkingSetPull.js +1 -0
  42. package/dist/core/WorkingSetPull.js.map +1 -1
  43. package/dist/core/WriteDomainRegistry.d.ts.map +1 -1
  44. package/dist/core/WriteDomainRegistry.js +32 -0
  45. package/dist/core/WriteDomainRegistry.js.map +1 -1
  46. package/dist/monitoring/OrchestratorPoller.d.ts +64 -0
  47. package/dist/monitoring/OrchestratorPoller.d.ts.map +1 -0
  48. package/dist/monitoring/OrchestratorPoller.js +132 -0
  49. package/dist/monitoring/OrchestratorPoller.js.map +1 -0
  50. package/dist/server/AgentServer.d.ts +2 -0
  51. package/dist/server/AgentServer.d.ts.map +1 -1
  52. package/dist/server/AgentServer.js +2 -0
  53. package/dist/server/AgentServer.js.map +1 -1
  54. package/dist/server/routes.d.ts +12 -0
  55. package/dist/server/routes.d.ts.map +1 -1
  56. package/dist/server/routes.js +155 -1
  57. package/dist/server/routes.js.map +1 -1
  58. package/package.json +1 -1
  59. package/src/data/builtin-manifest.json +65 -65
  60. package/src/templates/hooks/settings-template.json +10 -0
  61. package/upgrades/1.3.775.md +44 -0
  62. package/upgrades/1.3.776.md +44 -0
  63. package/upgrades/side-effects/intelligent-working-set-lazy-sync.md +220 -0
  64. package/upgrades/side-effects/llm-seamlessness-orchestrator.md +240 -0
@@ -1 +1 @@
1
- {"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../../src/commands/server.ts"],"names":[],"mappings":"AAAA;;;;;;;;GA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AC,EAAE,MAAM,OAAO,8BAA8B,EAAE,WAAW,GAAG,IAAI,EAK5E,qBAAqB,CAAC,EAAE,MAAM,OAAO,gCAAgC,EAAE,kBAAkB,GAAG,IAAI,EAKhG,mBAAmB,CAAC,EAAE,MAAM,MAAM,GAAG,IAAI,GAAG,SAAS,EAQrD,oBAAoB,CAAC,EAAE,MAAM;IAC3B,YAAY,EAAE,OAAO,kBAAkB,EAAE,oBAAoB,GAAG,IAAI,CAAC;IACrE,OAAO,EAAE,OAAO,CAAC;IACjB,MAAM,EAAE,OAAO,CAAC;IAChB,aAAa,EAAE,MAAM,CAAC;IACtB,SAAS,EAAE,MAAM,CAAC;IAClB,YAAY,EAAE,MAAM,CAAC;IACrB,SAAS,EAAE,MAAM,GAAG,UAAU,GAAG,SAAS,CAAC;IAC3C,QAAQ,EAAE,MAAM,CAAC;CAClB,GAAG,IAAI,GACP,IAAI,CAonBN;AA2lBD,wBAAsB,WAAW,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CAirmBtE;AAED,wBAAsB,UAAU,CAAC,OAAO,EAAE;IAAE,GAAG,CAAC,EAAE,MAAM,CAAA;CAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAsDzE;AAED;;;;;;;;;;;GAWG;AACH,wBAAsB,aAAa,CAAC,OAAO,EAAE;IAAE,GAAG,CAAC,EAAE,MAAM,CAAA;CAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAuD5E"}
@@ -3710,6 +3710,13 @@ export async function startServer(options) {
3710
3710
  // the mesh client) can reference it lazily; constructed in the mesh-wiring
3711
3711
  // block ONLY under the same explicit replication gate.
3712
3712
  let workingSetPullCoordinator;
3713
+ // Source-3 interactive-artifact manager (intelligent-working-set-lazy-sync). File-backed
3714
+ // (.instar/working-set/artifacts.json), hoisted so ONE instance is shared by the read-side
3715
+ // (WorkingSetPullServer), the replication emit-side (setReplicationEmitter), AND the recorder
3716
+ // route (POST /coherence/working-set/record). Sharing matters: the emit seam attaches to this
3717
+ // instance, so an artifact recorded via the route replicates when the flag is enabled.
3718
+ // Assigned lazily (??=) at whichever of those sites runs first; undefined ⇒ the routes 503.
3719
+ let workingSetArtifactManager;
3713
3720
  // Commitments-coherence receive side (COMMITMENTS-COHERENCE-SPEC §3.2) —
3714
3721
  // same explicit replication gate; undefined = dark (verb answers
3715
3722
  // 'disabled', merge layer returns own rows only).
@@ -3788,9 +3795,21 @@ export async function startServer(options) {
3788
3795
  const wsReaderMod = await import('../core/CoherenceJournalReader.js');
3789
3796
  const wsReader = new wsReaderMod.CoherenceJournalReader({ stateDir: config.stateDir });
3790
3797
  const ws = cjCfg?.workingSet;
3798
+ // Source 3 (intelligent-working-set-lazy-sync): the interactive-artifact manager.
3799
+ // File-backed, so this read-side instance sees the same artifacts.json the
3800
+ // replication-side instance (constructed later for the emit seam) writes. Only
3801
+ // READY rows nominate; each relPath is re-jailed by the canonical validator here
3802
+ // AND re-jailed + scanned inside computeWorkingSet (defense in depth).
3803
+ const wsArtStoreMod = await import('../core/WorkingSetArtifactReplicatedStore.js');
3804
+ const wsArtMgrMod = await import('../core/WorkingSetArtifactManager.js');
3805
+ const wsArtifactMgrServe = (workingSetArtifactManager ??= new wsArtMgrMod.WorkingSetArtifactManager(config.stateDir));
3791
3806
  workingSetPullServer = new wsMod.WorkingSetPullServer({
3792
3807
  stateDir: config.stateDir,
3793
3808
  readRuns: (topic) => wsReader.readOwnAutonomousRuns(topic, cjMachineId),
3809
+ readInteractiveArtifacts: (topic) => wsArtifactMgrServe
3810
+ .getReadyRows(topic)
3811
+ .map((r) => r.relPath)
3812
+ .filter((rel) => wsArtStoreMod.jailValidateRelPath(rel) !== null),
3794
3813
  caps: {
3795
3814
  ...(ws?.maxFileBytes != null ? { maxFileBytes: ws.maxFileBytes } : {}),
3796
3815
  ...(ws?.headlineFileBytes != null ? { headlineFileBytes: ws.headlineFileBytes } : {}),
@@ -3965,6 +3984,18 @@ export async function startServer(options) {
3965
3984
  // the file body), keyed on a content fingerprint (KnowledgeReplicatedStore.deriveKnowledgeRecordKey).
3966
3985
  const { KNOWLEDGE_KIND_REGISTRATION } = await import('../core/KnowledgeReplicatedStore.js');
3967
3986
  replicatedKindRegistry.register(KNOWLEDGE_KIND_REGISTRATION);
3987
+ // intelligent-working-set-lazy-sync — register the `working-set-artifact` replicated
3988
+ // kind (a per-topic index of files the agent wrote INTERACTIVELY under the .instar/
3989
+ // jail, so an interactive artifact follows a conversation across machines — the case
3990
+ // the computed WorkingSetManifest engine misses). Dual-registry's dynamic half (the
3991
+ // static half is CoherenceJournal.JOURNAL_KINDS, which now lists 'working-set-artifact').
3992
+ // Registration is INERT — emission/serve/pull stay gated behind
3993
+ // `multiMachine.stateSync.workingSetArtifact.enabled` (default false ⇒ strict no-op).
3994
+ // Only the row METADATA crosses (relPath/contentHash/state), keyed on a NON-path-shaped
3995
+ // sha256(jailedRelPath)+':'+producer surface; the file BODY is fetched by the existing
3996
+ // working-set engine, never replicated here.
3997
+ const { WORKING_SET_ARTIFACT_KIND_REGISTRATION } = await import('../core/WorkingSetArtifactReplicatedStore.js');
3998
+ replicatedKindRegistry.register(WORKING_SET_ARTIFACT_KIND_REGISTRATION);
3968
3999
  // WS2.5 (multi-machine-replicated-store-foundation) — register the FIFTH concrete
3969
4000
  // replicated kind, `evolution-action-record`, onto the registry: the FOURTH memory-family
3970
4001
  // kind (after WS2.4 knowledge + WS2.2 learnings + WS2.3 relationships). Dual-registry's
@@ -10546,6 +10577,69 @@ export async function startServer(options) {
10546
10577
  emitDelete: (title, url, type, deletedAt) => emitter.emit(KNOWLEDGE_STORE_KEY, deriveKnowledgeRecordKey(title, url, type), (hlc, origin, observed) => buildKnowledgeTombstoneData({ title, url, type, hlc, origin, deletedAt, observed })),
10547
10578
  });
10548
10579
  }
10580
+ // intelligent-working-set-lazy-sync — the union reader for the `workingSetArtifact`
10581
+ // store. loadOriginRecords materializes the OWN interactive-artifact rows (via
10582
+ // workingSetArtifactToOriginRecord, keyed on the NON-path-shaped
10583
+ // sha256(jailedRelPath)+':'+producer surface); peer replicas land via the journal-apply
10584
+ // path (a later rollout stage). With only the own origin the union is a strict no-op.
10585
+ // tierOf HIGH (append-both-and-flag; the READ layer is advisory). The emit seam is
10586
+ // attached ONLY when stateSync.workingSetArtifact.enabled is true (default false ⇒ NOT
10587
+ // injected ⇒ strict no-op). The manager is ALSO the recorder route's write target.
10588
+ const { workingSetArtifactTierOf, workingSetArtifactToOriginRecord, deriveWorkingSetArtifactRecordKey, buildWorkingSetArtifactData, buildWorkingSetArtifactTombstoneData, WORKING_SET_ARTIFACT_STORE_KEY, } = await import('../core/WorkingSetArtifactReplicatedStore.js');
10589
+ const { WorkingSetArtifactManager } = await import('../core/WorkingSetArtifactManager.js');
10590
+ // Consolidate onto the hoisted instance (shared with the read-side + the recorder route).
10591
+ // The local alias carries the definite type for use inside the reader/emit closures.
10592
+ const wsArtMgr = (workingSetArtifactManager ??= new WorkingSetArtifactManager(config.stateDir));
10593
+ // Boot-time record GC (intelligent-working-set-lazy-sync F3): purge interactive-artifact
10594
+ // rows older than the record TTL so the metadata catalog stays bounded across restarts
10595
+ // (a LOCAL cleanup, not a tombstone — a peer's copy ages out under its own TTL). Distinct
10596
+ // from the engine's 7d pending-pull TTL.
10597
+ try {
10598
+ const wsTtlDays = config.coherenceJournal?.workingSet?.recordTtlDays;
10599
+ const wsTtlMs = (typeof wsTtlDays === 'number' && wsTtlDays > 0 ? wsTtlDays : 30) * 24 * 60 * 60 * 1000;
10600
+ const wsPurged = wsArtMgr.gc(wsTtlMs);
10601
+ if (wsPurged > 0)
10602
+ console.log(pc.dim(` [ws-artifact] GC purged ${wsPurged} record(s) older than ${Math.round(wsTtlMs / 86400000)}d`));
10603
+ }
10604
+ catch { /* @silent-fallback-ok: record GC is best-effort housekeeping, never fails boot */ }
10605
+ const workingSetArtifactUnionReader = new ReplicatedStoreReader({
10606
+ registry: replicatedKindRegistry,
10607
+ stores: _stateSyncStoresResolved,
10608
+ tierOf: workingSetArtifactTierOf,
10609
+ loadOriginRecords: (store, recordKey) => {
10610
+ if (store !== WORKING_SET_ARTIFACT_STORE_KEY || _meshSelfId === null)
10611
+ return [];
10612
+ for (const r of wsArtMgr.getAllRows()) {
10613
+ if (deriveWorkingSetArtifactRecordKey(r.relPath, _meshSelfId) === recordKey) {
10614
+ const o = workingSetArtifactToOriginRecord({ ...r, producerMachineId: _meshSelfId }, _meshSelfId);
10615
+ return o ? [o] : [];
10616
+ }
10617
+ }
10618
+ return [];
10619
+ },
10620
+ listRecordKeys: (store) => {
10621
+ if (store !== WORKING_SET_ARTIFACT_STORE_KEY || _meshSelfId === null)
10622
+ return [];
10623
+ const keys = [];
10624
+ for (const r of wsArtMgr.getAllRows()) {
10625
+ const k = deriveWorkingSetArtifactRecordKey(r.relPath, _meshSelfId);
10626
+ if (k !== null)
10627
+ keys.push(k);
10628
+ }
10629
+ return keys;
10630
+ },
10631
+ droppedOrigins: droppedOriginRegistry,
10632
+ conflictStore,
10633
+ });
10634
+ void workingSetArtifactUnionReader;
10635
+ if (replicatedRecordEmitter && _meshSelfId !== null) {
10636
+ const emitter = replicatedRecordEmitter;
10637
+ const selfId = _meshSelfId;
10638
+ wsArtMgr.setReplicationEmitter({
10639
+ emitPut: (row) => emitter.emit(WORKING_SET_ARTIFACT_STORE_KEY, deriveWorkingSetArtifactRecordKey(row.relPath, selfId), (hlc, origin, observed) => buildWorkingSetArtifactData({ row, hlc, origin, observed })),
10640
+ emitDelete: (d) => emitter.emit(WORKING_SET_ARTIFACT_STORE_KEY, deriveWorkingSetArtifactRecordKey(d.relPath, d.producerMachineId), (hlc, origin, observed) => buildWorkingSetArtifactTombstoneData({ relPath: d.relPath, producerMachineId: d.producerMachineId, hlc, origin, deletedAt: d.deletedAt, observed })),
10641
+ });
10642
+ }
10549
10643
  // WS2.5 — the bypass-proof union reader for the `evolutionActions` store. The single
10550
10644
  // funnel every replicated action read routes through, so no caller reads a raw replica
10551
10645
  // around the no-clobber rule. `loadOriginRecords` materializes the OWN action queue (the
@@ -13429,6 +13523,133 @@ export async function startServer(options) {
13429
13523
  }
13430
13524
  }
13431
13525
  void cartographerSweepPoller;
13526
+ // ── Seamless LLM orchestrator (llm-seamlessness-orchestrator.md §Component3) ──
13527
+ // A lease-gated tier-1 LLM loop for ANTICIPATORY working-set preload — PROPOSE-ONLY /
13528
+ // SIGNAL-ONLY (it never moves a conversation; placement stays with the deterministic
13529
+ // RebalancePlanner/PlacementExecutor). Modeled on the Cartographer sweep wiring above.
13530
+ // Dev-gated DARK (resolveDevAgentGate) + dryRun-FIRST: on the fleet it is never
13531
+ // constructed; on a dev agent it runs but actuates NOTHING (logs would-actuate + audits)
13532
+ // until an operator flips seamlessOrchestrator.dryRun:false. Readers/deps are tick-time
13533
+ // closures over the function-scoped lets (the first tick is cadenceMs out — long after
13534
+ // boot assigns leaseCoordinatorRef / workingSet* — so the closures are safe).
13535
+ let orchestratorPoller = null;
13536
+ {
13537
+ const soCfg = (config.multiMachine?.seamlessOrchestrator) ?? {};
13538
+ const soEnabled = resolveDevAgentGate(soCfg.enabled, config);
13539
+ if (soEnabled) {
13540
+ try {
13541
+ const soNum = (v, d) => (typeof v === 'number' && Number.isFinite(v) ? v : d);
13542
+ const { SeamlessOrchestratorEngine } = await import('../core/SeamlessOrchestratorEngine.js');
13543
+ const { OrchestratorActuator } = await import('../core/OrchestratorActuator.js');
13544
+ const { OrchestratorPoller } = await import('../monitoring/OrchestratorPoller.js');
13545
+ const { OscillationBreaker } = await import('../core/OscillationBreaker.js');
13546
+ const { ParallelActivityIndex: SOActivityIndex } = await import('../core/ParallelActivityIndex.js');
13547
+ const soActivityIndex = new SOActivityIndex({ stateDir: config.stateDir });
13548
+ const soBreaker = new OscillationBreaker({
13549
+ oscillationWindowMs: soNum(soCfg.oscillationWindowMs, 3_600_000),
13550
+ blacklistTtlMs: soNum(soCfg.blacklistTtlMs, 86_400_000),
13551
+ });
13552
+ const soDryRun = soCfg.dryRun !== false; // default true (dryRun-first)
13553
+ const soAuditPath = path.join(config.stateDir, '..', 'logs', 'orchestrator-actions.jsonl');
13554
+ const soSignalsPath = path.join(config.stateDir, '..', 'logs', 'orchestrator-placement-signals.jsonl');
13555
+ const soWindowMs = soNum(soCfg.prefetchWindowMs, 3_600_000);
13556
+ const soWindowBudget = soNum(soCfg.prefetchWindowByteBudget, 33_554_432);
13557
+ let soWindowStart = Date.now();
13558
+ const soWindowSpent = 0;
13559
+ const soCooldowns = new Map();
13560
+ const engine = new SeamlessOrchestratorEngine({
13561
+ reads: {
13562
+ activeTopicsOnThisMachine: () => soActivityIndex.activities(Date.now()).map((a) => ({
13563
+ topic: a.topicId, focus: a.focus ?? '', lastActivityMs: a.updatedAt ?? 0, running: a.running,
13564
+ })),
13565
+ workingSetRecords: (topic) => (workingSetArtifactManager?.getReadyRows(topic) ?? []).map((r) => ({
13566
+ relPath: r.relPath, producerMachineId: r.producerMachineId, state: r.state,
13567
+ })),
13568
+ },
13569
+ llmQueue: sharedLlmQueue,
13570
+ holdsLease: () => (leaseCoordinatorRef ? leaseCoordinatorRef.holdsLease() : true),
13571
+ pressure: () => ({ tier: sharedPressureTier() }),
13572
+ lastActuatedAt: (topic) => soCooldowns.get(topic) ?? null,
13573
+ isBlacklisted: (topic) => soBreaker.isBlacklisted(topic), // F6 oscillation breaker
13574
+ config: {
13575
+ maxProposalsPerTick: soNum(soCfg.maxProposalsPerTick, 3),
13576
+ llmLiftThreshold: typeof soCfg.llmLiftThreshold === 'number' ? soCfg.llmLiftThreshold : 0.15,
13577
+ perTopicCooldownMs: soNum(soCfg.perTopicCooldownMs, 1_800_000),
13578
+ suspendPressureTiers: ['moderate', 'critical'],
13579
+ dryRun: soDryRun,
13580
+ },
13581
+ log: (m) => console.log(pc.gray(m)),
13582
+ });
13583
+ const actuator = new OrchestratorActuator({
13584
+ // Dark-first conservative placement reader: exercised ONLY for dryRun AUDIT rows
13585
+ // (actuate() never fetches/moves while dryRun). Precise pin/provenance/episode
13586
+ // sourcing (pool placement + stale-owner/lease-handback episode state) is the
13587
+ // TRACKED prerequisite before any operator flip to dryRun:false (spec P4). [C3d gap]
13588
+ revalidate: () => ({ pinned: false, recentlyUserMoved: false, inFailureEpisode: false }),
13589
+ budgetRemainingBytes: () => {
13590
+ const nowT = Date.now();
13591
+ if (nowT - soWindowStart >= soWindowMs) {
13592
+ soWindowStart = nowT;
13593
+ }
13594
+ return Math.max(0, soWindowBudget - soWindowSpent);
13595
+ },
13596
+ estimatedBytes: (p) => {
13597
+ try {
13598
+ return fs.statSync(path.join(config.stateDir, p.detail)).size;
13599
+ }
13600
+ catch {
13601
+ return 65_536; /* @silent-fallback-ok: an un-stat-able candidate uses a nominal estimate; the budget check is soak-only under dryRun. */
13602
+ }
13603
+ },
13604
+ fetchWorkingSet: async (topic) => {
13605
+ if (!workingSetPullCoordinator)
13606
+ return { ok: false, skipReason: 'coordinator-unwired' };
13607
+ const o = await workingSetPullCoordinator.fetchWorkingSet(topic);
13608
+ return { ok: o.scheduled === true, skipReason: o.skipReason };
13609
+ },
13610
+ recordPlacementSignal: (p) => {
13611
+ try {
13612
+ fs.mkdirSync(path.dirname(soSignalsPath), { recursive: true });
13613
+ fs.appendFileSync(soSignalsPath, JSON.stringify({ ts: new Date().toISOString(), topic: p.targetTopic, detail: p.detail }) + '\n');
13614
+ }
13615
+ catch { /* @silent-fallback-ok: best-effort placement-signal record; a write failure never blocks the loop (the planner re-reads on its own cadence). */ }
13616
+ },
13617
+ audit: (e) => {
13618
+ try {
13619
+ fs.mkdirSync(path.dirname(soAuditPath), { recursive: true });
13620
+ fs.appendFileSync(soAuditPath, JSON.stringify(e) + '\n');
13621
+ }
13622
+ catch { /* @silent-fallback-ok: best-effort audit append (read-only observability); a write failure never blocks actuation. */ }
13623
+ },
13624
+ now: () => new Date().toISOString(),
13625
+ log: (m) => console.log(pc.gray(m)),
13626
+ config: { dryRun: soDryRun },
13627
+ });
13628
+ orchestratorPoller = new OrchestratorPoller({
13629
+ engine,
13630
+ actuator,
13631
+ cadenceMs: soNum(soCfg.cadenceMs, 900_000),
13632
+ idleCadenceMs: soNum(soCfg.idleCadenceMs, 1_800_000),
13633
+ recordActuated: (topic, nowT) => {
13634
+ soCooldowns.set(topic, nowT);
13635
+ // F6 oscillation breaker: record the actuation; a one-shot `true` = the topic just
13636
+ // tripped the blacklist. In dryRun nothing actuates so this is inert; the deduped
13637
+ // attention-item raise + WS2 blacklist replication ride the same P4-live prerequisite
13638
+ // bundle as the revalidate-precision sourcing. [C4 tracked gap]
13639
+ if (soBreaker.recordActuation(topic, nowT)) {
13640
+ console.warn(` Seamless orchestrator: topic ${topic} tripped the oscillation blacklist (suppressed).`);
13641
+ }
13642
+ },
13643
+ log: (m) => console.log(pc.gray(m)),
13644
+ });
13645
+ orchestratorPoller.start();
13646
+ console.log(pc.green(` Seamless LLM orchestrator enabled (lease-gated, ${soDryRun ? 'dry-run' : 'LIVE'})`));
13647
+ }
13648
+ catch (err) {
13649
+ console.warn(' Seamless LLM orchestrator: construction failed —', err instanceof Error ? err.message : err);
13650
+ }
13651
+ }
13652
+ }
13432
13653
  // Self-Knowledge Tree — tree-based agent self-knowledge with LLM triage
13433
13654
  let selfKnowledgeTree;
13434
13655
  let coverageAuditor;
@@ -21118,7 +21339,7 @@ export async function startServer(options) {
21118
21339
  const server = new AgentServer({ config, sessionManager, state, scheduler, telegram, relationships, feedback, feedbackAnomalyDetector, dispatches, updateChecker, autoUpdater, autoDispatcher, quotaTracker, quotaManager, publisher, viewer, tunnel, evolution, watchdog, topicMemory, triageNurse, projectMapper, cartographer: cartographer ?? undefined, coherenceGate: scopeVerifier, contextHierarchy, canonicalState, operationGate, sentinel, adaptiveTrust, memoryMonitor, orphanReaper, coherenceMonitor, commitmentTracker, subscriptionPool, accountFollowMePeerViews: async () => { const nickById = new Map((_listPoolMachines?.() ?? []).map((m) => [m.machineId, m.nickname ?? m.machineId])); let peers = (_resolvePeerUrls?.() ?? []).map((p) => ({ machineId: p.machineId, nickname: nickById.get(p.machineId) ?? p.machineId, url: p.url })); if (peers.length === 0) {
21119
21340
  peers = (_listPoolMachines?.() ?? []).filter((m) => m.machineId !== _meshSelfId && !!m.lastKnownUrl).map((m) => ({ machineId: m.machineId, nickname: m.nickname ?? m.machineId, url: m.lastKnownUrl }));
21120
21341
  } if (peers.length === 0)
21121
- return []; const { fetchPeerSubscriptionViews } = await import('../core/fetchPeerSubscriptionViews.js'); return fetchPeerSubscriptionViews({ peers: () => peers, fetchImpl: fetch, authToken: config.authToken ?? '' }); }, quotaPoller, quotaAwareScheduler: _quotaAwareScheduler ?? undefined, proactiveSwapMonitor: _proactiveSwapMonitor ?? undefined, inUseAccountResolver, enrollmentWizard, accountFollowMeRevocation, credentialRepointing, semanticMemory, activitySentinel, rateLimitSentinel, releaseReadinessSentinel: releaseReadinessSentinel ?? undefined, greenPrAutoMerger: greenPrAutoMerger ?? undefined, guardLatchStore: guardLatchStore ?? undefined, messageRouter, summarySentinel, spawnManager, systemReviewer, capabilityMapper, selfKnowledgeTree, coverageAuditor, topicResumeMap: _topicResumeMap ?? undefined, topicProfile: _topicProfileCtx ?? undefined, sessionRefresh: _sessionRefresh ?? undefined, autonomyManager, trustElevationTracker, autonomousEvolution, coordinator: coordinator.enabled ? coordinator : undefined, meshBindActive: coordinator.managers.identityManager.hasIdentity() && config.multiMachine?.meshTransport?.enabled !== false, localSigningKeyPem, leaseTransport, peerEndpointRecorder, getSelfMeshEndpoints, onLeasePullRequest: () => leaseCoordinatorRef?.currentLease() ?? null, liveTailReceiver, handoffWireTransport, onHandoffBegin, onHandoffInitiate: handoffInitiate, handoffInProgress: handoffSentinelInProgress, messageLedger, currentInboundByTopic, replyMarkerTransport, onReplyMarker: messageLedger ? (marker) => { const m = marker; messageLedger.applyRemoteReplyMarker(m.dedupeKey, { platform: m.platform, replyIdempotencyKey: m.replyIdempotencyKey, epoch: m.epoch, topic: m.topic ?? null }); } : undefined, whatsapp: whatsappAdapter, slack: slackAdapter, imessage: imessageAdapter, conversationRegistry, conversationBindAuth, conversationFollowThrough, whatsappBusinessBackend, messageBridge, hookEventReceiver, worktreeMonitor, subagentTracker, instructionsVerifier, handshakeManager: threadlineHandshake, threadlineRouter, conversationStore, threadLog, threadMessageRecorder, warrantsReplyGate, collaborationSurfacer, threadResumeMap, topicLinkageHandler: topicLinkageHandler ?? undefined, threadlineRelayClient, threadlineReplyWaiters, listenerManager: listenerManager ?? undefined, a2aDeliveryTracker: a2aDeliveryTracker ?? undefined, responseReviewGate, reviewCanaryBattery, messagingToneGate, outboundDedupGate, telemetryHeartbeat, pasteManager, featureRegistry, discoveryEvaluator, completionEvaluator, unifiedTrust, liveConfig, sharedStateLedger, ledgerSessionRegistry, worktreeManager, oidcEnrolledRepos: parallelDevConfig?.oidcEnrolledRepos, initiativeTracker, projectRoundRunner, projectDriftChecker, machineHeartbeat, machinePoolRegistry, ropeHealthMonitor, writeAdmission: writeAdmission ?? undefined, getInboundQueue: () => _inboundQueue, getMachineCoherence: () => _machineCoherenceSentinel, meshRpcDispatcher, workingSetPullCoordinator, commitmentReplicaStore, preferenceReplicaStore, replicatedRecordEmitter, conflictStore, rollbackUnmerge, droppedOriginRegistry, preferencesUnionReader, forwardCommitmentMutate, sessionOwnershipRegistry, topicPinStore: _topicPinStore ?? undefined, topicPinSkewQuarantine: _topicPinSkewQuarantine ?? undefined, topicPinFoldView: _topicPinFoldView ?? undefined, ownershipReconciler: _ownershipReconciler ?? undefined, staleOwnerEngine: _staleOwnerEngine ?? undefined, leaseHandback: _leaseHandbackCtx ?? undefined, streamTicketStore: _streamTicketStore ?? undefined, poolStreamAllowRemoteInput: config.dashboard?.poolStream?.allowRemoteInput ?? false, poolStreamConnector: _poolStreamConnector ?? undefined, secretSync: _secretSyncHandle ?? undefined, meshSelfId: _meshSelfId ?? undefined, resolveRouterUrl: _resolveRouterUrl ?? undefined, resolvePeerUrls: _resolvePeerUrls ?? undefined, guardRegistry, listPoolMachines: _listPoolMachines ?? undefined, deliverMandateToMachine: _deliverMandateToMachine ?? undefined, poolLink: _poolLink ?? undefined, poolPollCache: _poolPollCache ?? undefined, sessionPoolE2EResultStore, proxyCoordinator, topicIntentStore, topicIntentArcCheck, usherSignalStore, intelligence: sharedIntelligence ?? undefined, telegramBridgeConfig, telegramBridge: telegramBridge ?? undefined, threadlineObservability, briefDeps, workingMemory, taskFlowRegistry, threadlineFlowBridge, sessionReaper, agentWorktreeReaper, externalHogSentinel, orphanedWorkSentinel, mcpProcessReaper, geminiLoopRunner, sleepController, agentActivityState, reapLog, resumeQueue, resumeDrainer, autonomousLivenessReconciler, enforcedTerminationStatus: () => enforcedTerminationWatchdog?.guardStatus() ?? null, prHandLease: prHandLease ?? undefined, operatorStopRecorder: recordOperatorStop, sleepWakeDetector, unjustifiedStopGate, stopGateDb, stopNotifier, liveTestGate, liveTestGateMode, liveTestRunnerCtx }); // Resolve the late-bound topic-operator getter (increment 2e): routing was
21342
+ return []; const { fetchPeerSubscriptionViews } = await import('../core/fetchPeerSubscriptionViews.js'); return fetchPeerSubscriptionViews({ peers: () => peers, fetchImpl: fetch, authToken: config.authToken ?? '' }); }, quotaPoller, quotaAwareScheduler: _quotaAwareScheduler ?? undefined, proactiveSwapMonitor: _proactiveSwapMonitor ?? undefined, inUseAccountResolver, enrollmentWizard, accountFollowMeRevocation, credentialRepointing, semanticMemory, activitySentinel, rateLimitSentinel, releaseReadinessSentinel: releaseReadinessSentinel ?? undefined, greenPrAutoMerger: greenPrAutoMerger ?? undefined, guardLatchStore: guardLatchStore ?? undefined, messageRouter, summarySentinel, spawnManager, systemReviewer, capabilityMapper, selfKnowledgeTree, coverageAuditor, topicResumeMap: _topicResumeMap ?? undefined, topicProfile: _topicProfileCtx ?? undefined, sessionRefresh: _sessionRefresh ?? undefined, autonomyManager, trustElevationTracker, autonomousEvolution, coordinator: coordinator.enabled ? coordinator : undefined, meshBindActive: coordinator.managers.identityManager.hasIdentity() && config.multiMachine?.meshTransport?.enabled !== false, localSigningKeyPem, leaseTransport, peerEndpointRecorder, getSelfMeshEndpoints, onLeasePullRequest: () => leaseCoordinatorRef?.currentLease() ?? null, liveTailReceiver, handoffWireTransport, onHandoffBegin, onHandoffInitiate: handoffInitiate, handoffInProgress: handoffSentinelInProgress, messageLedger, currentInboundByTopic, replyMarkerTransport, onReplyMarker: messageLedger ? (marker) => { const m = marker; messageLedger.applyRemoteReplyMarker(m.dedupeKey, { platform: m.platform, replyIdempotencyKey: m.replyIdempotencyKey, epoch: m.epoch, topic: m.topic ?? null }); } : undefined, whatsapp: whatsappAdapter, slack: slackAdapter, imessage: imessageAdapter, conversationRegistry, conversationBindAuth, conversationFollowThrough, whatsappBusinessBackend, messageBridge, hookEventReceiver, worktreeMonitor, subagentTracker, instructionsVerifier, handshakeManager: threadlineHandshake, threadlineRouter, conversationStore, threadLog, threadMessageRecorder, warrantsReplyGate, collaborationSurfacer, threadResumeMap, topicLinkageHandler: topicLinkageHandler ?? undefined, threadlineRelayClient, threadlineReplyWaiters, listenerManager: listenerManager ?? undefined, a2aDeliveryTracker: a2aDeliveryTracker ?? undefined, responseReviewGate, reviewCanaryBattery, messagingToneGate, outboundDedupGate, telemetryHeartbeat, pasteManager, featureRegistry, discoveryEvaluator, completionEvaluator, unifiedTrust, liveConfig, sharedStateLedger, ledgerSessionRegistry, worktreeManager, oidcEnrolledRepos: parallelDevConfig?.oidcEnrolledRepos, initiativeTracker, projectRoundRunner, projectDriftChecker, machineHeartbeat, machinePoolRegistry, ropeHealthMonitor, writeAdmission: writeAdmission ?? undefined, getInboundQueue: () => _inboundQueue, getMachineCoherence: () => _machineCoherenceSentinel, meshRpcDispatcher, workingSetPullCoordinator, workingSetArtifactManager, orchestratorPoller, commitmentReplicaStore, preferenceReplicaStore, replicatedRecordEmitter, conflictStore, rollbackUnmerge, droppedOriginRegistry, preferencesUnionReader, forwardCommitmentMutate, sessionOwnershipRegistry, topicPinStore: _topicPinStore ?? undefined, topicPinSkewQuarantine: _topicPinSkewQuarantine ?? undefined, topicPinFoldView: _topicPinFoldView ?? undefined, ownershipReconciler: _ownershipReconciler ?? undefined, staleOwnerEngine: _staleOwnerEngine ?? undefined, leaseHandback: _leaseHandbackCtx ?? undefined, streamTicketStore: _streamTicketStore ?? undefined, poolStreamAllowRemoteInput: config.dashboard?.poolStream?.allowRemoteInput ?? false, poolStreamConnector: _poolStreamConnector ?? undefined, secretSync: _secretSyncHandle ?? undefined, meshSelfId: _meshSelfId ?? undefined, resolveRouterUrl: _resolveRouterUrl ?? undefined, resolvePeerUrls: _resolvePeerUrls ?? undefined, guardRegistry, listPoolMachines: _listPoolMachines ?? undefined, deliverMandateToMachine: _deliverMandateToMachine ?? undefined, poolLink: _poolLink ?? undefined, poolPollCache: _poolPollCache ?? undefined, sessionPoolE2EResultStore, proxyCoordinator, topicIntentStore, topicIntentArcCheck, usherSignalStore, intelligence: sharedIntelligence ?? undefined, telegramBridgeConfig, telegramBridge: telegramBridge ?? undefined, threadlineObservability, briefDeps, workingMemory, taskFlowRegistry, threadlineFlowBridge, sessionReaper, agentWorktreeReaper, externalHogSentinel, orphanedWorkSentinel, mcpProcessReaper, geminiLoopRunner, sleepController, agentActivityState, reapLog, resumeQueue, resumeDrainer, autonomousLivenessReconciler, enforcedTerminationStatus: () => enforcedTerminationWatchdog?.guardStatus() ?? null, prHandLease: prHandLease ?? undefined, operatorStopRecorder: recordOperatorStop, sleepWakeDetector, unjustifiedStopGate, stopGateDb, stopNotifier, liveTestGate, liveTestGateMode, liveTestRunnerCtx }); // Resolve the late-bound topic-operator getter (increment 2e): routing was
21122
21343
  // wired before the server existed; from here on inbound binds use the
21123
21344
  // server's own store instance.
21124
21345
  _agentServerRef = server;