@topolo/cli 0.13.9 → 0.13.10

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.
@@ -362,6 +362,259 @@ async function nativeClaudePackOperation(manager, sidebar, plan, apply, checkpoi
362
362
  throw error;
363
363
  }
364
364
  }
365
+ async function nativeClaudeDynamicLaneOperation(manager, plan, operation, checkpoint, verifyContext, qualifyOrganization, verifyHistory) {
366
+ if (!["read", "configure", "retire"].includes(operation) || !/^[a-z0-9][a-z0-9-]*$/.test(plan.laneId) || !/^[a-f0-9]{64}$/.test(plan.planDigest) || !plan.intake.key.includes("/intakes/") || (/* @__PURE__ */ new Set([plan.nativeId, plan.source.sessionId, plan.intake.sessionId])).size !== 3 || !["low", "medium", "high", "max"].includes(plan.effort) || !["default", "acceptEdits", "bypassPermissions"].includes(plan.permissionMode) || ![plan.nativeId, plan.source.sessionId, plan.intake.sessionId].every((id) => /^local_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(id)) || plan.cwd !== plan.source.cwd)
367
+ throw new Error("Exact child, source role and originating intake plan required.");
368
+ const symbol = /* @__PURE__ */ Symbol.for("topolo.agent-pack.dynamic-lane.operation.v1");
369
+ if (manager[symbol]) throw new Error("An unresolved child operation retains native custody.");
370
+ const fence = () => {
371
+ if (Date.now() >= plan.deadline) throw new Error("Child operation deadline expired; no retry.");
372
+ verifyContext();
373
+ };
374
+ const fixed = async (role) => {
375
+ const raw = await manager.getSessionWhenLoaded(role.sessionId, "topolo-dynamic-source", { warnOnMiss: false });
376
+ const dto = await manager.getSession(role.sessionId);
377
+ fence();
378
+ if (!raw || !dto || raw.sessionId !== role.sessionId || dto.sessionId !== role.sessionId || raw.cwd !== role.cwd || dto.cwd !== role.cwd || raw.title !== role.title || dto.title !== role.title || raw.isArchived || dto.isArchived || raw.backend?.kind !== "local" || raw.backend.remoteTarget || raw.worktreePath || raw.worktreeLazy || raw.spawnedFrom)
379
+ throw new Error("Source role or intake raw native identity differs.");
380
+ return { raw, dto };
381
+ };
382
+ const child = async (allowArchived = false) => {
383
+ await fixed(plan.source);
384
+ await fixed(plan.intake);
385
+ const raw = await manager.getSessionWhenLoaded(plan.nativeId, "topolo-dynamic-child", { warnOnMiss: false });
386
+ const dto = await manager.getSession(plan.nativeId);
387
+ fence();
388
+ if (!raw || !dto || raw.sessionId !== plan.nativeId || dto.sessionId !== plan.nativeId || raw.cwd !== plan.cwd || dto.cwd !== plan.cwd || raw.title !== plan.title || dto.title !== plan.title || !allowArchived && (raw.isArchived || dto.isArchived) || raw.backend?.kind !== "local" || raw.backend.remoteTarget || raw.worktreePath || raw.worktreeLazy || raw.spawnedFrom?.sessionId !== plan.intake.sessionId || raw.spawnedFrom?.sideSession !== true)
389
+ throw new Error("Actual child raw descriptor or original native parent differs.");
390
+ const busy = raw.isRunning || raw.starting || dto.isRunning || dto.starting || raw.pendingToolPermissions?.length || dto.pendingToolPermissions?.length || manager.hasLosableWork(plan.nativeId);
391
+ return {
392
+ nativeId: plan.nativeId,
393
+ cwd: dto.cwd,
394
+ model: dto.model,
395
+ effort: dto.effort,
396
+ permissionMode: dto.permissionMode,
397
+ nativeParentId: raw.spawnedFrom.sessionId,
398
+ archived: raw.isArchived === true && dto.isArchived === true,
399
+ busy: !!busy,
400
+ pendingApprovals: dto.pendingToolPermissions?.length ?? 0,
401
+ backend: "local",
402
+ foreignWorkspace: false
403
+ };
404
+ };
405
+ fence();
406
+ const before = await child();
407
+ if (!manager.getAvailableCodeModels().includes(plan.model)) throw new Error("Exact task model is unavailable; no parent fallback.");
408
+ if (operation === "read") return { state: "native-child-read", ...before, settingsACK: false, contextACK: false };
409
+ if (before.busy) throw new Error("Own child has active or pending work.");
410
+ await qualifyOrganization();
411
+ fence();
412
+ let attempted = false;
413
+ manager[symbol] = { laneId: plan.laneId, planDigest: plan.planDigest, attempted: false };
414
+ try {
415
+ if (operation === "retire") {
416
+ if (plan.lifecycleState !== "settled") throw new Error("Only a settled child with verified operation outcome may retire.");
417
+ const history = await verifyHistory(plan.nativeId);
418
+ if (typeof manager.archiveCascadeClosureOf !== "function" || typeof manager.archiveSession !== "function")
419
+ throw new Error("Qualified preserved-history native archive API unavailable.");
420
+ const raw = await manager.getSessionWhenLoaded(plan.nativeId, "topolo-dynamic-retire", { warnOnMiss: false });
421
+ const closure = manager.archiveCascadeClosureOf(raw);
422
+ if (!Array.isArray(closure) || closure.length) throw new Error("Child archive would affect another native session.");
423
+ const current = await child();
424
+ if (current.busy) throw new Error("Child became busy before archive.");
425
+ fence();
426
+ checkpoint({ state: "archive-may-have-effects", laneId: plan.laneId, nativeId: plan.nativeId });
427
+ attempted = true;
428
+ manager[symbol].attempted = true;
429
+ await manager.archiveSession(plan.nativeId, { cleanupWorktree: false, forceWorktreeCleanup: false, discardUntracked: false, isAutomatic: true });
430
+ const after2 = await child(true);
431
+ if (!after2.archived || after2.busy || await verifyHistory(plan.nativeId, history) !== true)
432
+ throw new Error("Native child archive or transcript preservation is unproven.");
433
+ checkpoint({ state: "retired", laneId: plan.laneId, nativeId: plan.nativeId, historyPreserved: true });
434
+ delete manager[symbol];
435
+ return { state: "retired", ...after2, historyPreserved: true };
436
+ }
437
+ for (const field of ["model", "effort", "permissionMode"]) {
438
+ const current = await child();
439
+ if (current.busy) throw new Error("Child became busy before native settings effect.");
440
+ if (current[field] === plan[field]) continue;
441
+ await qualifyOrganization();
442
+ fence();
443
+ if (!manager.getAvailableCodeModels().includes(plan.model)) throw new Error("Native account catalog changed.");
444
+ checkpoint({ state: "settings-may-have-effects", laneId: plan.laneId, nativeId: plan.nativeId, field });
445
+ attempted = true;
446
+ manager[symbol].attempted = true;
447
+ if (field === "model") await manager.setModel(plan.nativeId, plan.model);
448
+ else if (field === "effort") await manager.setEffort(plan.nativeId, plan.effort);
449
+ else if (!await manager.setPermissionMode(plan.nativeId, plan.permissionMode, "picker")) throw new Error("Child permission setting refused.");
450
+ const actual = await child();
451
+ if (actual[field] !== plan[field]) throw new Error("Actual child " + field + " differs; no fallback or task dispatch.");
452
+ checkpoint({ state: "native-field-ACK", laneId: plan.laneId, nativeId: plan.nativeId, field, value: actual[field] });
453
+ }
454
+ const after = await child();
455
+ const processRecord = await manager.getSessionWhenLoaded(plan.nativeId, "topolo-dynamic-process-settings", { warnOnMiss: false });
456
+ fence();
457
+ if (!processRecord?.query || typeof manager.getEffort !== "function" || typeof manager.readRunningModel !== "function")
458
+ throw new Error("Actual child process settings are unavailable; settings ACK is unproven.");
459
+ const query = processRecord.query;
460
+ const actualModel = await manager.readRunningModel(processRecord, query);
461
+ const actualEffort = await manager.getEffort(plan.nativeId);
462
+ const reread = await manager.getSessionWhenLoaded(plan.nativeId, "topolo-dynamic-process-settings", { warnOnMiss: false });
463
+ const finalChild = await child();
464
+ if (reread !== processRecord || reread.query !== query || actualModel !== plan.model || actualEffort !== plan.effort || finalChild.busy)
465
+ throw new Error("Actual child process model/effort differs or is unavailable; settings ACK is unproven.");
466
+ await qualifyOrganization();
467
+ fence();
468
+ if (after.model !== plan.model || after.effort !== plan.effort || after.permissionMode !== plan.permissionMode || after.busy)
469
+ throw new Error("Actual child settings are not the complete requested tuple.");
470
+ checkpoint({ state: "configured-settings-ACK", laneId: plan.laneId, nativeId: plan.nativeId, after });
471
+ delete manager[symbol];
472
+ return { state: "configured-settings-ACK", ...after, settingsACK: true, contextACK: false, modelTurnsStarted: false };
473
+ } catch (error) {
474
+ if (!attempted) delete manager[symbol];
475
+ else checkpoint({ state: "uncertain-effect-hold", laneId: plan.laneId, nativeId: plan.nativeId });
476
+ throw error;
477
+ }
478
+ }
479
+ async function nativeClaudeDynamicContext(manager, plan, operation, helper, fingerprint, verifyContext, qualifyOrganization) {
480
+ if (!["context-start", "context-read"].includes(operation.kind) || !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(operation.operationId))
481
+ throw new Error("Closed own-child context operation required.");
482
+ const ready = async () => {
483
+ verifyContext();
484
+ const raw = await manager.getSessionWhenLoaded(plan.nativeId, "topolo-dynamic-context", { warnOnMiss: false });
485
+ const view = await manager.getSession(plan.nativeId);
486
+ verifyContext();
487
+ if (!raw || !view || raw.sessionId !== plan.nativeId || view.sessionId !== plan.nativeId || raw.cwd !== plan.cwd || view.cwd !== plan.cwd || raw.title !== plan.title || view.title !== plan.title || raw.isArchived || view.isArchived || raw.backend?.kind !== "local" || raw.backend.remoteTarget || raw.worktreePath || raw.worktreeLazy || raw.spawnedFrom?.sessionId !== plan.intake.sessionId || raw.spawnedFrom?.sideSession !== true || raw.isRunning || view.isRunning || raw.starting || view.starting || raw.pendingToolPermissions?.length || view.pendingToolPermissions?.length || manager.hasLosableWork(plan.nativeId))
488
+ throw new Error("Exact configured child is not idle on the original native parent.");
489
+ if (!raw.query || typeof manager.readRunningModel !== "function" || typeof manager.getEffort !== "function" || await manager.readRunningModel(raw, raw.query) !== plan.model || await manager.getEffort(plan.nativeId) !== plan.effort)
490
+ throw new Error("Current actual child process model/effort ACK differs.");
491
+ await qualifyOrganization();
492
+ verifyContext();
493
+ };
494
+ await ready();
495
+ if (typeof manager.getTranscriptForCallerElsewhere !== "function") throw new Error("Qualified own-child transcript resolver unavailable.");
496
+ if (operation.kind === "context-read") {
497
+ const history = await manager.getTranscriptForCallerElsewhere(plan.nativeId);
498
+ await ready();
499
+ if (!Array.isArray(history) || !history.length) throw new Error("Own-child context transcript is missing; no acknowledgement.");
500
+ return helper("context-ack", { laneId: plan.laneId, operationId: operation.operationId, messages: history });
501
+ }
502
+ const symbol = /* @__PURE__ */ Symbol.for("topolo.agent-pack.dynamic-context.v1");
503
+ if (manager[symbol]) throw new Error("An unresolved child bootstrap owns delivery; no replay.");
504
+ manager[symbol] = { laneId: plan.laneId, operationId: operation.operationId };
505
+ let armed = false;
506
+ try {
507
+ const bootstrap = await helper("context-prepare", { laneId: plan.laneId, operationId: operation.operationId });
508
+ const history = await manager.getTranscriptForCallerElsewhere(plan.nativeId);
509
+ if (!Array.isArray(history)) throw new Error("Exact own-child pre-bootstrap history is unavailable.");
510
+ await ready();
511
+ await helper("context-mark", {
512
+ laneId: plan.laneId,
513
+ operationId: operation.operationId,
514
+ state: "start-may-have-effects",
515
+ historyCount: history.length,
516
+ historyDigest: fingerprint(history)
517
+ });
518
+ armed = true;
519
+ const result = await manager.sendMessage(
520
+ plan.nativeId,
521
+ bootstrap.text,
522
+ void 0,
523
+ { messageUuid: operation.operationId, initiator: "agent", origin: { kind: "task-notification" } }
524
+ );
525
+ const state = result?.delivered === true ? "native-delivered" : result?.delivered === false ? "native-refused" : "uncertain";
526
+ await helper("context-mark", { laneId: plan.laneId, operationId: operation.operationId, state });
527
+ if (state === "uncertain") throw new Error("Child context delivery is uncertain; never replay.");
528
+ delete manager[symbol];
529
+ return { state, laneId: plan.laneId, operationId: operation.operationId, contextACK: false };
530
+ } catch (error) {
531
+ if (!armed) delete manager[symbol];
532
+ throw error;
533
+ }
534
+ }
535
+ async function nativeClaudeDynamicFixture(manager, plan, operation, helper, verifyContext, qualifyOrganization) {
536
+ if (!["fixture-start", "fixture-read"].includes(operation.kind) || operation.kind === "fixture-start" && !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(operation.operationId ?? ""))
537
+ throw new Error("Closed one-child native fixture operation required.");
538
+ const read = async () => {
539
+ const raw2 = await manager.getSessionWhenLoaded(plan.nativeId, "topolo-dynamic-fixture", { warnOnMiss: false });
540
+ const dto = await manager.getSession(plan.nativeId);
541
+ verifyContext();
542
+ if (!raw2 || !dto || raw2.sessionId !== plan.nativeId || dto.sessionId !== plan.nativeId || raw2.cwd !== plan.cwd || dto.cwd !== plan.cwd || raw2.title !== plan.title || dto.title !== plan.title || raw2.isArchived || dto.isArchived || raw2.backend?.kind !== "local" || raw2.backend.remoteTarget || raw2.worktreePath || raw2.worktreeLazy || raw2.spawnedFrom?.sessionId !== plan.intake.sessionId || raw2.spawnedFrom?.sideSession !== true) throw new Error("Own native fixture child identity or original intake parent changed.");
543
+ return { raw: raw2, native: {
544
+ nativeId: plan.nativeId,
545
+ busy: !!(raw2.isRunning || raw2.starting || dto.isRunning || dto.starting || manager.hasLosableWork(plan.nativeId)),
546
+ pendingApprovals: dto.pendingToolPermissions?.length ?? 0
547
+ } };
548
+ };
549
+ const { raw, native } = await read();
550
+ if (operation.kind === "fixture-read") {
551
+ if (native.busy || native.pendingApprovals) return { state: "native-fixture-pending", ...native };
552
+ const messages = await manager.getTranscriptForCallerElsewhere(plan.nativeId);
553
+ const latest = await read();
554
+ if (latest.native.busy || latest.native.pendingApprovals) return { state: "native-fixture-pending", ...latest.native };
555
+ if (!Array.isArray(messages)) throw new Error("Own native fixture transcript is unavailable.");
556
+ return helper("fixture-outcome", { laneId: plan.laneId, messages, native: latest.native });
557
+ }
558
+ if (native.busy || native.pendingApprovals || !raw.query || await manager.readRunningModel(raw, raw.query) !== plan.model || await manager.getEffort(plan.nativeId) !== plan.effort) throw new Error("Own fixture needs idle child and current actual process tuple ACK.");
559
+ await qualifyOrganization();
560
+ verifyContext();
561
+ const symbol = /* @__PURE__ */ Symbol.for("topolo.agent-pack.dynamic-fixture.v1");
562
+ if (manager[symbol]) throw new Error("An unresolved native fixture retains delivery custody.");
563
+ manager[symbol] = { laneId: plan.laneId, operationId: operation.operationId };
564
+ let armed = false;
565
+ try {
566
+ const fixture = await helper("fixture-prepare", { laneId: plan.laneId, operationId: operation.operationId });
567
+ const latest = await read();
568
+ if (latest.native.busy || latest.native.pendingApprovals) throw new Error("Own child became busy before fixture dispatch.");
569
+ await qualifyOrganization();
570
+ verifyContext();
571
+ await helper("fixture-mark", { laneId: plan.laneId, operationId: operation.operationId, state: "start-may-have-effects" });
572
+ armed = true;
573
+ const result = await manager.sendMessage(
574
+ plan.nativeId,
575
+ fixture.text,
576
+ void 0,
577
+ { messageUuid: operation.operationId, initiator: "agent", origin: { kind: "task-notification" } }
578
+ );
579
+ const state = result?.delivered === true ? "native-delivered" : result?.delivered === false ? "native-refused" : "uncertain";
580
+ await helper("fixture-mark", { laneId: plan.laneId, operationId: operation.operationId, state });
581
+ if (state === "uncertain") throw new Error("Native fixture delivery is uncertain; no replay.");
582
+ delete manager[symbol];
583
+ return { state, laneId: plan.laneId, operationId: operation.operationId, operationEffectVerified: false };
584
+ } catch (error) {
585
+ if (!armed) delete manager[symbol];
586
+ throw error;
587
+ }
588
+ }
589
+ async function nativeClaudeReadEmptyCreation(manager, planned, verifyContext) {
590
+ const pending = planned.creationNativeId ? { nativeId: planned.creationNativeId } : manager[/* @__PURE__ */ Symbol.for("topolo.agent-pack.native-creation.v1")]?.get(planned.laneId);
591
+ if (!pending?.nativeId) throw new Error("Own actual created native identity is unresolved; no replay.");
592
+ const raw = await manager.getSessionWhenLoaded(pending.nativeId, "topolo-dynamic-empty-process", { warnOnMiss: false });
593
+ const view = await manager.getSession(pending.nativeId);
594
+ verifyContext();
595
+ if (!raw || !view || raw.sessionId !== pending.nativeId || view.sessionId !== pending.nativeId || raw.cwd !== planned.role.cwd || view.cwd !== planned.role.cwd || raw.backend?.kind !== "local" || raw.backend.remoteTarget || raw.spawnedFrom?.sessionId !== planned.intake.nativeId || raw.spawnedFrom?.sideSession !== true || raw.isArchived || view.isArchived || raw.worktreePath || raw.worktreeLazy) throw new Error("Actual fresh native child placement/parent differs.");
596
+ if (raw.isRunning || view.isRunning || raw.messageBuffer?.length || raw.heldAcrossLoss?.length || raw.pendingToolPermissions?.length || view.pendingToolPermissions?.length || manager.hasLosableWork(pending.nativeId))
597
+ throw new Error("Fresh child has held/input/active work before configuration-only ACK.");
598
+ if (!raw.query || raw.pendingFirstStart || raw.startResumeInFlight) return { state: "created-initializing", nativeId: pending.nativeId, requestedTaskStarted: false, privateMCPVerified: false };
599
+ return {
600
+ state: "ready",
601
+ nativeId: pending.nativeId,
602
+ cwd: raw.cwd,
603
+ title: raw.title,
604
+ model: view.model,
605
+ effort: view.effort,
606
+ nativeParentId: raw.spawnedFrom.sessionId,
607
+ archived: false,
608
+ backend: "local",
609
+ foreignWorkspace: false,
610
+ busy: false,
611
+ pendingApprovals: 0,
612
+ requestedTaskStarted: false,
613
+ modelTurnsStarted: false,
614
+ privateMCPVerified: false,
615
+ proof: "current-native-descriptor-only"
616
+ };
617
+ }
365
618
 
366
619
  // src/lib/claude-pack-approvals.ts
367
620
  async function nativeClaudeApprovalControl(manager, descriptor, token, net, fs, invoke, qualify, checkpoint) {
@@ -579,10 +832,11 @@ async function nativeClaudeOwnedSmokeOperation(manager, members, operation, help
579
832
  async function nativeClaudeApprovalOperation(manager, routes, operation, fingerprint, checkpoint, history = []) {
580
833
  const symbol = /* @__PURE__ */ Symbol.for("topolo.agent-pack.approvals.v1");
581
834
  if (!routes.length || routes.length > 100 || new Set(routes.map((r) => r.sessionId)).size !== routes.length || new Set(routes.map((r) => r.key)).size !== routes.length) throw new Error("Unique owned approval roster required.");
582
- const byId = new Map(routes.map((r) => [r.sessionId, r]));
583
- const byKey = new Map(routes.map((r) => [r.key, r]));
835
+ const existing = manager[symbol];
836
+ const byId = existing?.byId ?? new Map(routes.map((r) => [r.sessionId, r]));
837
+ const byKey = existing?.byKey ?? new Map(routes.map((r) => [r.key, r]));
584
838
  for (const r of routes) {
585
- const intake = byKey.get(r.intakeKey);
839
+ const intake = routes.find((candidate) => candidate.key === r.intakeKey);
586
840
  if (!/^org:.+$/.test(r.contextKey) || !intake || !intake.key.includes("/intakes/") || intake.contextKey !== r.contextKey || intake.sessionId !== r.intakeSessionId)
587
841
  throw new Error("Approval route has no same-context owned intake.");
588
842
  }
@@ -595,7 +849,7 @@ async function nativeClaudeApprovalOperation(manager, routes, operation, fingerp
595
849
  const session = await manager.getSession(route.sessionId);
596
850
  if (!session || session.sessionId !== route.sessionId || session.cwd !== route.cwd || session.title !== route.title || session.isArchived)
597
851
  throw new Error("Native approval session identity differs: " + route.key);
598
- if (!descriptor || descriptor.sessionId !== route.sessionId || descriptor.cwd !== route.cwd || descriptor.title !== route.title || descriptor.isArchived || descriptor.backend?.kind !== "local" || descriptor.backend.remoteTarget || descriptor.worktreePath || descriptor.worktreeLazy || descriptor.spawnedFrom)
852
+ if (!descriptor || descriptor.sessionId !== route.sessionId || descriptor.cwd !== route.cwd || descriptor.title !== route.title || descriptor.isArchived || descriptor.backend?.kind !== "local" || descriptor.backend.remoteTarget || descriptor.worktreePath || descriptor.worktreeLazy || (route.dynamic ? descriptor.spawnedFrom?.sessionId !== route.dynamic.nativeParentId || descriptor.spawnedFrom?.sideSession !== true || route.dynamic.nativeParentId !== route.intakeSessionId || !/^[a-f0-9]{64}$/.test(route.dynamic.planDigest) : descriptor.spawnedFrom))
599
853
  throw new Error("Native approval session descriptor identity differs: " + route.key);
600
854
  return session;
601
855
  };
@@ -624,7 +878,7 @@ async function nativeClaudeApprovalOperation(manager, routes, operation, fingerp
624
878
  for (const r of routes) await owned(r);
625
879
  if (!state) {
626
880
  if (typeof manager.on !== "function" || typeof manager.sendMessage !== "function" || typeof manager.respondToToolPermission !== "function") throw new Error("Native approval transport unavailable.");
627
- state = { identity, routes, entries: /* @__PURE__ */ new Map(), notifications: /* @__PURE__ */ new Set(), deliveryAttempts: 0 };
881
+ state = { identity, routes, byId, byKey, entries: /* @__PURE__ */ new Map(), notifications: /* @__PURE__ */ new Set(), deliveryAttempts: 0 };
628
882
  manager[symbol] = state;
629
883
  const save = (entry2) => checkpoint({ ...entry2.record });
630
884
  const deliver = async (entry2) => {
@@ -644,7 +898,7 @@ async function nativeClaudeApprovalOperation(manager, routes, operation, fingerp
644
898
  save(entry2);
645
899
  return;
646
900
  }
647
- const text = "Permission relay (generated by the Topolo pack adapter). " + record.sourceKey + " awaits a native decision. Request " + record.key + ", fingerprint " + record.fingerprint + ". Read exact live details using topolo agent-packs approvals details " + record.key + " --harness claude --intake " + record.intakeSessionId + " --fingerprint " + record.fingerprint + ". Present this to the human in this intake and relay only the recorded answer. This notification grants no approval." + (record.cardOnly ? " Claude requires approval on the original native card; report this limitation here." : "");
901
+ const text = "Permission relay (generated by the Topolo pack adapter). " + record.sourceKey + " awaits a native decision. Request " + record.key + ", fingerprint " + record.fingerprint + ". Read exact live details using topolo agent-packs approvals details " + record.key + " --harness claude --intake " + record.intakeSessionId + " --fingerprint " + record.fingerprint + (byId.get(record.sourceSessionId)?.dynamic?.connectionId ? " --connection " + byId.get(record.sourceSessionId).dynamic.connectionId : "") + ". Present this to the human in this intake and relay only the recorded answer. This notification grants no approval." + (record.cardOnly ? " Claude requires approval on the original native card; report this limitation here." : "");
648
902
  record.notificationState = "may-have-effects";
649
903
  save(entry2);
650
904
  state.deliveryAttempts++;
@@ -695,6 +949,8 @@ async function nativeClaudeApprovalOperation(manager, routes, operation, fingerp
695
949
  state.entries.set(key, entry2);
696
950
  save(entry2);
697
951
  }
952
+ const lifecycle2 = state.dynamicLifecycle?.get(sessionId);
953
+ if (lifecycle2 && entry2.record.state === "pending") await lifecycle2.request(entry2.record, pending2);
698
954
  if (entry2.record.state === "pending") await deliver(entry2);
699
955
  };
700
956
  state.listener = async (event) => {
@@ -737,6 +993,11 @@ async function nativeClaudeApprovalOperation(manager, routes, operation, fingerp
737
993
  if (operation.kind === "list") return { requests: [...state.entries.values()].map((e) => ({ ...e.record })) };
738
994
  const entry = state.entries.get(operation.key);
739
995
  if (!entry || entry.record.state !== "pending" || entry.record.intakeSessionId !== operation.intake || entry.record.fingerprint !== operation.fingerprint) throw new Error("Exact pending request and owning intake required.");
996
+ if (operation.kind === "respond" && operation.decision === "once" && byId.get(entry.record.sourceSessionId)?.dynamic)
997
+ throw Object.assign(
998
+ new Error("native_private_query_prestart_contract_unqualified: dynamic private query authorization remains closed."),
999
+ { code: "native_private_query_prestart_contract_unqualified" }
1000
+ );
740
1001
  const pending = await current(entry);
741
1002
  if (manager[symbol] !== state || state.entries.get(operation.key) !== entry || entry.record.state !== "pending" || state.auditFailed)
742
1003
  throw new Error("Exact pending request changed during native identity validation; reconcile without replay.");
@@ -750,10 +1011,118 @@ async function nativeClaudeApprovalOperation(manager, routes, operation, fingerp
750
1011
  const source = await owned(byId.get(entry.record.sourceSessionId));
751
1012
  if (source.pendingToolPermissions?.some((r) => r.requestId === pending.requestId))
752
1013
  throw new Error("Native decision did not settle; reconcile without replay.");
1014
+ const lifecycle = state.dynamicLifecycle?.get(entry.record.sourceSessionId);
1015
+ if (lifecycle) await lifecycle.decision(entry.record, pending, operation.decision);
753
1016
  entry.record.state = "native-request-settled";
754
1017
  checkpoint({ ...entry.record });
755
1018
  return { state: entry.record.state, nativeApproved: false, operationEffectVerified: false };
756
1019
  }
1020
+ async function nativeClaudeAppendDynamicRoute(manager, route, verify, checkpoint, lifecycle) {
1021
+ const state = manager[/* @__PURE__ */ Symbol.for("topolo.agent-pack.approvals.v1")];
1022
+ if (!state || state.auditFailed || !state.byId || !state.byKey || !route.dynamic || !/^[a-f0-9]{64}$/.test(route.dynamic.planDigest) || route.dynamic.nativeParentId !== route.intakeSessionId)
1023
+ throw new Error("Current qualified original approval listener required.");
1024
+ const intake = state.byId.get(route.intakeSessionId);
1025
+ if (!intake || intake.key !== route.intakeKey || intake.contextKey !== route.contextKey || !intake.key.includes("/intakes/"))
1026
+ throw new Error("Dynamic approval route has no exact same-context original intake.");
1027
+ await verify();
1028
+ const raw = await manager.getSessionWhenLoaded(route.sessionId, "topolo-dynamic-route", { warnOnMiss: false });
1029
+ const dto = await manager.getSession(route.sessionId);
1030
+ if (!raw || !dto || raw.sessionId !== route.sessionId || raw.cwd !== route.cwd || raw.title !== route.title || dto.sessionId !== route.sessionId || dto.cwd !== route.cwd || dto.title !== route.title || raw.isArchived || dto.isArchived || raw.backend?.kind !== "local" || raw.backend.remoteTarget || raw.worktreePath || raw.worktreeLazy || raw.spawnedFrom?.sessionId !== route.intakeSessionId || raw.spawnedFrom?.sideSession !== true)
1031
+ throw new Error("Actual dynamic child descriptor differs before route append.");
1032
+ await verify();
1033
+ if (manager[/* @__PURE__ */ Symbol.for("topolo.agent-pack.approvals.v1")] !== state || state.auditFailed)
1034
+ throw new Error("Original native permission connection changed.");
1035
+ const old = state.byId.get(route.sessionId);
1036
+ if (old) {
1037
+ if (JSON.stringify(old) !== JSON.stringify(route)) throw new Error("Native child route conflicts with an existing owner.");
1038
+ return { state: "dynamic-route-current", generation: state.identity };
1039
+ }
1040
+ if (state.byKey.has(route.key)) throw new Error("Dynamic role key is already owned.");
1041
+ checkpoint({ state: "dynamic-route-append", route });
1042
+ state.byId.set(route.sessionId, route);
1043
+ state.byKey.set(route.key, route);
1044
+ state.dynamicRoutes ??= /* @__PURE__ */ new Map();
1045
+ state.dynamicRoutes.set(route.sessionId, route);
1046
+ if (lifecycle) {
1047
+ state.dynamicLifecycle ??= /* @__PURE__ */ new Map();
1048
+ state.dynamicLifecycle.set(route.sessionId, lifecycle);
1049
+ }
1050
+ return { state: "dynamic-route-appended", generation: state.identity, pendingRequestsPreserved: true };
1051
+ }
1052
+ async function nativeClaudeLaneControl(net, fs, manager, descriptor, token, invoke, qualify, checkpoint) {
1053
+ if (!/^[a-f0-9]{64}$/.test(token) || !/^[a-f0-9]{64}$/.test(descriptor.identity) || !/^[a-z0-9][a-z0-9-]*$/.test(descriptor.laneId) || !Number.isSafeInteger(descriptor.pid) || descriptor.pid < 1)
1054
+ throw new Error("Exact private lane native control identity required.");
1055
+ const symbol = /* @__PURE__ */ Symbol.for("topolo.agent-pack.dynamic-controls.v1");
1056
+ manager[symbol] ??= /* @__PURE__ */ new Map();
1057
+ const controls = manager[symbol];
1058
+ if (controls.has(descriptor.laneId) || fs.existsSync(descriptor.socket)) throw new Error("Own native lane control already exists; no takeover.");
1059
+ qualify();
1060
+ const control = { active: 0, descriptor, server: null, closed: false };
1061
+ const allowed = /* @__PURE__ */ new Set(["read", "context-start", "context-read", "fixture-start", "fixture-read", "retire", "approval-list", "approval-details", "approval-respond", "close"]);
1062
+ const server = net.createServer((connection) => {
1063
+ let text = "";
1064
+ let dispatched = false;
1065
+ connection.setEncoding("utf8");
1066
+ connection.setTimeout(24e4, () => connection.destroy());
1067
+ connection.on("error", () => connection.destroy());
1068
+ connection.on("data", async (chunk) => {
1069
+ if (dispatched) return;
1070
+ text += chunk;
1071
+ if (Buffer.byteLength(text) > 65536) {
1072
+ dispatched = true;
1073
+ connection.destroy();
1074
+ return;
1075
+ }
1076
+ if (!text.includes("\n")) return;
1077
+ dispatched = true;
1078
+ control.active++;
1079
+ try {
1080
+ qualify();
1081
+ const request = JSON.parse(text);
1082
+ if (Object.keys(request).sort().join() !== "identity,operation,pid,token" || request.token !== token || request.pid !== descriptor.pid || request.identity !== descriptor.identity)
1083
+ throw new Error("Private native lane control authentication differs.");
1084
+ const operation = request.operation;
1085
+ const fields = operation?.kind === "approval-respond" ? ["kind", "key", "intake", "fingerprint", "decision", "humanDecisionRecorded"] : operation?.kind === "approval-details" ? ["kind", "key", "intake", "fingerprint"] : ["context-start", "context-read", "fixture-start"].includes(operation?.kind) ? ["kind", "operationId"] : ["kind"];
1086
+ if (!operation || !allowed.has(operation.kind) || Object.keys(operation).some((k) => !fields.includes(k))) throw new Error("Closed private lane operation required.");
1087
+ if (operation.kind === "close" && control.active !== 1) throw new Error("Own native control has other in-flight operations.");
1088
+ const result = await invoke(operation);
1089
+ const encoded = JSON.stringify({ result }) + "\n";
1090
+ if (Buffer.byteLength(encoded) > 1048576) throw new Error("Bounded private native lane reply exceeded.");
1091
+ connection.end(encoded);
1092
+ if (operation.kind === "close") connection.once("close", () => server.close(() => {
1093
+ control.closed = true;
1094
+ controls.delete(descriptor.laneId);
1095
+ checkpoint({ state: "normal-own-lane-control-closed", laneId: descriptor.laneId });
1096
+ if (fs.existsSync(descriptor.socket)) {
1097
+ const current = fs.lstatSync(descriptor.socket);
1098
+ if (current.ino === control.inode && current.uid === control.uid) fs.unlinkSync(descriptor.socket);
1099
+ }
1100
+ }));
1101
+ } catch (error) {
1102
+ connection.end(JSON.stringify({ error: error instanceof Error ? error.message : "Native lane control refused." }) + "\n");
1103
+ } finally {
1104
+ control.active--;
1105
+ }
1106
+ });
1107
+ });
1108
+ control.server = server;
1109
+ await new Promise((done, fail) => {
1110
+ server.once("error", fail);
1111
+ server.listen(descriptor.socket, done);
1112
+ });
1113
+ try {
1114
+ fs.chmodSync(descriptor.socket, 384);
1115
+ const stat = fs.lstatSync(descriptor.socket);
1116
+ control.inode = stat.ino;
1117
+ control.uid = stat.uid;
1118
+ checkpoint({ state: "private-native-lane-control-ready", ...descriptor });
1119
+ controls.set(descriptor.laneId, control);
1120
+ } catch (error) {
1121
+ await new Promise((done) => server.close(() => done()));
1122
+ throw error;
1123
+ }
1124
+ return { state: "private-native-lane-control-ready", ...descriptor };
1125
+ }
757
1126
 
758
1127
  // src/lib/claude-pack-backend.ts
759
1128
  var CLAUDE_NATIVE_QUALIFIER = {
@@ -1396,7 +1765,7 @@ function requestClaudeApprovalControl(connection, operation, token, connect = cr
1396
1765
  error ? fail(error) : done(result);
1397
1766
  };
1398
1767
  client.setEncoding("utf8");
1399
- client.setTimeout(operation.kind === "smoke-start" ? 6e4 : 1e4, () => finish(new Error("Native approval response timed out; reconcile without replay.")));
1768
+ client.setTimeout(connection.laneId ? 24e4 : operation.kind === "smoke-start" ? 6e4 : 1e4, () => finish(new Error("Native approval response timed out; reconcile without replay.")));
1400
1769
  client.on("connect", () => client.write(JSON.stringify({ token, pid: connection.pid, identity: connection.identity, operation }) + "\n"));
1401
1770
  client.on("data", (chunk) => {
1402
1771
  reply += chunk;
@@ -1454,16 +1823,555 @@ async function operateClaudeSmoke(options, request = requestClaudeApprovalContro
1454
1823
  throw new Error("Exact closed native smoke fields required.");
1455
1824
  return operateClaudeApprovals(options, request);
1456
1825
  }
1826
+ function prepareClaudeDynamicLane(store, pack, policyPath, laneId) {
1827
+ if (!/^[a-z0-9][a-z0-9-]*$/.test(pack) || !/^[a-z0-9][a-z0-9-]*$/.test(laneId)) throw new Error("Exact pack and lane IDs required.");
1828
+ const root = realpathSync(store);
1829
+ const file = resolve(root, "dynamic-lanes/claude", laneId + ".json");
1830
+ const owned = (path) => {
1831
+ const info = lstatSync(path);
1832
+ if (!info.isFile() || info.isSymbolicLink() || info.nlink !== 1 || info.uid !== process.getuid?.() || info.mode & 18)
1833
+ throw new Error("Dynamic lane requires an owned regular context record.");
1834
+ return path;
1835
+ };
1836
+ owned(file);
1837
+ if (lstatSync(file).size > 131072) throw new Error("Dynamic lane record exceeds its schema bound.");
1838
+ const record = JSON.parse(readFileSync(file, "utf8"));
1839
+ const canonical = (value) => JSON.stringify(value, (_key, item) => item && typeof item === "object" && !Array.isArray(item) ? Object.fromEntries(Object.keys(item).sort().map((key) => [key, item[key]])) : item);
1840
+ const digest = (value) => createHash("sha256").update(canonical(value)).digest("hex");
1841
+ if (record.format !== "topolo-dynamic-lane" || record.schemaVersion !== 1 || record.harness !== "claude" || record.laneId !== laneId || record.planDigest !== digest(record.plan) || record.creationReceiptDigest !== digest(record.creationReceipt) || typeof record.nativeTitle !== "string" || !record.nativeTitle || record.nativeTitle.length > 256 || record.plan.role.packId !== pack || record.plan.nativeParentId !== record.plan.intake.nativeId)
1842
+ throw new Error("Durable dynamic child identity or plan digest differs.");
1843
+ const stateFile = owned(resolve(root, "claude/state.json"));
1844
+ const state = JSON.parse(readFileSync(stateFile, "utf8"));
1845
+ const policyFile = owned(realpathSync(policyPath));
1846
+ const policy = JSON.parse(readFileSync(policyFile, "utf8"));
1847
+ if (state.harness !== "claude" || policy.format !== "topolo-agent-execution-policy" || policy.pack !== pack || policy.sourceRevision !== record.plan.role.packRevision || !policy.installationConsent)
1848
+ throw new Error("Dynamic child source policy or organization-bound installation is stale.");
1849
+ const context = {
1850
+ [stateFile]: createHash("sha256").update(readFileSync(stateFile)).digest("hex"),
1851
+ [policyFile]: createHash("sha256").update(readFileSync(policyFile)).digest("hex")
1852
+ };
1853
+ const inventories = {};
1854
+ const fixed = (descriptor) => {
1855
+ const rows = state.agents.filter((a) => a.key === descriptor.key && a.desktopSessionId === descriptor.nativeId && a.pack === pack && a.sourceRevision === policy.sourceRevision && a.importState === "desktop-adopted");
1856
+ const settings = policy.agents.filter((r) => r.key === descriptor.key);
1857
+ if (rows.length !== 1 || settings.length !== 1) throw new Error("Dynamic source has no unique current adopted role.");
1858
+ const row = rows[0];
1859
+ const cwd = realpathSync(row.workspace);
1860
+ if (cwd !== descriptor.cwd || !cwd.startsWith(resolve(root, "claude/workspaces", pack) + sep) || canonical(settings[0].harnesses.claude.nativeSettings) !== canonical(descriptor.settings))
1861
+ throw new Error("Dynamic source workspace or current fixed settings differ.");
1862
+ const files = [resolve(cwd, "CLAUDE.md"), resolve(cwd, "topolo-connection.json"), resolve(cwd, ".mcp.json")];
1863
+ const hashes = {};
1864
+ for (const f of files) hashes[owned(f)] = createHash("sha256").update(readFileSync(f)).digest("hex");
1865
+ const connection = JSON.parse(readFileSync(files[1], "utf8"));
1866
+ const expected = {
1867
+ environment: descriptor.environment,
1868
+ contextKey: descriptor.contextKey,
1869
+ pack,
1870
+ packRevision: descriptor.packRevision,
1871
+ nativeThreadId: descriptor.nativeId,
1872
+ agentId: descriptor.AgentLogicalId,
1873
+ agentVersionId: descriptor.AgentVersionId,
1874
+ agentWorkspaceId: descriptor.AgentWorkspaceId,
1875
+ bytesWorkspaceId: descriptor.BytesWorkspaceId,
1876
+ instanceId: descriptor.installationId
1877
+ };
1878
+ if (Object.entries(expected).some(([k, v]) => connection[k] !== v) || connection.identity?.organizationId !== descriptor.organizationId || descriptor.contextKey !== "org:" + descriptor.organizationId || descriptor.privateMCPDescriptorHash !== hashes[files[2]] || descriptor.contextDigest !== digest(hashes))
1879
+ throw new Error("Current hosted Agent, Bytes, private MCP or loaded-source context descriptor differs.");
1880
+ Object.assign(context, hashes);
1881
+ inventories[cwd] = snapshotClaudeMarkdown(cwd, filesystem, cryptography, paths);
1882
+ return { key: row.key, sessionId: row.desktopSessionId, cwd, title: row.title };
1883
+ };
1884
+ const source = fixed(record.plan.role);
1885
+ const intake = fixed(record.plan.intake);
1886
+ const consent = policy.installationConsent;
1887
+ if (consent.contextKey !== record.plan.role.contextKey || consent.environment !== record.plan.role.environment || consent.intakeRoutes?.[source.key] !== intake.key || record.creationReceipt.cwd !== source.cwd)
1888
+ throw new Error("Dynamic child original intake or installation scope differs.");
1889
+ return {
1890
+ root,
1891
+ pack,
1892
+ record,
1893
+ context,
1894
+ contextInventories: inventories,
1895
+ consent,
1896
+ nativePlan: {
1897
+ laneId,
1898
+ planDigest: record.planDigest,
1899
+ nativeId: record.nativeId,
1900
+ cwd: record.creationReceipt.cwd,
1901
+ title: record.nativeTitle,
1902
+ source,
1903
+ intake,
1904
+ lifecycleState: record.state,
1905
+ ...record.plan.resolution.resolved,
1906
+ permissionMode: record.plan.verificationProfile === "manual" ? "default" : record.plan.role.settings.permissions.defaultMode,
1907
+ contextDigest: record.plan.role.contextDigest,
1908
+ deadline: Date.now() + 45e3
1909
+ }
1910
+ };
1911
+ }
1912
+ function privateClaudeHelperEnvironment(connection, fs, crypto, path, hostEnv) {
1913
+ const fields = ["format", "schemaVersion", "root", "pack", "sourceRoleKey", "policyFile", "bindingFile", "policyDigest", "bindingDigest", "stateDigest", "profile"];
1914
+ if (!connection || typeof connection !== "object" || Array.isArray(connection) || Object.keys(connection).sort().join() !== fields.sort().join() || connection.format !== "topolo-private-helper-connection" || connection.schemaVersion !== 1 || !/^[a-z0-9][a-z0-9-]*$/.test(connection.pack) || typeof connection.sourceRoleKey !== "string" || connection.sourceRoleKey.split("/").length !== 3)
1915
+ throw new Error("Explicit approved private helper connection required before client startup.");
1916
+ const canonical = (value) => JSON.stringify(value, (_key, item) => item && typeof item === "object" && !Array.isArray(item) ? Object.fromEntries(Object.keys(item).sort().map((key) => [key, item[key]])) : item);
1917
+ const hash = (bytes) => crypto.createHash("sha256").update(bytes).digest("hex");
1918
+ const owned = (file) => {
1919
+ const info = fs.lstatSync(file);
1920
+ if (!info.isFile() || info.isSymbolicLink() || info.uid !== process.getuid?.() || info.nlink !== 1 || info.mode & 18)
1921
+ throw new Error("Private helper metadata requires owned regular records.");
1922
+ };
1923
+ const read = (file, expected) => {
1924
+ owned(file);
1925
+ const bytes = fs.readFileSync(file);
1926
+ if (hash(bytes) !== expected) throw new Error("Private helper connection metadata changed before client startup.");
1927
+ return JSON.parse(bytes.toString("utf8"));
1928
+ };
1929
+ const root = fs.realpathSync(connection.root);
1930
+ if (root !== connection.root) throw new Error("Private helper library identity changed.");
1931
+ const policy = read(connection.policyFile, connection.policyDigest), consent = policy.installationConsent;
1932
+ const state = read(path.resolve(root, "claude/state.json"), connection.stateDigest);
1933
+ const binding = read(connection.bindingFile, connection.bindingDigest), profile = connection.profile;
1934
+ if (!profile || typeof profile !== "object" || Object.keys(profile).sort().join() !== ["format", "schemaVersion", "configPath", "environment", "contextKey", "identity"].sort().join() || profile.format !== "topolo-private-credential-profile" || profile.schemaVersion !== 1 || !["development", "staging", "production"].includes(profile.environment) || typeof profile.contextKey !== "string" || !profile.identity || Object.keys(profile.identity).sort().join() !== "organizationId,userId" || typeof profile.identity.userId !== "string" || !profile.identity.userId || typeof profile.identity.organizationId !== "string" || !profile.identity.organizationId || profile.contextKey !== "org:" + profile.identity.organizationId)
1935
+ throw new Error("Exact per-environment private profile identity reference required.");
1936
+ if (connection.bindingFile !== path.resolve(root, "connections", connection.pack, profile.environment, hash(profile.contextKey) + ".json") || canonical(binding.privateCredentialProfile) !== canonical(profile) || canonical(binding.identity) !== canonical(profile.identity) || binding.environment !== profile.environment || binding.contextKey !== profile.contextKey || policy.format !== "topolo-agent-execution-policy" || policy.pack !== connection.pack || policy.sourceRevision !== binding.packRevision || state.harness !== "claude" || !consent || consent.format !== "topolo-pack-installation-consent" || consent.schemaVersion !== 1 || consent.authority !== "local-installation-consent" || consent.approved !== true || consent.pack !== connection.pack || consent.environment !== profile.environment || consent.contextKey !== profile.contextKey || consent.principalId !== profile.identity.userId || !consent.agentWorkspaceId || binding.agentWorkspaceId !== consent.agentWorkspaceId || typeof binding.input?.instanceId !== "string" || !binding.input.instanceId || typeof binding.input.bytesWorkspaceId !== "string" || !binding.input.bytesWorkspaceId)
1937
+ throw new Error("Private helper profile differs from the actual pack installation and policy.");
1938
+ const intakeKey = consent.intakeRoutes?.[connection.sourceRoleKey];
1939
+ if (typeof intakeKey !== "string" || !intakeKey.includes("/intakes/")) throw new Error("Private helper original intake is missing.");
1940
+ for (const key of [connection.sourceRoleKey, intakeKey]) {
1941
+ const logical = key.split("/").slice(1).join("/");
1942
+ const rows = state.agents?.filter((row) => row.key === key && row.pack === connection.pack && row.sourceRevision === binding.packRevision && row.importState === "desktop-adopted");
1943
+ const roles = binding.input.roles?.filter((row) => row.logicalId === logical);
1944
+ if (key.split("/")[0] !== connection.pack || rows?.length !== 1 || roles?.length !== 1 || !policy.agents?.some((row) => row.key === key) || typeof roles[0].agentId !== "string" || !roles[0].agentId || typeof roles[0].agentVersionId !== "string" || !roles[0].agentVersionId)
1945
+ throw new Error("Private helper source or original intake is outside the current bound pack.");
1946
+ const cwd = fs.realpathSync(rows[0].workspace);
1947
+ if (!cwd.startsWith(path.resolve(root, "claude/workspaces", connection.pack) + path.sep)) throw new Error("Private helper role workspace is outside its pack.");
1948
+ const descriptorFile = path.resolve(cwd, "topolo-connection.json");
1949
+ owned(descriptorFile);
1950
+ const descriptor = JSON.parse(fs.readFileSync(descriptorFile, "utf8"));
1951
+ const expected = {
1952
+ harness: "claude",
1953
+ pack: connection.pack,
1954
+ packRevision: binding.packRevision,
1955
+ role: logical,
1956
+ nativeThreadId: rows[0].desktopSessionId,
1957
+ environment: profile.environment,
1958
+ contextKey: profile.contextKey,
1959
+ instanceId: binding.input.instanceId,
1960
+ agentId: roles[0].agentId,
1961
+ agentVersionId: roles[0].agentVersionId,
1962
+ agentWorkspaceId: binding.agentWorkspaceId,
1963
+ bytesWorkspaceId: binding.input.bytesWorkspaceId
1964
+ };
1965
+ if (Object.entries(expected).some(([name, value]) => descriptor[name] !== value) || canonical(descriptor.identity) !== canonical(profile.identity))
1966
+ throw new Error("Private helper role descriptor does not match the actual public connection binding.");
1967
+ }
1968
+ if (typeof profile.configPath !== "string" || !path.isAbsolute(profile.configPath) || fs.realpathSync(profile.configPath) !== profile.configPath)
1969
+ throw new Error("Explicit protected profile path must be absolute and must not follow links.");
1970
+ const leaf = fs.lstatSync(profile.configPath), parent = fs.lstatSync(path.dirname(profile.configPath));
1971
+ if (!leaf.isFile() || leaf.isSymbolicLink() || leaf.uid !== process.getuid?.() || leaf.nlink !== 1 || (leaf.mode & 511) !== 384 || !parent.isDirectory() || parent.isSymbolicLink() || parent.uid !== process.getuid?.() || (parent.mode & 511) !== 448)
1972
+ throw new Error("Private helper profile requires owned0600 single-link storage in an owned0700 directory.");
1973
+ const env = {};
1974
+ for (const key of ["HOME", "USER", "LOGNAME", "PATH", "LANG", "LC_ALL", "TMPDIR"]) if (typeof hostEnv[key] === "string") env[key] = hostEnv[key];
1975
+ return { ...env, TOPOLO_CONFIG_PATH: profile.configPath, TOPOLO_ENV: profile.environment, TOPOLO_CONTEXT: profile.contextKey };
1976
+ }
1977
+ function prepareClaudePrivateHelperConnection(store, pack, policyPath, sourceRoleKey) {
1978
+ if (!/^[a-z0-9][a-z0-9-]*$/.test(pack) || typeof sourceRoleKey !== "string" || sourceRoleKey.split("/").length !== 3)
1979
+ throw new Error("Exact existing pack source role required for a private helper connection.");
1980
+ const root = realpathSync(store), policyFile = realpathSync(policyPath);
1981
+ const policyBytes = readFileSync(policyFile), policy = JSON.parse(policyBytes.toString("utf8")), consent = policy.installationConsent;
1982
+ if (!consent || !["development", "staging", "production"].includes(consent.environment) || typeof consent.contextKey !== "string")
1983
+ throw new Error("Existing approved per-environment private connection required.");
1984
+ const bindingFile = resolve(root, "connections", pack, consent.environment, createHash("sha256").update(consent.contextKey).digest("hex") + ".json");
1985
+ const bindingBytes = readFileSync(bindingFile), binding = JSON.parse(bindingBytes.toString("utf8"));
1986
+ const connection = {
1987
+ format: "topolo-private-helper-connection",
1988
+ schemaVersion: 1,
1989
+ root,
1990
+ pack,
1991
+ sourceRoleKey,
1992
+ policyFile,
1993
+ bindingFile,
1994
+ policyDigest: createHash("sha256").update(policyBytes).digest("hex"),
1995
+ bindingDigest: createHash("sha256").update(bindingBytes).digest("hex"),
1996
+ stateDigest: createHash("sha256").update(readFileSync(resolve(root, "claude/state.json"))).digest("hex"),
1997
+ profile: binding.privateCredentialProfile
1998
+ };
1999
+ privateClaudeHelperEnvironment(connection, filesystem, cryptography, paths, process.env);
2000
+ return connection;
2001
+ }
2002
+ function runClaudeLaneHelper(root, pack, policyPath, action, payload, source, connection, launch = spawn, runtime = { fs: filesystem, crypto: cryptography, path: paths, env: process.env }, qualifyEnvironment = privateClaudeHelperEnvironment) {
2003
+ const actions = [
2004
+ "peek",
2005
+ "plan",
2006
+ "creation-begin",
2007
+ "creation-record",
2008
+ "creation-read",
2009
+ "adopt",
2010
+ "configure-begin",
2011
+ "configure-ack",
2012
+ "context-prepare",
2013
+ "context-mark",
2014
+ "context-ack",
2015
+ "fixture-prepare",
2016
+ "fixture-mark",
2017
+ "fixture-outcome",
2018
+ "permission-request",
2019
+ "permission-decision",
2020
+ "retire-begin",
2021
+ "retire-ack",
2022
+ "read"
2023
+ ];
2024
+ if (!actions.includes(action) || !/^[a-z0-9][a-z0-9-]*$/.test(pack) || !payload || typeof payload !== "object" || Array.isArray(payload))
2025
+ return Promise.reject(new Error("Closed typed native lifecycle helper required."));
2026
+ const encoded = JSON.stringify(payload);
2027
+ if (Buffer.byteLength(encoded) > 2097152) return Promise.reject(new Error("Own-child native transcript exceeds bounded transport; no broad history read."));
2028
+ const selectedRole = payload.sourceRoleKey ?? payload.request?.sourceRoleKey ?? payload.plan?.role?.key ?? payload.operation?.record?.plan?.role?.key;
2029
+ if (!connection || root !== connection.root || pack !== connection.pack || policyPath !== connection.policyFile || selectedRole !== void 0 && selectedRole !== connection.sourceRoleKey)
2030
+ return Promise.reject(new Error("Private helper arguments differ from the exact bound source connection."));
2031
+ let childEnv;
2032
+ try {
2033
+ childEnv = qualifyEnvironment(connection, runtime.fs, runtime.crypto, runtime.path, runtime.env);
2034
+ } catch (error) {
2035
+ return Promise.reject(error);
2036
+ }
2037
+ const script = "import sys,json\nsys.path.insert(0,sys.argv[5])\nfrom topolo_agent_pack.storage import Library\nfrom topolo_agent_pack.lanes import ClaudeLifecycle\ns=ClaudeLifecycle(Library(sys.argv[1]),sys.argv[2],sys.argv[3])\np=json.loads(sys.stdin.read(2097153))\nprint(json.dumps(s.dispatch(sys.argv[4],p)))";
2038
+ return new Promise((done, fail) => {
2039
+ const child = launch("python3", ["-I", "-B", "-c", script, root, pack, policyPath, action, source], { stdio: ["pipe", "pipe", "pipe"], env: childEnv });
2040
+ let output = "";
2041
+ let settled = false;
2042
+ const finish = (error, value) => {
2043
+ if (settled) return;
2044
+ settled = true;
2045
+ clearTimeout(timer);
2046
+ error ? fail(error) : done(value);
2047
+ };
2048
+ const timer = setTimeout(() => {
2049
+ child.kill("SIGTERM");
2050
+ finish(new Error("Owned lifecycle helper timed out; preserve possible-effect custody."));
2051
+ }, 2e5);
2052
+ child.stdout.setEncoding("utf8");
2053
+ child.stderr.resume();
2054
+ child.stdout.on("data", (data) => {
2055
+ output += data;
2056
+ if (Buffer.byteLength(output) > 1048576) {
2057
+ child.kill("SIGTERM");
2058
+ finish(new Error("Bounded native lifecycle reply exceeded."));
2059
+ }
2060
+ });
2061
+ child.on("error", () => finish(new Error("Bundled lifecycle helper unavailable.")));
2062
+ child.on("close", (code) => {
2063
+ if (settled) return;
2064
+ if (code !== 0) return finish(new Error("Current context/policy/native lifecycle helper refused; no fallback or replay."));
2065
+ try {
2066
+ finish(void 0, JSON.parse(output));
2067
+ } catch {
2068
+ finish(new Error("Typed lifecycle helper returned invalid JSON."));
2069
+ }
2070
+ });
2071
+ child.stdin.on("error", () => finish(new Error("Own lifecycle helper input closed; reconcile original effect.")));
2072
+ child.stdin.end(encoded);
2073
+ });
2074
+ }
2075
+ function requireClaudePrivateQueryEffectQualified(operation) {
2076
+ if (["create", "configure", "context-start", "fixture-start", "retire", "approval-once"].includes(operation))
2077
+ throw Object.assign(
2078
+ new Error("native_private_query_prestart_contract_unqualified: private native query startup, exclusion and owned lifecycle are not qualified."),
2079
+ { code: "native_private_query_prestart_contract_unqualified" }
2080
+ );
2081
+ }
2082
+ function claudeLaneExpression(options, source, journal, prepared) {
2083
+ if (!Number.isSafeInteger(options.pid) || options.pid < 1 || !["plan", "create", "create-read", "adopt", "read", "configure", "context-start", "context-read", "fixture-start", "fixture-read", "retire"].includes(options.operation))
2084
+ throw new Error("Closed typed Claude lane operation required.");
2085
+ requireClaudePrivateQueryEffectQualified(options.operation);
2086
+ if (!options.privateConnection) throw new Error("Explicit approved private helper connection required before native access.");
2087
+ return `(async()=>{
2088
+ const expected=${JSON.stringify({ ...options, qualifier: CLAUDE_NATIVE_QUALIFIER, source, journal })};
2089
+ const requireClaudePrivateQueryEffectQualified=(${requireClaudePrivateQueryEffectQualified.toString()});
2090
+ requireClaudePrivateQueryEffectQualified(expected.operation);
2091
+ if(process.pid!==expected.pid || typeof process.getBuiltinModule!=='function')throw new Error('Native process identity changed.');
2092
+ const load=process.getBuiltinModule('module').createRequire(process.resourcesPath+'/app.asar/package.json');
2093
+ const fs=load('node:fs'),crypto=load('node:crypto'),path=load('node:path');
2094
+ const base=process.resourcesPath+'/app.asar/.vite/build/';
2095
+ const qualify=()=>{
2096
+ if(process.pid!==expected.pid || load('electron').app.getVersion()!==expected.qualifier.version)throw new Error('Native version/PID changed.');
2097
+ for(const [file,hash] of Object.entries(expected.qualifier.hashes))
2098
+ if(crypto.createHash('sha256').update(fs.readFileSync(base+file)).digest('hex')!==hash)throw new Error('Native module changed.');
2099
+ };
2100
+ qualify();const manager=load(base+expected.qualifier.manager).claudeCodeSessionManager;
2101
+ const canonical=value=>JSON.stringify(value,(_key,item)=>item&&typeof item==='object'&&!Array.isArray(item)?Object.fromEntries(Object.keys(item).sort().map(k=>[k,item[k]])):item);
2102
+ const fingerprint=value=>crypto.createHash('sha256').update(canonical(value)).digest('hex');
2103
+ const generation=fingerprint({pid:expected.pid,qualifier:expected.qualifier,root:expected.root,pack:expected.pack});
2104
+ const models=()=>{
2105
+ qualify();const rows=manager.getAvailableCodeModels();
2106
+ if(!Array.isArray(rows)||!rows.length||rows.some(m=>typeof m!=='string')||new Set(rows).size!==rows.length)throw new Error('Current native account model IDs unavailable.');
2107
+ return {harness:'claude',source:'native-account-model-ids',connectionGeneration:generation,models:[...rows].sort()};
2108
+ };
2109
+ const privateClaudeHelperEnvironment=(${privateClaudeHelperEnvironment.toString()});
2110
+ const helper=(action,payload)=>(${runClaudeLaneHelper.toString()})(expected.root,expected.pack,expected.policy,action,
2111
+ {...payload,...(action==='context-mark'?{historyCount:payload.historyCount??null,historyDigest:payload.historyDigest??null}:{}),models:models()},
2112
+ expected.source,expected.privateConnection,load('node:child_process').spawn,{fs,crypto,path,env:process.env},privateClaudeHelperEnvironment);
2113
+ const checkpoint=value=>{const fd=fs.openSync(expected.journal,'a');try{fs.writeSync(fd,JSON.stringify(value)+'\\n');fs.fsyncSync(fd);}finally{fs.closeSync(fd);}};
2114
+ const fixed=async role=>{
2115
+ const raw=await manager.getSessionWhenLoaded(role.nativeId,'topolo-dynamic-source',{warnOnMiss:false});
2116
+ const view=await manager.getSession(role.nativeId);qualify();
2117
+ if(!raw||!view||raw.sessionId!==role.nativeId||view.sessionId!==role.nativeId||raw.cwd!==role.cwd||view.cwd!==role.cwd||
2118
+ raw.isArchived||view.isArchived||raw.backend?.kind!=='local'||raw.backend.remoteTarget||raw.spawnedFrom||raw.worktreePath||raw.worktreeLazy)
2119
+ throw new Error('Exact source/intake actual native descriptor unavailable.');
2120
+ return {raw,view};
2121
+ };
2122
+ if(expected.operation==='plan'){
2123
+ if(Object.keys(expected.input).join()!=='request')throw new Error('Closed intake lane request required.');
2124
+ const current=await helper('peek',{sourceRoleKey:expected.input.request.sourceRoleKey});
2125
+ await fixed(current.role);await fixed(current.intake);
2126
+ const rows=await manager.getAllSessions();qualify();
2127
+ if(!Array.isArray(rows))throw new Error('Actual native ID-only creation inventory unavailable.');
2128
+ return helper('plan',{request:expected.input.request,nativeIds:rows.map(r=>r.sessionId)});
2129
+ }
2130
+ if(expected.operation==='create-read'){
2131
+ if(Object.keys(expected.input).join()!=='laneId')throw new Error('Exact immutable owned creation lane required.');
2132
+ const laneId=expected.input.laneId;
2133
+ const pending=await helper('creation-read',{laneId});
2134
+ const p=pending.plan;
2135
+ await fixed(p.role);await fixed(p.intake);
2136
+ const current=async()=>{const proof=await helper('creation-read',{laneId});
2137
+ if(canonical(proof.plan)!==canonical(p))throw new Error('Current immutable creation plan differs.');};
2138
+ if(!pending.creation.nativeId)throw new Error('Own native creation identity is unresolved; no replay.');
2139
+ await current();
2140
+ const native=await (${nativeClaudeReadEmptyCreation.toString()})(manager,{...p,creationNativeId:pending.creation.nativeId},qualify);
2141
+ if(native.state!=='ready')return {...native,laneId};
2142
+ const receipt={format:'topolo-native-lane-created',schemaVersion:1,state:'ready',planDigest:fingerprint(p),
2143
+ harness:'claude',nativeId:native.nativeId,logicalOriginThreadId:p.logicalOriginThreadId,cwd:native.cwd,
2144
+ model:native.model,effort:native.effort,nativeParentId:native.nativeParentId,fresh:true,creationSource:'supported-native-host-tool'};
2145
+ const record=await helper('adopt',{plan:p,receipt,native});
2146
+ return {state:'created-adopted-unconfigured',receipt,record,modelTurnsStarted:false,requestedTaskStarted:false};
2147
+ }
2148
+ if(expected.operation==='adopt'){
2149
+ if(Object.keys(expected.input).sort().join()!=='plan,receipt')throw new Error('Exact own host plan and creation receipt required.');
2150
+ const p=expected.input.plan,r=expected.input.receipt;await fixed(p.role);await fixed(p.intake);
2151
+ const raw=await manager.getSessionWhenLoaded(r.nativeId,'topolo-dynamic-adopt',{warnOnMiss:false});
2152
+ const view=await manager.getSession(r.nativeId);qualify();
2153
+ if(!raw||!view||raw.sessionId!==r.nativeId||view.sessionId!==r.nativeId||raw.cwd!==r.cwd||view.cwd!==r.cwd||raw.title!==view.title||
2154
+ raw.isArchived||view.isArchived||raw.backend?.kind!=='local'||raw.backend.remoteTarget||raw.worktreePath||raw.worktreeLazy||
2155
+ raw.spawnedFrom?.sessionId!==p.intake.nativeId||raw.spawnedFrom?.sideSession!==true)throw new Error('Actual child native raw parent or placement differs.');
2156
+ return helper('adopt',{plan:p,receipt:r,native:{nativeId:r.nativeId,cwd:view.cwd,title:view.title,model:view.model,effort:view.effort,
2157
+ nativeParentId:raw.spawnedFrom.sessionId,archived:false,backend:'local',foreignWorkspace:false,
2158
+ busy:!!(view.isRunning||view.starting||raw.isRunning||raw.starting||manager.hasLosableWork(r.nativeId)),pendingApprovals:view.pendingToolPermissions?.length??0}});
2159
+ }
2160
+ const prepared=${JSON.stringify(prepared ?? null)};
2161
+ if(!prepared)throw new Error('Exact registered own child preparation required.');
2162
+ const nativePlan={...prepared.nativePlan,deadline:Date.now()+200000};
2163
+ const snapshotMarkdown=(${snapshotClaudeMarkdown.toString()});
2164
+ const verifyContext=()=>{
2165
+ qualify();
2166
+ for(const [file,hash] of Object.entries(prepared.context))
2167
+ if(crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex')!==hash)throw new Error('Current source/registration/policy context changed.');
2168
+ for(const [cwd,inventory] of Object.entries(prepared.contextInventories))
2169
+ if(canonical(snapshotMarkdown(cwd,fs,crypto,path))!==canonical(inventory))throw new Error('Current source charter inventory changed.');
2170
+ };
2171
+ const qualifyOrganization=async()=>{await helper('read',{laneId:nativePlan.laneId});verifyContext();};
2172
+ let historyBefore;
2173
+ const ownHistory=async()=>{
2174
+ const raw=await manager.getSessionWhenLoaded(nativePlan.nativeId,'topolo-dynamic-history',{warnOnMiss:false});
2175
+ if(!raw||raw.backend?.kind!=='local'||raw.backend.remoteTarget||raw.spawnedFrom?.sessionId!==nativePlan.intake.sessionId)throw new Error('Own child transcript eligibility changed.');
2176
+ const messages=await manager.getTranscriptForCallerElsewhere(nativePlan.nativeId);qualify();
2177
+ if(!Array.isArray(messages))throw new Error('Exact own child transcript resolver unavailable.');return messages;
2178
+ };
2179
+ const history=(id,before)=>{if(id!==nativePlan.nativeId)throw new Error('Unrelated transcript forbidden.');
2180
+ return before===undefined?historyBefore:fingerprint(historyBefore)===before;};
2181
+ if(expected.operation==='configure'){
2182
+ const operation=await helper('configure-begin',{laneId:nativePlan.laneId,generation});
2183
+ // Helper's owned marker changes the registration; verify immutable source inputs and that precise beforeimage.
2184
+ delete prepared.context[path.resolve(expected.root,'dynamic-lanes/claude',nativePlan.laneId+'.json')];
2185
+ const result=await (${nativeClaudeDynamicLaneOperation.toString()})(manager,nativePlan,'configure',checkpoint,verifyContext,qualifyOrganization,history);
2186
+ const configured=await helper('configure-ack',{operation,native:result});
2187
+ const intakeRoute={key:prepared.record.plan.intake.key,sessionId:nativePlan.intake.sessionId,cwd:nativePlan.intake.cwd,title:nativePlan.intake.title,
2188
+ contextKey:prepared.record.plan.intake.contextKey,intakeKey:prepared.record.plan.intake.key,intakeSessionId:nativePlan.intake.sessionId};
2189
+ if(!manager[Symbol.for('topolo.agent-pack.approvals.v1')])
2190
+ await (${nativeClaudeApprovalOperation.toString()})(manager,[intakeRoute],{kind:'install'},fingerprint,checkpoint);
2191
+ const route={key:prepared.record.plan.role.key+'/dynamic/'+nativePlan.laneId,sessionId:nativePlan.nativeId,cwd:nativePlan.cwd,title:nativePlan.title,
2192
+ contextKey:prepared.record.plan.role.contextKey,intakeKey:prepared.record.plan.intake.key,intakeSessionId:nativePlan.intake.sessionId,
2193
+ dynamic:{laneId:nativePlan.laneId,planDigest:nativePlan.planDigest,nativeParentId:nativePlan.intake.sessionId,generation,connectionId:nativePlan.laneId}};
2194
+ await (${nativeClaudeAppendDynamicRoute.toString()})(manager,route,qualifyOrganization,checkpoint,{
2195
+ request:async(record,pending)=>{if(typeof pending.toolUseId!=='string')throw new Error('Actual native permission toolUseId is missing.');
2196
+ await helper('permission-request',{laneId:nativePlan.laneId,request:{nativeId:nativePlan.nativeId,fingerprint:record.fingerprint,requestId:pending.requestId,
2197
+ generation,intakeKey:record.intakeKey,intakeNativeId:record.intakeSessionId,toolUseId:pending.toolUseId}});},
2198
+ decision:async(record,pending,decision)=>helper('permission-decision',{laneId:nativePlan.laneId,decision:decision==='once'?'approved':'denied',
2199
+ intakeKey:record.intakeKey,fingerprint:record.fingerprint,generation})});
2200
+ const control=expected.control;
2201
+ if(!control)throw new Error('Exact owned per-lane native control setup required.');
2202
+ const secretInfo=fs.lstatSync(control.secretPath);
2203
+ if(!secretInfo.isFile()||secretInfo.isSymbolicLink()||secretInfo.uid!==process.getuid()||secretInfo.mode&63)throw new Error('Unowned private native control secret.');
2204
+ const secret=JSON.parse(fs.readFileSync(control.secretPath,'utf8'));
2205
+ const ownedOperation=async op=>{
2206
+ requireClaudePrivateQueryEffectQualified(op.kind==='approval-respond'&&op.decision==='once'?'approval-once':op.kind);
2207
+ qualify();const current=await helper('read',{laneId:nativePlan.laneId});
2208
+ const scopedPlan={...nativePlan,lifecycleState:current.state,deadline:Date.now()+200000};
2209
+ if(op.kind.startsWith('approval-')){
2210
+ const state=manager[Symbol.for('topolo.agent-pack.approvals.v1')];
2211
+ if(!state)throw new Error('Original native approval listener unavailable.');
2212
+ if(op.kind!=='approval-list'){
2213
+ const entry=state.entries.get(op.key);
2214
+ if(!entry||entry.record.sourceSessionId!==nativePlan.nativeId||entry.record.intakeSessionId!==nativePlan.intake.sessionId)
2215
+ throw new Error('Native approval is outside the exact owned child/original intake.');
2216
+ }
2217
+ const result=await (${nativeClaudeApprovalOperation.toString()})(manager,state.routes,
2218
+ {...op,kind:op.kind.slice('approval-'.length)},fingerprint,checkpoint);
2219
+ return op.kind==='approval-list'?{requests:result.requests.filter(r=>r.sourceSessionId===nativePlan.nativeId)}:result;
2220
+ }
2221
+ if(op.kind==='context-start'||op.kind==='context-read')return (${nativeClaudeDynamicContext.toString()})(manager,scopedPlan,
2222
+ {kind:op.kind,operationId:op.operationId},helper,fingerprint,verifyContext,qualifyOrganization);
2223
+ if(op.kind==='fixture-start'||op.kind==='fixture-read')return (${nativeClaudeDynamicFixture.toString()})(manager,scopedPlan,
2224
+ {kind:op.kind,operationId:op.operationId},helper,verifyContext,qualifyOrganization);
2225
+ if(op.kind==='read')return (${nativeClaudeDynamicLaneOperation.toString()})(manager,scopedPlan,'read',checkpoint,verifyContext,qualifyOrganization,history);
2226
+ if(op.kind==='retire'){
2227
+ const messages=await ownHistory();const before=fingerprint(messages);const retirement=await helper('retire-begin',{laneId:scopedPlan.laneId});
2228
+ const result=await (${nativeClaudeDynamicLaneOperation.toString()})(manager,scopedPlan,'retire',checkpoint,verifyContext,qualifyOrganization,
2229
+ async(id,saved)=>{if(id!==scopedPlan.nativeId)throw new Error('Unrelated transcript forbidden.');return saved===undefined?before:fingerprint(await ownHistory())===saved;});
2230
+ const retired=await helper('retire-ack',{operation:retirement,native:result});
2231
+ const state=manager[Symbol.for('topolo.agent-pack.approvals.v1')];
2232
+ if([...state.entries.values()].some(e=>e.record.sourceSessionId===scopedPlan.nativeId&&['pending','response-may-have-effects'].includes(e.record.state)))
2233
+ throw new Error('Own retired route still has an unresolved native request.');
2234
+ state.byId.delete(scopedPlan.nativeId);state.byKey.delete(route.key);state.dynamicRoutes?.delete(scopedPlan.nativeId);state.dynamicLifecycle?.delete(scopedPlan.nativeId);
2235
+ return retired;
2236
+ }
2237
+ if(op.kind==='close'){
2238
+ if(current.state!=='retired')throw new Error('Only a normally retired own child control may close.');
2239
+ return {state:'normal-own-lane-control-close-approved',laneId:scopedPlan.laneId};
2240
+ }
2241
+ throw new Error('Unsupported exact owned native lane operation.');
2242
+ };
2243
+ const connection=await (${nativeClaudeLaneControl.toString()})(load('node:net'),fs,manager,
2244
+ {socket:control.socket,pid:expected.pid,identity:control.identity,laneId:nativePlan.laneId},secret.token,
2245
+ ownedOperation,qualify,checkpoint);
2246
+ return {record:configured,connection};
2247
+
2248
+ }
2249
+ if(expected.operation==='read')return (${nativeClaudeDynamicLaneOperation.toString()})(manager,nativePlan,'read',checkpoint,verifyContext,qualifyOrganization,history);
2250
+ if(expected.operation==='context-start'||expected.operation==='context-read'){
2251
+ delete prepared.context[path.resolve(expected.root,'dynamic-lanes/claude',nativePlan.laneId+'.json')];
2252
+ return (${nativeClaudeDynamicContext.toString()})(manager,nativePlan,{kind:expected.operation,operationId:expected.input.operationId},
2253
+ helper,fingerprint,verifyContext,qualifyOrganization);
2254
+ }
2255
+ if(expected.operation==='fixture-start'||expected.operation==='fixture-read'){
2256
+ delete prepared.context[path.resolve(expected.root,'dynamic-lanes/claude',nativePlan.laneId+'.json')];
2257
+ return (${nativeClaudeDynamicFixture.toString()})(manager,nativePlan,{kind:expected.operation,operationId:expected.input.operationId},
2258
+ helper,verifyContext,qualifyOrganization);
2259
+ }
2260
+ if(expected.operation==='retire'){
2261
+ historyBefore=await ownHistory();const before=fingerprint(historyBefore);
2262
+ const operation=await helper('retire-begin',{laneId:nativePlan.laneId});
2263
+ delete prepared.context[path.resolve(expected.root,'dynamic-lanes/claude',nativePlan.laneId+'.json')];
2264
+ const result=await (${nativeClaudeDynamicLaneOperation.toString()})(manager,nativePlan,'retire',checkpoint,verifyContext,qualifyOrganization,
2265
+ async(id,saved)=>{if(id!==nativePlan.nativeId)throw new Error('Unrelated archive transcript forbidden.');if(saved===undefined)return before;return fingerprint(await ownHistory())===saved;});
2266
+ historyBefore=await ownHistory();if(fingerprint(historyBefore)!==before)throw new Error('Own child transcript preservation differs.');
2267
+ return helper('retire-ack',{operation,native:{...result,historyPreserved:true}});
2268
+ }
2269
+ throw new Error('Closed native fixture operation not yet qualified on this connection.');
2270
+ })()`;
2271
+ }
2272
+ async function operateClaudeLane(options, evaluate = evaluateClaudeMain) {
2273
+ requireClaudePrivateQueryEffectQualified(options.operation);
2274
+ validateInspectorEndpoint(options.endpoint);
2275
+ const root = realpathSync(options.store);
2276
+ const policy = realpathSync(options.policy);
2277
+ const release = await lockClaudeLibrary(root);
2278
+ try {
2279
+ const here = dirname(fileURLToPath(import.meta.url));
2280
+ const source = [resolve(here, "../../agent-packs/src"), resolve(here, "../agent-packs/src")].find(existsSync);
2281
+ if (!source) throw new Error("Installed typed lifecycle helper source unavailable.");
2282
+ const directory = resolve(root, "claude/dynamic-journals");
2283
+ mkdirSync(directory, { recursive: true, mode: 448 });
2284
+ if (lstatSync(directory).isSymbolicLink()) throw new Error("Unowned native lifecycle journal directory.");
2285
+ const journal = resolve(directory, randomUUID() + ".jsonl");
2286
+ durableRecord(journal, { operation: options.operation, pid: options.pid, at: Date.now() }, "wx");
2287
+ const prepared = ["plan", "create", "create-read", "adopt"].includes(options.operation) ? void 0 : prepareClaudeDynamicLane(root, options.pack, policy, options.input.laneId);
2288
+ let sourceRoleKey = prepared?.record.plan.role.key ?? (options.operation === "plan" ? options.input.request?.sourceRoleKey : options.input.plan?.role?.key);
2289
+ if (["create", "create-read"].includes(options.operation)) {
2290
+ if (typeof options.input.laneId !== "string" || !/^[a-z0-9][a-z0-9-]*$/.test(options.input.laneId)) throw new Error("Exact existing creation lane required.");
2291
+ const file = resolve(root, "dynamic-lanes/claude/plans", options.input.laneId + ".json");
2292
+ const info = lstatSync(file);
2293
+ if (!info.isFile() || info.isSymbolicLink() || info.nlink !== 1 || info.uid !== process.getuid?.() || info.mode & 18)
2294
+ throw new Error("Unowned immutable creation plan.");
2295
+ sourceRoleKey = JSON.parse(readFileSync(file, "utf8")).role?.key;
2296
+ }
2297
+ const privateConnection = prepareClaudePrivateHelperConnection(root, options.pack, policy, sourceRoleKey);
2298
+ let control;
2299
+ let connectionFile;
2300
+ if (options.operation === "configure") {
2301
+ if (!prepared) throw new Error("Exact fresh child preparation required.");
2302
+ const laneId = prepared.nativePlan.laneId;
2303
+ const privateRoot = resolve(root, "claude/dynamic-controls");
2304
+ mkdirSync(privateRoot, { recursive: true, mode: 448 });
2305
+ if (lstatSync(privateRoot).isSymbolicLink()) throw new Error("Unowned dynamic control directory.");
2306
+ const directory2 = resolve(privateRoot, laneId);
2307
+ mkdirSync(directory2, { mode: 448 });
2308
+ const secretPath = resolve(directory2, "secret.json");
2309
+ durableRecord(secretPath, { token: randomBytes(32).toString("hex") }, "wx");
2310
+ const identity = createHash("sha256").update(JSON.stringify({ pid: options.pid, laneId, planDigest: prepared.record.planDigest, qualifier: CLAUDE_NATIVE_QUALIFIER })).digest("hex");
2311
+ const socketDirectory = resolve("/tmp", "topolo-claude-" + process.getuid?.() + "-" + createHash("sha256").update(root + "\0" + laneId).digest("hex").slice(0, 24));
2312
+ mkdirSync(socketDirectory, { mode: 448 });
2313
+ const socket = resolve(socketDirectory, "control.sock");
2314
+ control = { socket, secretPath, identity };
2315
+ connectionFile = resolve(directory2, "connection.json");
2316
+ durableRecord(connectionFile, { state: "prepared", pid: options.pid, laneId, pack: options.pack, policy, root, journal, ...control }, "wx");
2317
+ }
2318
+ const result = await evaluate(options.endpoint, claudeLaneExpression({
2319
+ root,
2320
+ pack: options.pack,
2321
+ policy,
2322
+ pid: options.pid,
2323
+ operation: options.operation,
2324
+ input: options.input,
2325
+ privateConnection,
2326
+ ...control ? { control } : {}
2327
+ }, realpathSync(source), journal, prepared));
2328
+ if (connectionFile) {
2329
+ const value = JSON.parse(readFileSync(connectionFile, "utf8"));
2330
+ writeFileSync(connectionFile, JSON.stringify({ ...value, state: "ready" }) + "\n", { mode: 384 });
2331
+ }
2332
+ return result;
2333
+ } finally {
2334
+ await release();
2335
+ }
2336
+ }
2337
+ function operateClaudeLaneControl(options, request = requestClaudeApprovalControl) {
2338
+ requireClaudePrivateQueryEffectQualified(options.operation.kind === "approval-respond" && options.operation.decision === "once" ? "approval-once" : options.operation.kind);
2339
+ if (!/^[a-z0-9][a-z0-9-]*$/.test(options.connection)) throw new Error("Exact owned native lane connection ID required.");
2340
+ const root = realpathSync(options.store);
2341
+ const directory = resolve(root, "claude/dynamic-controls", options.connection);
2342
+ const owned = (file2) => {
2343
+ const info = lstatSync(file2);
2344
+ if (!info.isFile() || info.isSymbolicLink() || info.uid !== process.getuid?.() || info.mode & 63)
2345
+ throw new Error("Unowned private native lane connection record.");
2346
+ };
2347
+ const file = resolve(directory, "connection.json");
2348
+ owned(file);
2349
+ const connection = JSON.parse(readFileSync(file, "utf8"));
2350
+ if (connection.state !== "ready" || connection.laneId !== options.connection || connection.root !== root || !Number.isSafeInteger(connection.pid))
2351
+ throw new Error("Exact current ready native lane connection required.");
2352
+ owned(connection.secretPath);
2353
+ if (realpathSync(connection.secretPath) !== resolve(directory, "secret.json")) throw new Error("Private native secret path differs.");
2354
+ const secret = JSON.parse(readFileSync(connection.secretPath, "utf8"));
2355
+ return request(connection, options.operation, secret.token);
2356
+ }
1457
2357
  export {
1458
2358
  CLAUDE_NATIVE_QUALIFIER,
2359
+ claudeLaneExpression,
1459
2360
  configureClaudePack,
1460
2361
  evaluateClaudeMain,
1461
2362
  lockClaudeLibrary,
1462
2363
  nativePackExpression,
1463
2364
  operateClaudeApprovals,
2365
+ operateClaudeLane,
2366
+ operateClaudeLaneControl,
1464
2367
  operateClaudeSmoke,
2368
+ prepareClaudeDynamicLane,
1465
2369
  prepareClaudeNativePlan,
2370
+ prepareClaudePrivateHelperConnection,
2371
+ privateClaudeHelperEnvironment,
1466
2372
  requestClaudeApprovalControl,
2373
+ requireClaudePrivateQueryEffectQualified,
2374
+ runClaudeLaneHelper,
1467
2375
  runClaudeSmokeHelper,
1468
2376
  snapshotClaudeMarkdown,
1469
2377
  validateInspectorEndpoint,