instar 1.3.370 → 1.3.372

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.
@@ -1 +1 @@
1
- {"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../../src/commands/server.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AA6SH,UAAU,YAAY;IACpB,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb;2DACuD;IACvD,QAAQ,CAAC,EAAE,OAAO,CAAC;CACpB;AAuxDD,wBAAsB,WAAW,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CA8gTtE;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"}
1
+ {"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../../src/commands/server.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AA6SH,UAAU,YAAY;IACpB,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb;2DACuD;IACvD,QAAQ,CAAC,EAAE,OAAO,CAAC;CACpB;AAuxDD,wBAAsB,WAAW,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CAwpTtE;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"}
@@ -2367,6 +2367,13 @@ export async function startServer(options) {
2367
2367
  // same explicit replication gate; undefined = dark (verb answers
2368
2368
  // 'disabled', merge layer returns own rows only).
2369
2369
  let commitmentReplicaStore;
2370
+ // P1.5b owner-routed mutation (§3.4): the owner-side replay window, the
2371
+ // forwarder-side durable intent queue, and the route-facing forward fn.
2372
+ // All undefined while dark.
2373
+ let commitmentOpKeyWindow;
2374
+ let pendingMutationLedger;
2375
+ let _commitmentReFire;
2376
+ let forwardCommitmentMutate;
2370
2377
  {
2371
2378
  const cjCfg = config.multiMachine?.coherenceJournal;
2372
2379
  const cjEnabled = cjCfg?.enabled ?? !!config.developmentAgent;
@@ -9957,6 +9964,23 @@ export async function startServer(options) {
9957
9964
  return { ok: false, reason: 'working-set disabled' };
9958
9965
  return workingSetPullServer.handle(cmd);
9959
9966
  },
9967
+ // COMMITMENTS-COHERENCE-SPEC §3.4 — owner-side apply for the
9968
+ // owner-routed mutation. opKey window first (replay returns the
9969
+ // recorded verdict, applies nothing); the UNCHANGED state machine
9970
+ // re-validates; the opKey records AFTER the store write (§4.5 —
9971
+ // a crash between resolves as idempotent-noop on the re-fire).
9972
+ 'commitment-mutate': async (cmd) => {
9973
+ const c = cmd;
9974
+ if (!commitmentOpKeyWindow || !commitmentTracker)
9975
+ return { ok: false, reason: 'commitment-mutate disabled' };
9976
+ const mutMod = await import('../core/CommitmentMutation.js');
9977
+ const replay = commitmentOpKeyWindow.check(c.payload.opKey);
9978
+ if (replay)
9979
+ return { verdict: replay.verdict, ...(replay.status ? { status: replay.status } : {}), replayed: true };
9980
+ const outcome = await mutMod.applyOwnerMutation(commitmentTracker, c.payload);
9981
+ commitmentOpKeyWindow.record(c.payload.opKey, outcome);
9982
+ return outcome;
9983
+ },
9960
9984
  // COMMITMENTS-COHERENCE-SPEC §3.2 — serve OWN commitment records
9961
9985
  // as seq-windowed delta pages. Registered always (lockstep with
9962
9986
  // the union+RBAC edits); answers 'disabled' until the replication
@@ -10122,6 +10146,27 @@ export async function startServer(options) {
10122
10146
  if (pin?.pinned && pin.preferredMachine === wsSelf) {
10123
10147
  return { owner: wsSelf, epoch: 0 };
10124
10148
  }
10149
+ // Issue #930 (live, v1.3.369): the pin store is ROUTER-local —
10150
+ // on the pinned-TO machine it is empty, so #926's fallback
10151
+ // never fires there. Second fallback: the newest
10152
+ // topic-placement JOURNAL entry (own + replica — the entry is
10153
+ // emitted at the router's CAS chokepoint, the strongest
10154
+ // placement evidence reachable here). Admitting a READ-ONLY,
10155
+ // jailed, hash-verified, never-clobber pull off it is not the
10156
+ // kill/spawn/move class the journal-actuation ban guards, and
10157
+ // nomination already runs on replica evidence by design; the
10158
+ // per-write stillCurrent recheck still aborts on a real claim.
10159
+ try {
10160
+ const placement = wsReader2
10161
+ .query({ kind: 'topic-placement', topic, limit: 1 })
10162
+ .entries[0];
10163
+ const pd = placement?.data;
10164
+ if (pd?.owner === wsSelf && typeof pd.epoch === 'number') {
10165
+ return { owner: wsSelf, epoch: pd.epoch };
10166
+ }
10167
+ }
10168
+ catch { /* @silent-fallback-ok: missing placement evidence simply means no fallback ownership — the reflex answers not-owner honestly (WORKING-SET-HANDOFF-SPEC §3.3) */
10169
+ }
10125
10170
  return { owner: null, epoch: null };
10126
10171
  };
10127
10172
  workingSetPullCoordinator = new wscMod.WorkingSetPullCoordinator({
@@ -10222,7 +10267,81 @@ export async function startServer(options) {
10222
10267
  stateDir: config.stateDir,
10223
10268
  logger: (m) => console.log(pc.dim(` [commitments-sync] ${m}`)),
10224
10269
  });
10225
- console.log(pc.dim(' [commitments-sync] replica store wired (serve + receive + advert)'));
10270
+ // P1.5b: opKey window + pending-mutation ledger + forward fn.
10271
+ const mutMod = await import('../core/CommitmentMutation.js');
10272
+ const csCfg2 = config.multiMachine?.coherenceJournal?.commitments;
10273
+ commitmentOpKeyWindow = new mutMod.OpKeyWindow({
10274
+ stateDir: config.stateDir,
10275
+ ttlDays: csCfg2?.opKeyTtlDays,
10276
+ });
10277
+ pendingMutationLedger = new mutMod.PendingMutationLedger({
10278
+ stateDir: config.stateDir,
10279
+ ttlDays: csCfg2?.pendingMutationTtlDays,
10280
+ maxPerCommitment: csCfg2?.maxPendingOpsPerCommitment,
10281
+ maxPerOwner: csCfg2?.maxPendingOpsPerOwner,
10282
+ onExpired: (rec) => {
10283
+ void telegram?.createAttentionItem({
10284
+ id: `CMT-MUT-EXPIRED-${rec.payload.opKey}`,
10285
+ title: `A queued commitment ${rec.payload.op} was never applied`,
10286
+ summary: `The ${rec.payload.op} for ${rec.payload.origin}::${rec.payload.id} stayed queued for the full retention window (${rec.attempts} attempts) — its home machine never returned. Re-issue it once that machine is back.`,
10287
+ category: 'agent-health',
10288
+ priority: 'NORMAL',
10289
+ lane: 'agent-health',
10290
+ sourceContext: 'commitments-coherence',
10291
+ }).catch(() => { });
10292
+ },
10293
+ logger: (m) => console.log(pc.dim(` [commitment-mutate] ${m}`)),
10294
+ });
10295
+ const sendMutate = async (ownerMachineId, payload) => {
10296
+ const url = peerUrl(ownerMachineId);
10297
+ const queue = async (reason) => {
10298
+ await pendingMutationLedger.enqueue(payload);
10299
+ return { kind: 'queued', reason };
10300
+ };
10301
+ if (!url)
10302
+ return queue('owner unreachable (no known URL)');
10303
+ try {
10304
+ const res = await meshClient.send({ machineId: ownerMachineId, url }, { type: 'commitment-mutate', payload }, 0);
10305
+ if (res.ok && res.result && typeof res.result === 'object' && 'verdict' in res.result) {
10306
+ await pendingMutationLedger.clear(payload.opKey);
10307
+ return { kind: 'verdict', outcome: res.result };
10308
+ }
10309
+ if (!res.ok && (res.status === 501 || res.status === 403)) {
10310
+ // Mutating-verb mixed-version honesty (§3.4): an old
10311
+ // owner queues durably + the caller answers honestly.
10312
+ return queue(`owner runs an older version (HTTP ${res.status}) — applies after it updates`);
10313
+ }
10314
+ return queue(`owner answered unexpectedly (HTTP ${res.status})`);
10315
+ }
10316
+ catch (e) {
10317
+ // Timeout/transport = AMBIGUOUS (B24): queue with the SAME
10318
+ // opKey — if the owner did apply, the re-fire returns the
10319
+ // recorded verdict (idempotent-noop), never a double-apply.
10320
+ return queue(`owner unreachable (${e instanceof Error ? e.message : String(e)}) — queued, confirming on its return`);
10321
+ }
10322
+ };
10323
+ forwardCommitmentMutate = sendMutate;
10324
+ // Re-fire on the owner's return: ride the SAME presence seam
10325
+ // the working-set drain uses; sequential, fresh envelopes.
10326
+ const reFireForOwner = async (ownerMachineId) => {
10327
+ if (!pendingMutationLedger)
10328
+ return;
10329
+ const pending = await pendingMutationLedger.pendingForOwner(ownerMachineId);
10330
+ for (const rec of pending) {
10331
+ const r = await sendMutate(ownerMachineId, rec.payload);
10332
+ if (r.kind === 'verdict')
10333
+ continue; // cleared inside sendMutate
10334
+ await pendingMutationLedger.recordAttempt(rec.payload.opKey);
10335
+ }
10336
+ };
10337
+ _commitmentReFire = reFireForOwner;
10338
+ // TTL sweep rides the working-set 10-min timer cadence.
10339
+ const cmtSweepTimer = setInterval(() => {
10340
+ void pendingMutationLedger?.sweepExpired().catch(() => { });
10341
+ }, 600_000);
10342
+ if (typeof cmtSweepTimer.unref === 'function')
10343
+ cmtSweepTimer.unref();
10344
+ console.log(pc.dim(' [commitments-sync] replica store wired (serve + receive + advert + owner-routed mutation)'));
10226
10345
  }
10227
10346
  catch (e) { /* @silent-fallback-ok: commitments-sync construction failure degrades to local-only commitments — never blocks boot (COMMITMENTS-COHERENCE-SPEC §4) */
10228
10347
  commitmentReplicaStore = undefined;
@@ -10468,6 +10587,13 @@ export async function startServer(options) {
10468
10587
  return undefined;
10469
10588
  return nested[machineId] ?? Object.values(nested)[0];
10470
10589
  };
10590
+ // Returning-peer hook (one compact dep keeps the wiring-test window
10591
+ // intact): working-set pending-pull drain (§3.4) + queued
10592
+ // commitment-mutate re-fire (P1.5b §3.4). Both no-op while dark.
10593
+ const onPeerBack = (machineId) => {
10594
+ workingSetPullCoordinator?.onPeerRecorded(machineId);
10595
+ void _commitmentReFire?.(machineId).catch(() => { });
10596
+ };
10471
10597
  const peerPresencePuller = new presenceMod.PeerPresencePuller({
10472
10598
  selfMachineId: meshSelfId,
10473
10599
  listPeers: () => meshIdMgr
@@ -10476,13 +10602,22 @@ export async function startServer(options) {
10476
10602
  .map((m) => ({ machineId: m.machineId, url: peerUrl(m.machineId) })),
10477
10603
  recordHeartbeat: (obs) => { machinePoolRegistry?.recordHeartbeat(obs); },
10478
10604
  log: (line) => console.log(pc.dim(` [peer-presence] ${line}`)),
10479
- onPeerRecorded: (machineId) => workingSetPullCoordinator?.onPeerRecorded(machineId), // working-set re-arm (§3.4); no-op when dark
10605
+ onPeerRecorded: (m) => onPeerBack(m), // ws re-arm + queued-commitment re-fire; no-op when dark
10480
10606
  fetchPeerCapacity: async (machineId, url) => {
10481
10607
  const res = await meshClient.send({ machineId, url }, { type: 'session-status' }, 0);
10482
10608
  if (res.ok && res.result && typeof res.result === 'object') {
10483
10609
  const cap = res.result;
10484
10610
  const journalAdvert = _unwrapPeerJournalAdvert(machineId, cap.journalAdvert);
10485
- return { selfReportedLastSeen: cap.selfReportedLastSeen, loadAvg: cap.loadAvg, journalAdvert };
10611
+ // #930 sibling (live, v1.3.369): the commitments advert was
10612
+ // parsed AWAY here — served by the peer, dropped by this
10613
+ // narrowing return — so driveCommitmentsSync never fired and
10614
+ // zero replicas ever landed. Pass it through.
10615
+ return {
10616
+ selfReportedLastSeen: cap.selfReportedLastSeen,
10617
+ loadAvg: cap.loadAvg,
10618
+ journalAdvert,
10619
+ ...(cap.commitmentsAdvert ? { commitmentsAdvert: cap.commitmentsAdvert } : {}),
10620
+ };
10486
10621
  }
10487
10622
  return null;
10488
10623
  },
@@ -10761,7 +10896,7 @@ export async function startServer(options) {
10761
10896
  catch (err) {
10762
10897
  console.log(pc.dim(` [session-pool] rollout gate not wired: ${err instanceof Error ? err.message : String(err)}`));
10763
10898
  }
10764
- 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, coherenceGate: scopeVerifier, contextHierarchy, canonicalState, operationGate, sentinel, adaptiveTrust, memoryMonitor, orphanReaper, coherenceMonitor, commitmentTracker, semanticMemory, activitySentinel, rateLimitSentinel, releaseReadinessSentinel: releaseReadinessSentinel ?? undefined, messageRouter, summarySentinel, spawnManager, systemReviewer, capabilityMapper, selfKnowledgeTree, coverageAuditor, topicResumeMap: _topicResumeMap ?? undefined, sessionRefresh: _sessionRefresh ?? undefined, autonomyManager, trustElevationTracker, autonomousEvolution, coordinator: coordinator.enabled ? coordinator : undefined, localSigningKeyPem, leaseTransport, 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, whatsappBusinessBackend, messageBridge, hookEventReceiver, worktreeMonitor, subagentTracker, instructionsVerifier, handshakeManager: threadlineHandshake, threadlineRouter, conversationStore, warrantsReplyGate, collaborationSurfacer, threadResumeMap, topicLinkageHandler: topicLinkageHandler ?? undefined, threadlineRelayClient, threadlineReplyWaiters, listenerManager: listenerManager ?? undefined, responseReviewGate, messagingToneGate, outboundDedupGate, telemetryHeartbeat, pasteManager, featureRegistry, discoveryEvaluator, completionEvaluator, unifiedTrust, liveConfig, sharedStateLedger, ledgerSessionRegistry, worktreeManager, oidcEnrolledRepos: parallelDevConfig?.oidcEnrolledRepos, initiativeTracker, projectRoundRunner, projectDriftChecker, machineHeartbeat, machinePoolRegistry, meshRpcDispatcher, workingSetPullCoordinator, commitmentReplicaStore, sessionOwnershipRegistry, topicPinStore: _topicPinStore ?? undefined, secretSync: _secretSyncHandle ?? undefined, meshSelfId: _meshSelfId ?? undefined, resolveRouterUrl: _resolveRouterUrl ?? undefined, resolvePeerUrls: _resolvePeerUrls ?? undefined, sessionPoolE2EResultStore, proxyCoordinator, topicIntentStore, topicIntentArcCheck, usherSignalStore, intelligence: sharedIntelligence ?? undefined, telegramBridgeConfig, telegramBridge: telegramBridge ?? undefined, threadlineObservability, briefDeps, workingMemory, taskFlowRegistry, threadlineFlowBridge, sessionReaper, agentWorktreeReaper, mcpProcessReaper, geminiLoopRunner, sleepController, agentActivityState, reapLog, sleepWakeDetector, unjustifiedStopGate, stopGateDb, stopNotifier });
10899
+ 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, coherenceGate: scopeVerifier, contextHierarchy, canonicalState, operationGate, sentinel, adaptiveTrust, memoryMonitor, orphanReaper, coherenceMonitor, commitmentTracker, semanticMemory, activitySentinel, rateLimitSentinel, releaseReadinessSentinel: releaseReadinessSentinel ?? undefined, messageRouter, summarySentinel, spawnManager, systemReviewer, capabilityMapper, selfKnowledgeTree, coverageAuditor, topicResumeMap: _topicResumeMap ?? undefined, sessionRefresh: _sessionRefresh ?? undefined, autonomyManager, trustElevationTracker, autonomousEvolution, coordinator: coordinator.enabled ? coordinator : undefined, localSigningKeyPem, leaseTransport, 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, whatsappBusinessBackend, messageBridge, hookEventReceiver, worktreeMonitor, subagentTracker, instructionsVerifier, handshakeManager: threadlineHandshake, threadlineRouter, conversationStore, warrantsReplyGate, collaborationSurfacer, threadResumeMap, topicLinkageHandler: topicLinkageHandler ?? undefined, threadlineRelayClient, threadlineReplyWaiters, listenerManager: listenerManager ?? undefined, responseReviewGate, messagingToneGate, outboundDedupGate, telemetryHeartbeat, pasteManager, featureRegistry, discoveryEvaluator, completionEvaluator, unifiedTrust, liveConfig, sharedStateLedger, ledgerSessionRegistry, worktreeManager, oidcEnrolledRepos: parallelDevConfig?.oidcEnrolledRepos, initiativeTracker, projectRoundRunner, projectDriftChecker, machineHeartbeat, machinePoolRegistry, meshRpcDispatcher, workingSetPullCoordinator, commitmentReplicaStore, forwardCommitmentMutate, sessionOwnershipRegistry, topicPinStore: _topicPinStore ?? undefined, secretSync: _secretSyncHandle ?? undefined, meshSelfId: _meshSelfId ?? undefined, resolveRouterUrl: _resolveRouterUrl ?? undefined, resolvePeerUrls: _resolvePeerUrls ?? undefined, sessionPoolE2EResultStore, proxyCoordinator, topicIntentStore, topicIntentArcCheck, usherSignalStore, intelligence: sharedIntelligence ?? undefined, telegramBridgeConfig, telegramBridge: telegramBridge ?? undefined, threadlineObservability, briefDeps, workingMemory, taskFlowRegistry, threadlineFlowBridge, sessionReaper, agentWorktreeReaper, mcpProcessReaper, geminiLoopRunner, sleepController, agentActivityState, reapLog, sleepWakeDetector, unjustifiedStopGate, stopGateDb, stopNotifier });
10765
10900
  // Boot-recovery (tunnel-failure-resilience spec Part 6): if the agent
10766
10901
  // died mid-relay-episode, the persisted tunnel.json carries
10767
10902
  // rotationPending=true. Rotate the dashboard PIN + authToken BEFORE