@narumitw/pi-sync 0.60.2 → 0.60.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +4 -0
  3. package/dist/chunks/{chunk-B53FS4RW.ts → chunk-IGDI5CIH.ts} +2 -2
  4. package/dist/chunks/{chunk-ENFHHB5O.ts → chunk-OVCP2SOB.ts} +42 -6
  5. package/dist/chunks/chunk-OVCP2SOB.ts.map +7 -0
  6. package/dist/chunks/{chunk-E7UJHMNW.ts → chunk-RJZIKZI3.ts} +2 -2
  7. package/dist/chunks/{chunk-3YXBG7BQ.ts → chunk-SE7HHBKH.ts} +2 -2
  8. package/dist/chunks/{chunk-FOMZEZER.ts → chunk-VQRDL3SY.ts} +227 -54
  9. package/dist/chunks/chunk-VQRDL3SY.ts.map +7 -0
  10. package/dist/chunks/{command-handler-RTBEFZUX.ts → command-handler-TMH4US44.ts} +10 -8
  11. package/dist/chunks/command-handler-TMH4US44.ts.map +7 -0
  12. package/dist/chunks/{conflict-review-YXROU42F.ts → conflict-review-QGUCODDH.ts} +3 -3
  13. package/dist/chunks/{manager-result-dispatcher-4PEUHK7F.ts → manager-result-dispatcher-YVVD44QD.ts} +4 -4
  14. package/dist/chunks/{manager-ui-TNAMQNEU.ts → manager-ui-Q54OHOPR.ts} +8 -8
  15. package/dist/chunks/{remote-selection-ui-47H7V62F.ts → remote-selection-ui-ODSUHX5N.ts} +3 -3
  16. package/dist/chunks/{sync-inspection-5GQEB62G.ts → sync-inspection-ECUTWISE.ts} +3 -3
  17. package/dist/chunks/{sync-operations-65HDA67O.ts → sync-operations-REXODWZB.ts} +3 -3
  18. package/dist/index.ts +58 -39
  19. package/dist/index.ts.map +3 -3
  20. package/docs/agent-mode-verification.md +1 -1
  21. package/docs/agent-quality-verification.md +1 -1
  22. package/docs/continuous-sync-verification.md +1 -1
  23. package/docs/daemon-migration.md +82 -6
  24. package/docs/tui-contract.md +7 -1
  25. package/package.json +3 -3
  26. package/skills/configure-pi-sync/references/configuration.md +1 -0
  27. package/src/commands/command-execution.ts +1 -1
  28. package/src/commands/command-handler.ts +2 -0
  29. package/src/daemon/pi-client.ts +240 -51
  30. package/src/sync-extension.ts +62 -41
  31. package/src/ui/sync-status.ts +47 -4
  32. package/dist/chunks/chunk-ENFHHB5O.ts.map +0 -7
  33. package/dist/chunks/chunk-FOMZEZER.ts.map +0 -7
  34. package/dist/chunks/command-handler-RTBEFZUX.ts.map +0 -7
  35. package/docs/settings.md +0 -90
  36. /package/dist/chunks/{chunk-B53FS4RW.ts.map → chunk-IGDI5CIH.ts.map} +0 -0
  37. /package/dist/chunks/{chunk-E7UJHMNW.ts.map → chunk-RJZIKZI3.ts.map} +0 -0
  38. /package/dist/chunks/{chunk-3YXBG7BQ.ts.map → chunk-SE7HHBKH.ts.map} +0 -0
  39. /package/dist/chunks/{conflict-review-YXROU42F.ts.map → conflict-review-QGUCODDH.ts.map} +0 -0
  40. /package/dist/chunks/{manager-result-dispatcher-4PEUHK7F.ts.map → manager-result-dispatcher-YVVD44QD.ts.map} +0 -0
  41. /package/dist/chunks/{manager-ui-TNAMQNEU.ts.map → manager-ui-Q54OHOPR.ts.map} +0 -0
  42. /package/dist/chunks/{remote-selection-ui-47H7V62F.ts.map → remote-selection-ui-ODSUHX5N.ts.map} +0 -0
  43. /package/dist/chunks/{sync-inspection-5GQEB62G.ts.map → sync-inspection-ECUTWISE.ts.map} +0 -0
  44. /package/dist/chunks/{sync-operations-65HDA67O.ts.map → sync-operations-REXODWZB.ts.map} +0 -0
package/dist/index.ts CHANGED
@@ -4,7 +4,7 @@ import {
4
4
  createSyncAttentionController,
5
5
  readStateForConfig,
6
6
  syncStateFingerprint
7
- } from "./chunks/chunk-E7UJHMNW.ts";
7
+ } from "./chunks/chunk-RJZIKZI3.ts";
8
8
  import "./chunks/chunk-HEB6YT64.ts";
9
9
  import {
10
10
  withStateDirectoryAccess
@@ -21,12 +21,12 @@ import {
21
21
  installPiDaemonHost,
22
22
  piDaemonClient,
23
23
  withPiDaemonClient
24
- } from "./chunks/chunk-FOMZEZER.ts";
24
+ } from "./chunks/chunk-VQRDL3SY.ts";
25
25
  import {
26
26
  configureSyncStatus,
27
27
  createSyncStatusPublisher,
28
28
  setSyncStatus
29
- } from "./chunks/chunk-ENFHHB5O.ts";
29
+ } from "./chunks/chunk-OVCP2SOB.ts";
30
30
  import {
31
31
  completeSyncArguments,
32
32
  setSyncSetupCompletions,
@@ -289,12 +289,12 @@ function createStartupCheck(loaders, attention, timeoutMs = 3e4, publish) {
289
289
  // src/sync/sync-loaders.ts
290
290
  function createSyncLoaders(dependencies) {
291
291
  const loaders = {
292
- commands: cachedModuleLoader(dependencies.loadCommandHandler ?? (() => import("./chunks/command-handler-RTBEFZUX.ts"))),
293
- inspection: cachedModuleLoader(dependencies.loadSyncInspection ?? (() => import("./chunks/sync-inspection-5GQEB62G.ts"))),
292
+ commands: cachedModuleLoader(dependencies.loadCommandHandler ?? (() => import("./chunks/command-handler-TMH4US44.ts"))),
293
+ inspection: cachedModuleLoader(dependencies.loadSyncInspection ?? (() => import("./chunks/sync-inspection-ECUTWISE.ts"))),
294
294
  setupSwitch: cachedModuleLoader(dependencies.loadSetupSwitch ?? (() => import("./chunks/setup-switch-SPZE7HIQ.ts"))),
295
295
  snapshot: cachedModuleLoader(dependencies.loadSnapshot ?? (() => import("./chunks/snapshot-5HY3M2NL.ts"))),
296
296
  syncState: cachedModuleLoader(dependencies.loadSyncState ?? (() => import("./chunks/sync-state-2LMIXJ2C.ts"))),
297
- operations: cachedModuleLoader(dependencies.loadSyncOperations ?? (() => import("./chunks/sync-operations-65HDA67O.ts")))
297
+ operations: cachedModuleLoader(dependencies.loadSyncOperations ?? (() => import("./chunks/sync-operations-REXODWZB.ts")))
298
298
  };
299
299
  return loaders;
300
300
  }
@@ -363,39 +363,58 @@ function sync(pi, dependencies = {}) {
363
363
  await commands.handleCommand(args, ctx, signal, loaders, attention);
364
364
  return;
365
365
  }
366
- await withPiDaemonClient(ctx, async (ownedContext) => {
367
- ctx = ownedContext;
368
- const command = splitArgs(args)[0];
369
- const ready = await initialization;
370
- if (signal.aborted || owner !== client) return;
371
- await client.setBusy("command", true);
372
- try {
373
- await check.stop();
374
- if (signal.aborted || owner !== client) return;
375
- if (ready === false && command !== "help" && command !== "unlock" && command !== "migrate-state" && command !== "daemon") {
376
- ctx.ui.notify(
377
- "pi-sync recovery required. Repair the startup error, then /reload before syncing. Use /sync help for recovery guidance.",
378
- "error"
379
- );
380
- return;
381
- }
382
- if (command === "unlock" || command === "migrate-state") {
383
- const { stateDirectoryMigrationNotice } = await import("./chunks/state-directory-XXHU73Z3.ts");
366
+ const reload = new AbortController();
367
+ const commandSignal = combineSignals(signal, reload.signal);
368
+ try {
369
+ await withPiDaemonClient(
370
+ ctx,
371
+ async (ctx2) => {
372
+ const command = splitArgs(args)[0];
373
+ const ready = await initialization;
384
374
  if (signal.aborted || owner !== client) return;
385
- stateDirectoryMigrationNotice();
386
- }
387
- const commands = await loaders.commands();
388
- if (signal.aborted || owner !== client) return;
389
- await commands.handleCommand(args, ctx, signal, loaders, attention);
390
- } catch (error) {
391
- if (!signal.aborted) {
392
- ctx.ui.notify(`pi-sync command unavailable: ${safeTerminalText(errorMessage(error))}`, "error");
393
- if (command === "unlock" || command === "migrate-state") throw error;
394
- }
395
- } finally {
396
- if (!signal.aborted && owner === client) await client.setBusy("command", false);
397
- }
398
- });
375
+ const requiresContact = !["help", "unlock", "migrate-state"].includes(command ?? "");
376
+ let busyPublished = false;
377
+ try {
378
+ await client.setBusy("command", true, requiresContact);
379
+ busyPublished = requiresContact;
380
+ if (signal.aborted || owner !== client) return;
381
+ await check.stop();
382
+ if (signal.aborted || owner !== client) return;
383
+ if (ready === false && command !== "help" && command !== "unlock" && command !== "migrate-state" && command !== "daemon") {
384
+ ctx2.ui.notify(
385
+ "pi-sync recovery required. Repair the startup error, then /reload before syncing. Use /sync help for recovery guidance.",
386
+ "error"
387
+ );
388
+ return;
389
+ }
390
+ if (command === "unlock" || command === "migrate-state") {
391
+ const { stateDirectoryMigrationNotice } = await import("./chunks/state-directory-XXHU73Z3.ts");
392
+ if (signal.aborted || owner !== client) return;
393
+ stateDirectoryMigrationNotice();
394
+ }
395
+ const commands = await loaders.commands();
396
+ if (signal.aborted || owner !== client) return;
397
+ await commands.handleCommand(args, ctx2, commandSignal, loaders, attention);
398
+ } catch (error) {
399
+ if (!commandSignal.aborted && owner === client) {
400
+ ctx2.ui.notify(`pi-sync command unavailable: ${safeTerminalText(errorMessage(error))}`, "error");
401
+ if (command === "unlock" || command === "migrate-state") throw error;
402
+ }
403
+ } finally {
404
+ if (!signal.aborted && owner === client) {
405
+ const publish = busyPublished || command === "unlock" || command === "migrate-state";
406
+ await client.setBusy("command", false, publish).catch(() => {
407
+ });
408
+ }
409
+ }
410
+ },
411
+ reload
412
+ );
413
+ if (!signal.aborted && owner === client && client.canReload(reload)) await ctx.reload();
414
+ } finally {
415
+ client.releaseReload(reload);
416
+ reload.abort();
417
+ }
399
418
  }
400
419
  });
401
420
  pi.on("session_start", async (_event, ctx) => {
@@ -420,7 +439,7 @@ function sync(pi, dependencies = {}) {
420
439
  await check.stop();
421
440
  if (previousClient) {
422
441
  try {
423
- await client.attachExisting();
442
+ await client.attachExisting({ allowUpgrade: true });
424
443
  } catch {
425
444
  }
426
445
  try {
package/dist/index.ts.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/sync/agent-policy.ts", "../src/settings/config-errors.ts", "../src/sync/startup-timings.ts", "../src/sync/automatic-sync.ts", "../src/sync/startup-check.ts", "../src/sync/sync-loaders.ts", "../src/ui/startup-timings-entry.ts", "../src/sync-extension.ts"],
4
- "sourcesContent": ["export type * from \"@narumitw/pi-sync-daemon/engine/sync/agent-policy\";\nexport {\n AGENT_INPUT_BYTES,\n AGENT_MAX_ATTEMPTS,\n AGENT_MAX_TOKENS,\n AGENT_MAX_UNITS,\n AGENT_OUTPUT_BYTES,\n AGENT_TIMEOUT_MS,\n startupTransferEnabled,\n} from \"@narumitw/pi-sync-daemon/engine/sync/agent-policy\";\n", "export type * from \"@narumitw/pi-sync-daemon/engine/settings/config-errors\";\nexport { isMissingConfigError } from \"@narumitw/pi-sync-daemon/engine/settings/config-errors\";\n", "export type * from \"@narumitw/pi-sync-daemon/engine/sync/startup-timings\";\nexport { createStartupTimings } from \"@narumitw/pi-sync-daemon/engine/sync/startup-timings\";\n", "import type { ExtensionContext } from \"@earendil-works/pi-coding-agent\";\nimport { setSyncSetupCompletions } from \"../commands/command.js\";\nimport { piDaemonClient } from \"../daemon/pi-client.js\";\nimport { isMissingConfigError } from \"../settings/config-errors.js\";\nimport type { AnySyncConfig, PiSyncSettingsV3 } from \"../settings/settings-types.js\";\nimport { configureSyncStatus } from \"../ui/sync-status.js\";\nimport { safeTerminalText } from \"../ui/terminal-text.js\";\nimport { throwIfAborted } from \"./signals.js\";\nimport { createStartupTimings, type StartupTimingPublisher } from \"./startup-timings.js\";\nimport { errorMessage } from \"./sync-errors.js\";\nimport type { SyncLoaders } from \"./sync-loaders.js\";\n\nexport async function startSession(\n ctx: ExtensionContext,\n signal: AbortSignal,\n publish?: StartupTimingPublisher,\n): Promise<{ debug: boolean; config?: AnySyncConfig } | undefined> {\n throwIfAborted(signal);\n const client = piDaemonClient(ctx);\n // One-off sessions only protect their files in an already existing service.\n // They never launch it or authorize observations, transfers, or model work.\n if (!ctx.hasUI || ![\"tui\", \"rpc\"].includes(ctx.mode)) {\n await client.attachExisting();\n throwIfAborted(signal);\n return { debug: false };\n }\n const timings = createStartupTimings(publish);\n const document = await timings.measure(\"settings read\", () => client.readSettings());\n throwIfAborted(signal);\n configureSyncStatus(ctx, (document?.parsed.showStatus as boolean | undefined) ?? true);\n const { stateDirectoryMigrationNotice } = await import(\"../state/state-directory.js\");\n const notice = stateDirectoryMigrationNotice();\n const { pendingTransactionEntries } = await import(\"../snapshot/snapshot-transaction-directory.js\");\n const recoveryNeeded = (await pendingTransactionEntries()).some((entry) => entry.isDirectory());\n throwIfAborted(signal);\n if (!(await client.configured()) && !recoveryNeeded) {\n if (notice) ctx.ui.notify(notice, \"warning\");\n setSyncSetupCompletions([]);\n const debug = document?.parsed.debug === true;\n await client.markReady(debug);\n timings.publish(ctx, debug, signal, \"local initialization\", \"completed\");\n return { debug };\n }\n throwIfAborted(signal);\n const result = (await client.run(\"initialize\", {}, signal)) as {\n debug: boolean;\n config?: AnySyncConfig;\n settings?: PiSyncSettingsV3;\n handoverRequired: boolean;\n };\n throwIfAborted(signal);\n configureSyncStatus(ctx, result.settings?.showStatus ?? true);\n setSyncSetupCompletions(Object.keys(result.settings?.syncSetups ?? {}).sort((a, b) => a.localeCompare(b)));\n await client.markReady(result.debug);\n throwIfAborted(signal);\n if (result.handoverRequired) {\n ctx.ui.notify(\n \"pi-sync: close or upgrade older Pi processes, then use /sync to review daemon handover. No automatic transfer is authorized yet.\",\n \"warning\",\n );\n return { debug: result.debug };\n }\n return { debug: result.debug, config: result.config };\n}\nexport async function autoPushSessions(ctx: ExtensionContext, signal: AbortSignal, _loaders: SyncLoaders) {\n try {\n const client = piDaemonClient(ctx);\n if (!(await client.configured())) return;\n throwIfAborted(signal);\n await client.run(\n \"shutdown\",\n { args: [], yes: true, force: false, stale: false, silent: true, reload: false },\n signal,\n );\n } catch (error) {\n if (signal.aborted || isMissingConfigError(error)) return;\n ctx.ui.notify(`pi-sync session push skipped: ${safeTerminalText(errorMessage(error))}`, \"warning\");\n }\n}\n", "import type { ExtensionContext } from \"@earendil-works/pi-coding-agent\";\nimport { loadConfigForCheck, syncCheckConfigFingerprint } from \"../settings/config.js\";\nimport { isMissingConfigError } from \"../settings/config-errors.js\";\nimport type { AnySyncConfig } from \"../settings/settings-types.js\";\nimport { snapshotOptionsForContext } from \"../snapshot/session-paths.js\";\nimport { withStateDirectoryAccess } from \"../state/state-directory.js\";\nimport { readStateForConfig, syncStateFingerprint } from \"../state/sync-state-store.js\";\nimport type { SyncAttentionController } from \"../ui/sync-attention.js\";\nimport { setSyncStatus } from \"../ui/sync-status.js\";\nimport { safeTerminalText } from \"../ui/terminal-text.js\";\nimport { startupTransferEnabled } from \"./agent-policy.js\";\nimport { combineSignals, throwIfAborted } from \"./signals.js\";\nimport { createStartupTimings, type StartupTimingPublisher } from \"./startup-timings.js\";\nimport { errorMessage } from \"./sync-errors.js\";\nimport type { SyncLoaders } from \"./sync-loaders.js\";\n\n/** One owned task per extension session, never keyed by the shared headless UI. */\nexport function createStartupCheck(\n loaders: SyncLoaders,\n attention: SyncAttentionController,\n timeoutMs = 30_000,\n publish?: StartupTimingPublisher,\n) {\n let active:\n | {\n controller: AbortController;\n promise: Promise<void>;\n owner: ExtensionContext[\"sessionManager\"];\n transfer: boolean;\n }\n | undefined;\n\n let pending: { ctx: ExtensionContext; signal: AbortSignal; config: AnySyncConfig } | undefined;\n\n const controllerApi = {\n async interrupt(ctx: ExtensionContext) {\n const task = active;\n if (!task?.transfer || task.owner !== ctx.sessionManager) return;\n task.controller.abort(new DOMException(\"Agent became busy\", \"AbortError\"));\n await task.promise;\n },\n settled(ctx: ExtensionContext) {\n const queued = pending;\n if (!queued || queued.ctx.sessionManager !== ctx.sessionManager || queued.signal.aborted || !ctx.isIdle()) return;\n pending = undefined;\n controllerApi.start(ctx, queued.signal, queued.config);\n },\n start(ctx: ExtensionContext, sessionSignal: AbortSignal, initialConfig?: AnySyncConfig) {\n if (!ctx.hasUI || sessionSignal.aborted) return;\n if (initialConfig && startupTransferEnabled(initialConfig) && !ctx.isIdle()) {\n pending = { ctx, signal: sessionSignal, config: initialConfig };\n return;\n }\n if (active) throw new Error(\"Previous startup check has not been drained.\");\n const timings = createStartupTimings(publish);\n const controller = new AbortController();\n const signal = combineSignals(sessionSignal, controller.signal);\n const task = {\n controller,\n owner: ctx.sessionManager,\n promise: Promise.resolve(),\n transfer: Boolean(initialConfig && startupTransferEnabled(initialConfig)),\n };\n active = task;\n const isCurrent = () => !sessionSignal.aborted && active === task && task.owner === ctx.sessionManager;\n const timer = setTimeout(\n () => controller.abort(new DOMException(\"Startup check timed out\", \"TimeoutError\")),\n timeoutMs,\n );\n timer.unref();\n let config: AnySyncConfig | undefined;\n let checking = false;\n let stopped = false;\n // Handle every detached rejection here; Pi's awaited event runner cannot catch it.\n task.promise = Promise.resolve()\n .then(async () => {\n try {\n throwIfAborted(signal);\n config = initialConfig ?? (await loadConfigForCheck());\n task.transfer = startupTransferEnabled(config);\n throwIfAborted(signal);\n if (!config.automatic && !startupTransferEnabled(config)) return;\n const captured = config;\n const identity = syncCheckConfigFingerprint(captured);\n checking = true;\n setSyncStatus(ctx, \"sync ...\", { activity: \"checking\" });\n const { inspectSync } = await timings.measure(\"inspection import\", () => loaders.inspection());\n throwIfAborted(signal);\n const currentConfig = await loadConfigForCheck();\n throwIfAborted(signal);\n if (syncCheckConfigFingerprint(currentConfig) !== identity) return;\n // The daemon owns the operation and cache guards.\n const inspection = await timings.measure(\"inspection and guards\", () =>\n inspectSync(captured, snapshotOptionsForContext(ctx, captured), signal, undefined, timings),\n );\n throwIfAborted(signal);\n const latest = await loadConfigForCheck();\n throwIfAborted(signal);\n if (syncCheckConfigFingerprint(latest) !== identity) return;\n const state = await withStateDirectoryAccess(() => readStateForConfig(latest));\n throwIfAborted(signal);\n if (syncStateFingerprint(state) !== inspection.stateIdentity || !isCurrent()) return;\n attention.observe({\n setupName: captured.setupName,\n configIdentity: identity,\n checkedAt: new Date().toISOString(),\n inspection,\n automaticTransfer: startupTransferEnabled(captured),\n });\n if (\n startupTransferEnabled(captured) &&\n !inspection.firstSync &&\n inspection.head &&\n inspection.selectionState?.kind === \"same\"\n ) {\n const operations = await timings.measure(\"operations import\", () => loaders.operations());\n throwIfAborted(signal);\n if (!isCurrent()) return;\n if (!ctx.isIdle()) {\n pending = { ctx, signal: sessionSignal, config: captured };\n return;\n }\n await timings.measure(\"automatic transfer\", () =>\n operations.syncBoth(ctx, {\n args: [],\n yes: true,\n force: false,\n stale: false,\n silent: true,\n reload: false,\n auto: true,\n signal,\n startupTimings: timings,\n onCommit: () => attention.clearObservation(),\n }),\n );\n throwIfAborted(signal);\n if (!isCurrent()) return;\n attention.clearObservation();\n return;\n }\n attention.observe({\n setupName: captured.setupName,\n configIdentity: identity,\n checkedAt: new Date().toISOString(),\n inspection,\n automaticTransfer: startupTransferEnabled(captured),\n });\n if (ctx.mode === \"rpc\") attention.notifyObservation(ctx);\n } catch (error) {\n stopped = true;\n if (!isCurrent() || sessionSignal.aborted || isMissingConfigError(error)) return;\n if (signal.aborted && controller.signal.reason?.name !== \"TimeoutError\") return;\n // A settings edit invalidates failures as well as successful observations.\n if (config) {\n const latest = await loadConfigForCheck().catch(() => undefined);\n if (!isCurrent() || (signal.aborted && controller.signal.reason?.name !== \"TimeoutError\")) return;\n if (!latest || syncCheckConfigFingerprint(latest) !== syncCheckConfigFingerprint(config)) return;\n }\n ctx.ui.notify(\n config && startupTransferEnabled(config)\n ? `pi-sync automatic transfer stopped: ${safeTerminalText(errorMessage(error))}. Run /sync to review or reconcile retained recovery evidence. No resources were reloaded.`\n : `pi-sync startup check skipped: ${safeTerminalText(errorMessage(error))}. Run /sync status to retry. No startup transfer was performed.`,\n \"warning\",\n );\n } finally {\n clearTimeout(timer);\n if (isCurrent() && checking) {\n if (!signal.aborted || controller.signal.reason?.name === \"TimeoutError\") {\n const latest = await loadConfigForCheck().catch(() => undefined);\n if (isCurrent()) {\n if (signal.aborted && controller.signal.reason?.name !== \"TimeoutError\")\n setSyncStatus(ctx, undefined);\n else if (\n config &&\n latest &&\n syncCheckConfigFingerprint(latest) === syncCheckConfigFingerprint(config)\n )\n await attention.publish(ctx, sessionSignal);\n else attention.reset(ctx);\n }\n } else setSyncStatus(ctx, undefined);\n }\n if (isCurrent()) {\n timings.publish(\n ctx,\n config?.debug ?? false,\n sessionSignal,\n \"background startup\",\n signal.aborted || stopped ? \"stopped\" : \"completed\",\n );\n }\n if (active === task) active = undefined;\n }\n })\n .catch(() => {\n // UI teardown can itself throw. No unhandled rejection or retained timer.\n clearTimeout(timer);\n if (active === task) active = undefined;\n });\n },\n async stop() {\n pending = undefined;\n const task = active;\n if (!task) return;\n task.controller.abort(new DOMException(\"Startup check cancelled\", \"AbortError\"));\n // Drain the actual work, including child/ref cleanup, before foreground guards.\n await task.promise;\n },\n };\n return controllerApi;\n}\n", "type SetupSwitchModule = Pick<typeof import(\"./setup-switch.js\"), \"useSyncSetup\">;\ntype SnapshotModule = Pick<typeof import(\"../snapshot/snapshot.js\"), \"createSnapshot\">;\ntype SyncStateModule = Pick<typeof import(\"./sync-state.js\"), \"hasLocalChanges\">;\ntype SyncOperations = typeof import(\"./sync-operations.js\");\ntype CommandHandlerModule = Pick<typeof import(\"../commands/command-handler.js\"), \"handleCommand\">;\n\ntype SyncInspectionModule = Pick<typeof import(\"./sync-inspection.js\"), \"inspectSync\">;\n\nexport interface SyncDependencies {\n loadCommandHandler(): Promise<CommandHandlerModule>;\n loadSyncInspection(): Promise<SyncInspectionModule>;\n loadSetupSwitch(): Promise<SetupSwitchModule>;\n loadSnapshot(): Promise<SnapshotModule>;\n loadSyncState(): Promise<SyncStateModule>;\n loadSyncOperations(): Promise<SyncOperations>;\n}\n\nexport interface SyncLoaders {\n commands(): Promise<CommandHandlerModule>;\n inspection(): Promise<SyncInspectionModule>;\n setupSwitch(): Promise<SetupSwitchModule>;\n snapshot(): Promise<SnapshotModule>;\n syncState(): Promise<SyncStateModule>;\n operations(): Promise<SyncOperations>;\n}\n\nexport function createSyncLoaders(dependencies: Partial<SyncDependencies>): SyncLoaders {\n const loaders: SyncLoaders = {\n commands: cachedModuleLoader(dependencies.loadCommandHandler ?? (() => import(\"../commands/command-handler.js\"))),\n inspection: cachedModuleLoader(dependencies.loadSyncInspection ?? (() => import(\"./sync-inspection.js\"))),\n setupSwitch: cachedModuleLoader(dependencies.loadSetupSwitch ?? (() => import(\"./setup-switch.js\"))),\n snapshot: cachedModuleLoader(dependencies.loadSnapshot ?? (() => import(\"../snapshot/snapshot.js\"))),\n syncState: cachedModuleLoader(dependencies.loadSyncState ?? (() => import(\"./sync-state.js\"))),\n operations: cachedModuleLoader(dependencies.loadSyncOperations ?? (() => import(\"./sync-operations.js\"))),\n };\n return loaders;\n}\n\nfunction cachedModuleLoader<Module>(load: () => Promise<Module>): () => Promise<Module> {\n let pending: Promise<Module> | undefined;\n return () => {\n if (!pending) {\n pending = load().catch((error) => {\n pending = undefined;\n throw error;\n });\n }\n return pending;\n };\n}\n", "import type { ExtensionAPI } from \"@earendil-works/pi-coding-agent\";\nimport { Text, truncateToWidth } from \"@earendil-works/pi-tui\";\nimport type { StartupTimingPublisher } from \"../sync/startup-timings.js\";\nimport { safeTerminalText } from \"./terminal-text.js\";\n\nexport const STARTUP_TIMING_ENTRY = \"pi-sync-startup-timings\";\n\nexport interface StartupTimingEntry {\n version: 1;\n report: string;\n}\n\nexport function registerStartupTimings(pi: ExtensionAPI): StartupTimingPublisher {\n pi.registerEntryRenderer<StartupTimingEntry>(STARTUP_TIMING_ENTRY, (entry, _options, theme) => {\n const data = entry.data;\n if (data?.version !== 1 || typeof data.report !== \"string\") return undefined;\n const text = new Text(\n data.report\n .split(\"\\n\")\n .map((line, index) => theme.fg(index === 0 ? \"accent\" : \"muted\", safeTerminalText(line)))\n .join(\"\\n\"),\n 0,\n 0,\n );\n return {\n render: (width) => (width > 0 ? text.render(width).map((line) => truncateToWidth(line, width)) : []),\n invalidate: () => text.invalidate(),\n };\n });\n return (ctx, report) => {\n // Pi coalesces consecutive info notifications, including the final /reload notice.\n // Custom entries remain visible without adding messages to model context.\n if (ctx.mode === \"tui\") pi.appendEntry<StartupTimingEntry>(STARTUP_TIMING_ENTRY, { version: 1, report });\n else ctx.ui.notify(report, \"info\");\n };\n}\n", "import type { ExtensionAPI, ExtensionContext } from \"@earendil-works/pi-coding-agent\";\nimport { completeSyncArguments, splitArgs } from \"./commands/command.js\";\nimport {\n bindPiDaemonClient,\n installPiDaemonHost,\n type PiDaemonClient,\n withPiDaemonClient,\n} from \"./daemon/pi-client.js\";\nimport type { AnySyncConfig } from \"./settings/settings-types.js\";\nimport { startupTransferEnabled } from \"./sync/agent-policy.js\";\nimport { autoPushSessions, startSession } from \"./sync/automatic-sync.js\";\nimport { combineSignals } from \"./sync/signals.js\";\nimport { createStartupCheck } from \"./sync/startup-check.js\";\nimport { errorMessage } from \"./sync/sync-errors.js\";\nimport { createSyncLoaders, type SyncDependencies } from \"./sync/sync-loaders.js\";\nimport { registerStartupTimings } from \"./ui/startup-timings-entry.js\";\nimport { createSyncAttentionController } from \"./ui/sync-attention.js\";\nimport { createSyncStatusPublisher } from \"./ui/sync-status.js\";\nimport { safeTerminalText } from \"./ui/terminal-text.js\";\n\nexport default function sync(pi: ExtensionAPI, dependencies: Partial<SyncDependencies> = {}) {\n installPiDaemonHost();\n const loaders = createSyncLoaders(dependencies);\n const attention = createSyncAttentionController();\n const status = createSyncStatusPublisher(pi.events);\n const publishTimings = registerStartupTimings(pi);\n const check = createStartupCheck(loaders, attention, 30_000, publishTimings);\n let sessionAbort = new AbortController();\n let shutdownAbort: AbortController | undefined;\n let initialization = Promise.resolve<AnySyncConfig | false | undefined>(undefined);\n let owner: PiDaemonClient | undefined;\n let ownerManager: ExtensionContext[\"sessionManager\"] | undefined;\n\n pi.registerCommand(\"sync\", {\n description: \"Sync Pi settings through Git, WebDAV, R2, or S3-compatible storage\",\n getArgumentCompletions: completeSyncArguments,\n handler: async (args, ctx) => {\n if (!ctx.hasUI) throw new Error(\"/sync requires TUI or RPC mode so results and safety prompts are observable.\");\n status.bind(ctx);\n const signal = sessionAbort.signal;\n const client = owner;\n if (!client || ownerManager !== ctx.sessionManager) {\n if (splitArgs(args)[0] !== \"help\") throw new Error(\"pi-sync session is not ready.\");\n const commands = await loaders.commands();\n if (signal.aborted || owner) return;\n ctx.isIdle();\n await commands.handleCommand(args, ctx, signal, loaders, attention);\n return;\n }\n await withPiDaemonClient(ctx, async (ownedContext) => {\n ctx = ownedContext;\n const command = splitArgs(args)[0];\n const ready = await initialization;\n if (signal.aborted || owner !== client) return;\n await client.setBusy(\"command\", true);\n try {\n await check.stop();\n if (signal.aborted || owner !== client) return;\n if (\n ready === false &&\n command !== \"help\" &&\n command !== \"unlock\" &&\n command !== \"migrate-state\" &&\n command !== \"daemon\"\n ) {\n ctx.ui.notify(\n \"pi-sync recovery required. Repair the startup error, then /reload before syncing. Use /sync help for recovery guidance.\",\n \"error\",\n );\n return;\n }\n if (command === \"unlock\" || command === \"migrate-state\") {\n const { stateDirectoryMigrationNotice } = await import(\"./state/state-directory.js\");\n if (signal.aborted || owner !== client) return;\n // Recovery cannot guess an authoritative root when roots coexist or are unsafe.\n stateDirectoryMigrationNotice();\n }\n const commands = await loaders.commands();\n if (signal.aborted || owner !== client) return;\n await commands.handleCommand(args, ctx, signal, loaders, attention);\n } catch (error) {\n if (!signal.aborted) {\n ctx.ui.notify(`pi-sync command unavailable: ${safeTerminalText(errorMessage(error))}`, \"error\");\n if (command === \"unlock\" || command === \"migrate-state\") throw error;\n }\n } finally {\n if (!signal.aborted && owner === client) await client.setBusy(\"command\", false);\n }\n });\n },\n });\n pi.on(\"session_start\", async (_event, ctx) => {\n const releaseStatus = status.start(ctx);\n const previousClient = owner;\n shutdownAbort?.abort(new DOMException(\"Session replaced\", \"AbortError\"));\n shutdownAbort = undefined;\n sessionAbort.abort(new DOMException(\"Session replaced\", \"AbortError\"));\n sessionAbort = new AbortController();\n const signal = sessionAbort.signal;\n const client = bindPiDaemonClient(ctx, signal, publishTimings);\n owner = client;\n ownerManager = ctx.sessionManager;\n const replacementFile = ctx.sessionManager.getSessionFile?.();\n attention.reset(ctx);\n const previous = initialization;\n initialization = withPiDaemonClient(ctx, async () => {\n await previous.catch(() => {});\n if (signal.aborted || owner !== client) return false;\n try {\n await check.stop();\n if (previousClient) {\n // Register the replacement before removing old session protection.\n try {\n await client.attachExisting();\n } catch {\n /* Initialization below reports an unavailable owner. */\n }\n try {\n await previousClient.disposeForShutdown(\"resume\", replacementFile);\n } catch {\n /* Plain, detached recovery owns uncertain grants; no closed ctx is retained. */\n }\n await client.finishReattachment();\n }\n if (signal.aborted || owner !== client) return false;\n return (await startSession(ctx, signal, publishTimings))?.config;\n } catch (error) {\n if (!signal.aborted && owner === client) {\n try {\n client.validate();\n if (ctx.hasUI)\n ctx.ui.notify(`pi-sync recovery required: ${safeTerminalText(errorMessage(error))}`, \"error\");\n } catch {\n /* SDK context was replaced. */\n }\n }\n return false;\n }\n });\n try {\n const ready = await initialization;\n if (ready === false) releaseStatus();\n if (\n ready &&\n !signal.aborted &&\n owner === client &&\n !(ready.continuous && ready.agentMode) &&\n (ready.automatic || startupTransferEnabled(ready))\n )\n await withPiDaemonClient(ctx, async () => {\n check.start(ctx, signal, ready);\n });\n } catch (error) {\n releaseStatus();\n throw error;\n }\n });\n pi.on(\"agent_start\", async (_event, ctx) => {\n const client = owner;\n if (!client || ownerManager !== ctx.sessionManager || sessionAbort.signal.aborted) return;\n if (!ctx.hasUI || ![\"tui\", \"rpc\"].includes(ctx.mode)) await client.attachExisting();\n await client.setBusy(\"agent\", true);\n if (owner === client && !sessionAbort.signal.aborted) await check.interrupt(ctx);\n });\n pi.on(\"agent_settled\", async (_event, ctx) => {\n const client = owner;\n if (!client || ownerManager !== ctx.sessionManager || sessionAbort.signal.aborted) return;\n await client.setBusy(\"agent\", false);\n if (owner === client && !sessionAbort.signal.aborted)\n await withPiDaemonClient(ctx, async () => {\n check.settled(ctx);\n });\n });\n pi.on(\"model_select\", async (_event, ctx) => {\n if (owner && ownerManager === ctx.sessionManager && !sessionAbort.signal.aborted) await owner.update();\n });\n const pauseForReplacement = async (_event: unknown, ctx: ExtensionContext) => {\n const client = owner;\n if (!client || ownerManager !== ctx.sessionManager || sessionAbort.signal.aborted) return;\n const results = await Promise.allSettled([client.pauseForSessionChange(), check.stop()]);\n if (results.some((result) => result.status === \"rejected\")) {\n if (owner === client && !sessionAbort.signal.aborted)\n ctx.ui.notify(\n \"pi-sync could not drain its writer. Repair or stop the existing daemon before changing sessions.\",\n \"error\",\n );\n return { cancel: true };\n }\n // Another handler can still cancel the SDK transition. Stay paused until\n // /reload instead of guessing that it is safe to resume while handlers run.\n };\n pi.on(\"session_before_switch\", pauseForReplacement);\n pi.on(\"session_before_fork\", pauseForReplacement);\n pi.on(\"session_shutdown\", async (event, ctx) => {\n const releaseStatus = status.cleanupFor(ctx);\n const client = owner;\n if (!client || ownerManager !== ctx.sessionManager) {\n releaseStatus();\n return;\n }\n const controller = new AbortController();\n shutdownAbort?.abort(new DOMException(\"Session shut down again\", \"AbortError\"));\n shutdownAbort = controller;\n const signal = combineSignals(controller.signal, AbortSignal.timeout(30_000));\n const reason = typeof event === \"object\" && event ? (event as { reason?: string }).reason : undefined;\n const target =\n typeof event === \"object\" && event ? (event as { targetSessionFile?: string }).targetSessionFile : undefined;\n // Cancel old dialogs/settings work now, while the SDK context is still active.\n sessionAbort.abort(new DOMException(\"Session shutting down\", \"AbortError\"));\n let shutdownClient: PiDaemonClient | undefined;\n try {\n await initialization.catch(() => {});\n await check.stop();\n if (signal.aborted || owner !== client) return;\n if (reason !== \"reload\") {\n shutdownClient = bindPiDaemonClient(ctx, signal, publishTimings);\n await shutdownClient.setBusy(\"shutdown\", true);\n const attached = await shutdownClient.attachExisting();\n if (!signal.aborted && owner === client && attached)\n await withPiDaemonClient(ctx, () => autoPushSessions(ctx, signal, loaders));\n }\n } catch (error) {\n if (!signal.aborted && owner === client) {\n try {\n ctx.ui.notify(`pi-sync shutdown skipped: ${safeTerminalText(errorMessage(error))}`, \"warning\");\n } catch {\n /* SDK context was replaced. */\n }\n }\n } finally {\n if (owner === client) {\n owner = undefined;\n ownerManager = undefined;\n try {\n attention.reset(ctx);\n } catch {\n /* Cleanup never depends on an active SDK context. */\n }\n }\n try {\n await client.disposeForShutdown(reason, target);\n } finally {\n try {\n await shutdownClient?.disposeForShutdown(reason, target);\n } finally {\n controller.abort();\n releaseStatus();\n }\n }\n if (shutdownAbort === controller) shutdownAbort = undefined;\n }\n });\n}\nexport type { SyncDependencies } from \"./sync/sync-loaders.js\";\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;ACRP,SAAS,4BAA4B;;;ACArC,SAAS,4BAA4B;;;ACWrC,eAAsB,aACpB,KACA,QACA,SACiE;AACjE,iBAAe,MAAM;AACrB,QAAM,SAAS,eAAe,GAAG;AAGjC,MAAI,CAAC,IAAI,SAAS,CAAC,CAAC,OAAO,KAAK,EAAE,SAAS,IAAI,IAAI,GAAG;AACpD,UAAM,OAAO,eAAe;AAC5B,mBAAe,MAAM;AACrB,WAAO,EAAE,OAAO,MAAM;AAAA,EACxB;AACA,QAAM,UAAU,qBAAqB,OAAO;AAC5C,QAAM,WAAW,MAAM,QAAQ,QAAQ,iBAAiB,MAAM,OAAO,aAAa,CAAC;AACnF,iBAAe,MAAM;AACrB,sBAAoB,KAAM,UAAU,OAAO,cAAsC,IAAI;AACrF,QAAM,EAAE,8BAA8B,IAAI,MAAM,OAAO,sCAA6B;AACpF,QAAM,SAAS,8BAA8B;AAC7C,QAAM,EAAE,0BAA0B,IAAI,MAAM,OAAO,qDAA+C;AAClG,QAAM,kBAAkB,MAAM,0BAA0B,GAAG,KAAK,CAAC,UAAU,MAAM,YAAY,CAAC;AAC9F,iBAAe,MAAM;AACrB,MAAI,CAAE,MAAM,OAAO,WAAW,KAAM,CAAC,gBAAgB;AACnD,QAAI,OAAQ,KAAI,GAAG,OAAO,QAAQ,SAAS;AAC3C,4BAAwB,CAAC,CAAC;AAC1B,UAAM,QAAQ,UAAU,OAAO,UAAU;AACzC,UAAM,OAAO,UAAU,KAAK;AAC5B,YAAQ,QAAQ,KAAK,OAAO,QAAQ,wBAAwB,WAAW;AACv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ent": ["export type * from \"@narumitw/pi-sync-daemon/engine/sync/agent-policy\";\nexport {\n AGENT_INPUT_BYTES,\n AGENT_MAX_ATTEMPTS,\n AGENT_MAX_TOKENS,\n AGENT_MAX_UNITS,\n AGENT_OUTPUT_BYTES,\n AGENT_TIMEOUT_MS,\n startupTransferEnabled,\n} from \"@narumitw/pi-sync-daemon/engine/sync/agent-policy\";\n", "export type * from \"@narumitw/pi-sync-daemon/engine/settings/config-errors\";\nexport { isMissingConfigError } from \"@narumitw/pi-sync-daemon/engine/settings/config-errors\";\n", "export type * from \"@narumitw/pi-sync-daemon/engine/sync/startup-timings\";\nexport { createStartupTimings } from \"@narumitw/pi-sync-daemon/engine/sync/startup-timings\";\n", "import type { ExtensionContext } from \"@earendil-works/pi-coding-agent\";\nimport { setSyncSetupCompletions } from \"../commands/command.js\";\nimport { piDaemonClient } from \"../daemon/pi-client.js\";\nimport { isMissingConfigError } from \"../settings/config-errors.js\";\nimport type { AnySyncConfig, PiSyncSettingsV3 } from \"../settings/settings-types.js\";\nimport { configureSyncStatus } from \"../ui/sync-status.js\";\nimport { safeTerminalText } from \"../ui/terminal-text.js\";\nimport { throwIfAborted } from \"./signals.js\";\nimport { createStartupTimings, type StartupTimingPublisher } from \"./startup-timings.js\";\nimport { errorMessage } from \"./sync-errors.js\";\nimport type { SyncLoaders } from \"./sync-loaders.js\";\n\nexport async function startSession(\n ctx: ExtensionContext,\n signal: AbortSignal,\n publish?: StartupTimingPublisher,\n): Promise<{ debug: boolean; config?: AnySyncConfig } | undefined> {\n throwIfAborted(signal);\n const client = piDaemonClient(ctx);\n // One-off sessions only protect their files in an already existing service.\n // They never launch it or authorize observations, transfers, or model work.\n if (!ctx.hasUI || ![\"tui\", \"rpc\"].includes(ctx.mode)) {\n await client.attachExisting();\n throwIfAborted(signal);\n return { debug: false };\n }\n const timings = createStartupTimings(publish);\n const document = await timings.measure(\"settings read\", () => client.readSettings());\n throwIfAborted(signal);\n configureSyncStatus(ctx, (document?.parsed.showStatus as boolean | undefined) ?? true);\n const { stateDirectoryMigrationNotice } = await import(\"../state/state-directory.js\");\n const notice = stateDirectoryMigrationNotice();\n const { pendingTransactionEntries } = await import(\"../snapshot/snapshot-transaction-directory.js\");\n const recoveryNeeded = (await pendingTransactionEntries()).some((entry) => entry.isDirectory());\n throwIfAborted(signal);\n if (!(await client.configured()) && !recoveryNeeded) {\n if (notice) ctx.ui.notify(notice, \"warning\");\n setSyncSetupCompletions([]);\n const debug = document?.parsed.debug === true;\n await client.markReady(debug);\n timings.publish(ctx, debug, signal, \"local initialization\", \"completed\");\n return { debug };\n }\n throwIfAborted(signal);\n const result = (await client.run(\"initialize\", {}, signal)) as {\n debug: boolean;\n config?: AnySyncConfig;\n settings?: PiSyncSettingsV3;\n handoverRequired: boolean;\n };\n throwIfAborted(signal);\n configureSyncStatus(ctx, result.settings?.showStatus ?? true);\n setSyncSetupCompletions(Object.keys(result.settings?.syncSetups ?? {}).sort((a, b) => a.localeCompare(b)));\n await client.markReady(result.debug);\n throwIfAborted(signal);\n if (result.handoverRequired) {\n ctx.ui.notify(\n \"pi-sync: close or upgrade older Pi processes, then use /sync to review daemon handover. No automatic transfer is authorized yet.\",\n \"warning\",\n );\n return { debug: result.debug };\n }\n return { debug: result.debug, config: result.config };\n}\nexport async function autoPushSessions(ctx: ExtensionContext, signal: AbortSignal, _loaders: SyncLoaders) {\n try {\n const client = piDaemonClient(ctx);\n if (!(await client.configured())) return;\n throwIfAborted(signal);\n await client.run(\n \"shutdown\",\n { args: [], yes: true, force: false, stale: false, silent: true, reload: false },\n signal,\n );\n } catch (error) {\n if (signal.aborted || isMissingConfigError(error)) return;\n ctx.ui.notify(`pi-sync session push skipped: ${safeTerminalText(errorMessage(error))}`, \"warning\");\n }\n}\n", "import type { ExtensionContext } from \"@earendil-works/pi-coding-agent\";\nimport { loadConfigForCheck, syncCheckConfigFingerprint } from \"../settings/config.js\";\nimport { isMissingConfigError } from \"../settings/config-errors.js\";\nimport type { AnySyncConfig } from \"../settings/settings-types.js\";\nimport { snapshotOptionsForContext } from \"../snapshot/session-paths.js\";\nimport { withStateDirectoryAccess } from \"../state/state-directory.js\";\nimport { readStateForConfig, syncStateFingerprint } from \"../state/sync-state-store.js\";\nimport type { SyncAttentionController } from \"../ui/sync-attention.js\";\nimport { setSyncStatus } from \"../ui/sync-status.js\";\nimport { safeTerminalText } from \"../ui/terminal-text.js\";\nimport { startupTransferEnabled } from \"./agent-policy.js\";\nimport { combineSignals, throwIfAborted } from \"./signals.js\";\nimport { createStartupTimings, type StartupTimingPublisher } from \"./startup-timings.js\";\nimport { errorMessage } from \"./sync-errors.js\";\nimport type { SyncLoaders } from \"./sync-loaders.js\";\n\n/** One owned task per extension session, never keyed by the shared headless UI. */\nexport function createStartupCheck(\n loaders: SyncLoaders,\n attention: SyncAttentionController,\n timeoutMs = 30_000,\n publish?: StartupTimingPublisher,\n) {\n let active:\n | {\n controller: AbortController;\n promise: Promise<void>;\n owner: ExtensionContext[\"sessionManager\"];\n transfer: boolean;\n }\n | undefined;\n\n let pending: { ctx: ExtensionContext; signal: AbortSignal; config: AnySyncConfig } | undefined;\n\n const controllerApi = {\n async interrupt(ctx: ExtensionContext) {\n const task = active;\n if (!task?.transfer || task.owner !== ctx.sessionManager) return;\n task.controller.abort(new DOMException(\"Agent became busy\", \"AbortError\"));\n await task.promise;\n },\n settled(ctx: ExtensionContext) {\n const queued = pending;\n if (!queued || queued.ctx.sessionManager !== ctx.sessionManager || queued.signal.aborted || !ctx.isIdle()) return;\n pending = undefined;\n controllerApi.start(ctx, queued.signal, queued.config);\n },\n start(ctx: ExtensionContext, sessionSignal: AbortSignal, initialConfig?: AnySyncConfig) {\n if (!ctx.hasUI || sessionSignal.aborted) return;\n if (initialConfig && startupTransferEnabled(initialConfig) && !ctx.isIdle()) {\n pending = { ctx, signal: sessionSignal, config: initialConfig };\n return;\n }\n if (active) throw new Error(\"Previous startup check has not been drained.\");\n const timings = createStartupTimings(publish);\n const controller = new AbortController();\n const signal = combineSignals(sessionSignal, controller.signal);\n const task = {\n controller,\n owner: ctx.sessionManager,\n promise: Promise.resolve(),\n transfer: Boolean(initialConfig && startupTransferEnabled(initialConfig)),\n };\n active = task;\n const isCurrent = () => !sessionSignal.aborted && active === task && task.owner === ctx.sessionManager;\n const timer = setTimeout(\n () => controller.abort(new DOMException(\"Startup check timed out\", \"TimeoutError\")),\n timeoutMs,\n );\n timer.unref();\n let config: AnySyncConfig | undefined;\n let checking = false;\n let stopped = false;\n // Handle every detached rejection here; Pi's awaited event runner cannot catch it.\n task.promise = Promise.resolve()\n .then(async () => {\n try {\n throwIfAborted(signal);\n config = initialConfig ?? (await loadConfigForCheck());\n task.transfer = startupTransferEnabled(config);\n throwIfAborted(signal);\n if (!config.automatic && !startupTransferEnabled(config)) return;\n const captured = config;\n const identity = syncCheckConfigFingerprint(captured);\n checking = true;\n setSyncStatus(ctx, \"sync ...\", { activity: \"checking\" });\n const { inspectSync } = await timings.measure(\"inspection import\", () => loaders.inspection());\n throwIfAborted(signal);\n const currentConfig = await loadConfigForCheck();\n throwIfAborted(signal);\n if (syncCheckConfigFingerprint(currentConfig) !== identity) return;\n // The daemon owns the operation and cache guards.\n const inspection = await timings.measure(\"inspection and guards\", () =>\n inspectSync(captured, snapshotOptionsForContext(ctx, captured), signal, undefined, timings),\n );\n throwIfAborted(signal);\n const latest = await loadConfigForCheck();\n throwIfAborted(signal);\n if (syncCheckConfigFingerprint(latest) !== identity) return;\n const state = await withStateDirectoryAccess(() => readStateForConfig(latest));\n throwIfAborted(signal);\n if (syncStateFingerprint(state) !== inspection.stateIdentity || !isCurrent()) return;\n attention.observe({\n setupName: captured.setupName,\n configIdentity: identity,\n checkedAt: new Date().toISOString(),\n inspection,\n automaticTransfer: startupTransferEnabled(captured),\n });\n if (\n startupTransferEnabled(captured) &&\n !inspection.firstSync &&\n inspection.head &&\n inspection.selectionState?.kind === \"same\"\n ) {\n const operations = await timings.measure(\"operations import\", () => loaders.operations());\n throwIfAborted(signal);\n if (!isCurrent()) return;\n if (!ctx.isIdle()) {\n pending = { ctx, signal: sessionSignal, config: captured };\n return;\n }\n await timings.measure(\"automatic transfer\", () =>\n operations.syncBoth(ctx, {\n args: [],\n yes: true,\n force: false,\n stale: false,\n silent: true,\n reload: false,\n auto: true,\n signal,\n startupTimings: timings,\n onCommit: () => attention.clearObservation(),\n }),\n );\n throwIfAborted(signal);\n if (!isCurrent()) return;\n attention.clearObservation();\n return;\n }\n attention.observe({\n setupName: captured.setupName,\n configIdentity: identity,\n checkedAt: new Date().toISOString(),\n inspection,\n automaticTransfer: startupTransferEnabled(captured),\n });\n if (ctx.mode === \"rpc\") attention.notifyObservation(ctx);\n } catch (error) {\n stopped = true;\n if (!isCurrent() || sessionSignal.aborted || isMissingConfigError(error)) return;\n if (signal.aborted && controller.signal.reason?.name !== \"TimeoutError\") return;\n // A settings edit invalidates failures as well as successful observations.\n if (config) {\n const latest = await loadConfigForCheck().catch(() => undefined);\n if (!isCurrent() || (signal.aborted && controller.signal.reason?.name !== \"TimeoutError\")) return;\n if (!latest || syncCheckConfigFingerprint(latest) !== syncCheckConfigFingerprint(config)) return;\n }\n ctx.ui.notify(\n config && startupTransferEnabled(config)\n ? `pi-sync automatic transfer stopped: ${safeTerminalText(errorMessage(error))}. Run /sync to review or reconcile retained recovery evidence. No resources were reloaded.`\n : `pi-sync startup check skipped: ${safeTerminalText(errorMessage(error))}. Run /sync status to retry. No startup transfer was performed.`,\n \"warning\",\n );\n } finally {\n clearTimeout(timer);\n if (isCurrent() && checking) {\n if (!signal.aborted || controller.signal.reason?.name === \"TimeoutError\") {\n const latest = await loadConfigForCheck().catch(() => undefined);\n if (isCurrent()) {\n if (signal.aborted && controller.signal.reason?.name !== \"TimeoutError\")\n setSyncStatus(ctx, undefined);\n else if (\n config &&\n latest &&\n syncCheckConfigFingerprint(latest) === syncCheckConfigFingerprint(config)\n )\n await attention.publish(ctx, sessionSignal);\n else attention.reset(ctx);\n }\n } else setSyncStatus(ctx, undefined);\n }\n if (isCurrent()) {\n timings.publish(\n ctx,\n config?.debug ?? false,\n sessionSignal,\n \"background startup\",\n signal.aborted || stopped ? \"stopped\" : \"completed\",\n );\n }\n if (active === task) active = undefined;\n }\n })\n .catch(() => {\n // UI teardown can itself throw. No unhandled rejection or retained timer.\n clearTimeout(timer);\n if (active === task) active = undefined;\n });\n },\n async stop() {\n pending = undefined;\n const task = active;\n if (!task) return;\n task.controller.abort(new DOMException(\"Startup check cancelled\", \"AbortError\"));\n // Drain the actual work, including child/ref cleanup, before foreground guards.\n await task.promise;\n },\n };\n return controllerApi;\n}\n", "type SetupSwitchModule = Pick<typeof import(\"./setup-switch.js\"), \"useSyncSetup\">;\ntype SnapshotModule = Pick<typeof import(\"../snapshot/snapshot.js\"), \"createSnapshot\">;\ntype SyncStateModule = Pick<typeof import(\"./sync-state.js\"), \"hasLocalChanges\">;\ntype SyncOperations = typeof import(\"./sync-operations.js\");\ntype CommandHandlerModule = Pick<typeof import(\"../commands/command-handler.js\"), \"handleCommand\">;\n\ntype SyncInspectionModule = Pick<typeof import(\"./sync-inspection.js\"), \"inspectSync\">;\n\nexport interface SyncDependencies {\n loadCommandHandler(): Promise<CommandHandlerModule>;\n loadSyncInspection(): Promise<SyncInspectionModule>;\n loadSetupSwitch(): Promise<SetupSwitchModule>;\n loadSnapshot(): Promise<SnapshotModule>;\n loadSyncState(): Promise<SyncStateModule>;\n loadSyncOperations(): Promise<SyncOperations>;\n}\n\nexport interface SyncLoaders {\n commands(): Promise<CommandHandlerModule>;\n inspection(): Promise<SyncInspectionModule>;\n setupSwitch(): Promise<SetupSwitchModule>;\n snapshot(): Promise<SnapshotModule>;\n syncState(): Promise<SyncStateModule>;\n operations(): Promise<SyncOperations>;\n}\n\nexport function createSyncLoaders(dependencies: Partial<SyncDependencies>): SyncLoaders {\n const loaders: SyncLoaders = {\n commands: cachedModuleLoader(dependencies.loadCommandHandler ?? (() => import(\"../commands/command-handler.js\"))),\n inspection: cachedModuleLoader(dependencies.loadSyncInspection ?? (() => import(\"./sync-inspection.js\"))),\n setupSwitch: cachedModuleLoader(dependencies.loadSetupSwitch ?? (() => import(\"./setup-switch.js\"))),\n snapshot: cachedModuleLoader(dependencies.loadSnapshot ?? (() => import(\"../snapshot/snapshot.js\"))),\n syncState: cachedModuleLoader(dependencies.loadSyncState ?? (() => import(\"./sync-state.js\"))),\n operations: cachedModuleLoader(dependencies.loadSyncOperations ?? (() => import(\"./sync-operations.js\"))),\n };\n return loaders;\n}\n\nfunction cachedModuleLoader<Module>(load: () => Promise<Module>): () => Promise<Module> {\n let pending: Promise<Module> | undefined;\n return () => {\n if (!pending) {\n pending = load().catch((error) => {\n pending = undefined;\n throw error;\n });\n }\n return pending;\n };\n}\n", "import type { ExtensionAPI } from \"@earendil-works/pi-coding-agent\";\nimport { Text, truncateToWidth } from \"@earendil-works/pi-tui\";\nimport type { StartupTimingPublisher } from \"../sync/startup-timings.js\";\nimport { safeTerminalText } from \"./terminal-text.js\";\n\nexport const STARTUP_TIMING_ENTRY = \"pi-sync-startup-timings\";\n\nexport interface StartupTimingEntry {\n version: 1;\n report: string;\n}\n\nexport function registerStartupTimings(pi: ExtensionAPI): StartupTimingPublisher {\n pi.registerEntryRenderer<StartupTimingEntry>(STARTUP_TIMING_ENTRY, (entry, _options, theme) => {\n const data = entry.data;\n if (data?.version !== 1 || typeof data.report !== \"string\") return undefined;\n const text = new Text(\n data.report\n .split(\"\\n\")\n .map((line, index) => theme.fg(index === 0 ? \"accent\" : \"muted\", safeTerminalText(line)))\n .join(\"\\n\"),\n 0,\n 0,\n );\n return {\n render: (width) => (width > 0 ? text.render(width).map((line) => truncateToWidth(line, width)) : []),\n invalidate: () => text.invalidate(),\n };\n });\n return (ctx, report) => {\n // Pi coalesces consecutive info notifications, including the final /reload notice.\n // Custom entries remain visible without adding messages to model context.\n if (ctx.mode === \"tui\") pi.appendEntry<StartupTimingEntry>(STARTUP_TIMING_ENTRY, { version: 1, report });\n else ctx.ui.notify(report, \"info\");\n };\n}\n", "import type { ExtensionAPI, ExtensionContext } from \"@earendil-works/pi-coding-agent\";\nimport { completeSyncArguments, splitArgs } from \"./commands/command.js\";\nimport {\n bindPiDaemonClient,\n installPiDaemonHost,\n type PiDaemonClient,\n withPiDaemonClient,\n} from \"./daemon/pi-client.js\";\nimport type { AnySyncConfig } from \"./settings/settings-types.js\";\nimport { startupTransferEnabled } from \"./sync/agent-policy.js\";\nimport { autoPushSessions, startSession } from \"./sync/automatic-sync.js\";\nimport { combineSignals } from \"./sync/signals.js\";\nimport { createStartupCheck } from \"./sync/startup-check.js\";\nimport { errorMessage } from \"./sync/sync-errors.js\";\nimport { createSyncLoaders, type SyncDependencies } from \"./sync/sync-loaders.js\";\nimport { registerStartupTimings } from \"./ui/startup-timings-entry.js\";\nimport { createSyncAttentionController } from \"./ui/sync-attention.js\";\nimport { createSyncStatusPublisher } from \"./ui/sync-status.js\";\nimport { safeTerminalText } from \"./ui/terminal-text.js\";\n\nexport default function sync(pi: ExtensionAPI, dependencies: Partial<SyncDependencies> = {}) {\n installPiDaemonHost();\n const loaders = createSyncLoaders(dependencies);\n const attention = createSyncAttentionController();\n const status = createSyncStatusPublisher(pi.events);\n const publishTimings = registerStartupTimings(pi);\n const check = createStartupCheck(loaders, attention, 30_000, publishTimings);\n let sessionAbort = new AbortController();\n let shutdownAbort: AbortController | undefined;\n let initialization = Promise.resolve<AnySyncConfig | false | undefined>(undefined);\n let owner: PiDaemonClient | undefined;\n let ownerManager: ExtensionContext[\"sessionManager\"] | undefined;\n\n pi.registerCommand(\"sync\", {\n description: \"Sync Pi settings through Git, WebDAV, R2, or S3-compatible storage\",\n getArgumentCompletions: completeSyncArguments,\n handler: async (args, ctx) => {\n if (!ctx.hasUI) throw new Error(\"/sync requires TUI or RPC mode so results and safety prompts are observable.\");\n status.bind(ctx);\n const signal = sessionAbort.signal;\n const client = owner;\n if (!client || ownerManager !== ctx.sessionManager) {\n if (splitArgs(args)[0] !== \"help\") throw new Error(\"pi-sync session is not ready.\");\n const commands = await loaders.commands();\n if (signal.aborted || owner) return;\n ctx.isIdle();\n await commands.handleCommand(args, ctx, signal, loaders, attention);\n return;\n }\n const reload = new AbortController();\n const commandSignal = combineSignals(signal, reload.signal);\n try {\n await withPiDaemonClient(\n ctx,\n async (ctx) => {\n const command = splitArgs(args)[0];\n const ready = await initialization;\n if (signal.aborted || owner !== client) return;\n const requiresContact = ![\"help\", \"unlock\", \"migrate-state\"].includes(command ?? \"\");\n let busyPublished = false;\n try {\n await client.setBusy(\"command\", true, requiresContact);\n busyPublished = requiresContact;\n if (signal.aborted || owner !== client) return;\n await check.stop();\n if (signal.aborted || owner !== client) return;\n if (\n ready === false &&\n command !== \"help\" &&\n command !== \"unlock\" &&\n command !== \"migrate-state\" &&\n command !== \"daemon\"\n ) {\n ctx.ui.notify(\n \"pi-sync recovery required. Repair the startup error, then /reload before syncing. Use /sync help for recovery guidance.\",\n \"error\",\n );\n return;\n }\n if (command === \"unlock\" || command === \"migrate-state\") {\n const { stateDirectoryMigrationNotice } = await import(\"./state/state-directory.js\");\n if (signal.aborted || owner !== client) return;\n // Recovery cannot guess an authoritative root when roots coexist or are unsafe.\n stateDirectoryMigrationNotice();\n }\n const commands = await loaders.commands();\n if (signal.aborted || owner !== client) return;\n await commands.handleCommand(args, ctx, commandSignal, loaders, attention);\n } catch (error) {\n if (!commandSignal.aborted && owner === client) {\n ctx.ui.notify(`pi-sync command unavailable: ${safeTerminalText(errorMessage(error))}`, \"error\");\n if (command === \"unlock\" || command === \"migrate-state\") throw error;\n }\n } finally {\n if (!signal.aborted && owner === client) {\n // Recovery can publish busy facts after bypassing the initial contact check.\n const publish = busyPublished || command === \"unlock\" || command === \"migrate-state\";\n // Release local busy state even if contact failed; do not mask the command result.\n await client.setBusy(\"command\", false, publish).catch(() => {});\n }\n }\n },\n reload,\n );\n // Pi reload awaits our shutdown hook. Neither daemon work nor old UI may await reload.\n if (!signal.aborted && owner === client && client.canReload(reload)) await ctx.reload();\n } finally {\n client.releaseReload(reload);\n reload.abort();\n }\n },\n });\n pi.on(\"session_start\", async (_event, ctx) => {\n const releaseStatus = status.start(ctx);\n const previousClient = owner;\n shutdownAbort?.abort(new DOMException(\"Session replaced\", \"AbortError\"));\n shutdownAbort = undefined;\n sessionAbort.abort(new DOMException(\"Session replaced\", \"AbortError\"));\n sessionAbort = new AbortController();\n const signal = sessionAbort.signal;\n const client = bindPiDaemonClient(ctx, signal, publishTimings);\n owner = client;\n ownerManager = ctx.sessionManager;\n const replacementFile = ctx.sessionManager.getSessionFile?.();\n attention.reset(ctx);\n const previous = initialization;\n initialization = withPiDaemonClient(ctx, async () => {\n await previous.catch(() => {});\n if (signal.aborted || owner !== client) return false;\n try {\n await check.stop();\n if (previousClient) {\n // Protect the replacement session before removing old session protection.\n try {\n await client.attachExisting({ allowUpgrade: true });\n } catch {\n /* Initialization below reports an unavailable owner. */\n }\n try {\n await previousClient.disposeForShutdown(\"resume\", replacementFile);\n } catch {\n /* Plain, detached recovery owns uncertain grants; no closed ctx is retained. */\n }\n await client.finishReattachment();\n }\n if (signal.aborted || owner !== client) return false;\n return (await startSession(ctx, signal, publishTimings))?.config;\n } catch (error) {\n if (!signal.aborted && owner === client) {\n try {\n client.validate();\n if (ctx.hasUI)\n ctx.ui.notify(`pi-sync recovery required: ${safeTerminalText(errorMessage(error))}`, \"error\");\n } catch {\n /* SDK context was replaced. */\n }\n }\n return false;\n }\n });\n try {\n const ready = await initialization;\n if (ready === false) releaseStatus();\n if (\n ready &&\n !signal.aborted &&\n owner === client &&\n !(ready.continuous && ready.agentMode) &&\n (ready.automatic || startupTransferEnabled(ready))\n )\n await withPiDaemonClient(ctx, async () => {\n check.start(ctx, signal, ready);\n });\n } catch (error) {\n releaseStatus();\n throw error;\n }\n });\n pi.on(\"agent_start\", async (_event, ctx) => {\n const client = owner;\n if (!client || ownerManager !== ctx.sessionManager || sessionAbort.signal.aborted) return;\n if (!ctx.hasUI || ![\"tui\", \"rpc\"].includes(ctx.mode)) await client.attachExisting();\n await client.setBusy(\"agent\", true);\n if (owner === client && !sessionAbort.signal.aborted) await check.interrupt(ctx);\n });\n pi.on(\"agent_settled\", async (_event, ctx) => {\n const client = owner;\n if (!client || ownerManager !== ctx.sessionManager || sessionAbort.signal.aborted) return;\n await client.setBusy(\"agent\", false);\n if (owner === client && !sessionAbort.signal.aborted)\n await withPiDaemonClient(ctx, async () => {\n check.settled(ctx);\n });\n });\n pi.on(\"model_select\", async (_event, ctx) => {\n if (owner && ownerManager === ctx.sessionManager && !sessionAbort.signal.aborted) await owner.update();\n });\n const pauseForReplacement = async (_event: unknown, ctx: ExtensionContext) => {\n const client = owner;\n if (!client || ownerManager !== ctx.sessionManager || sessionAbort.signal.aborted) return;\n const results = await Promise.allSettled([client.pauseForSessionChange(), check.stop()]);\n if (results.some((result) => result.status === \"rejected\")) {\n if (owner === client && !sessionAbort.signal.aborted)\n ctx.ui.notify(\n \"pi-sync could not drain its writer. Repair or stop the existing daemon before changing sessions.\",\n \"error\",\n );\n return { cancel: true };\n }\n // Another handler can still cancel the SDK transition. Stay paused until\n // /reload instead of guessing that it is safe to resume while handlers run.\n };\n pi.on(\"session_before_switch\", pauseForReplacement);\n pi.on(\"session_before_fork\", pauseForReplacement);\n pi.on(\"session_shutdown\", async (event, ctx) => {\n const releaseStatus = status.cleanupFor(ctx);\n const client = owner;\n if (!client || ownerManager !== ctx.sessionManager) {\n releaseStatus();\n return;\n }\n const controller = new AbortController();\n shutdownAbort?.abort(new DOMException(\"Session shut down again\", \"AbortError\"));\n shutdownAbort = controller;\n const signal = combineSignals(controller.signal, AbortSignal.timeout(30_000));\n const reason = typeof event === \"object\" && event ? (event as { reason?: string }).reason : undefined;\n const target =\n typeof event === \"object\" && event ? (event as { targetSessionFile?: string }).targetSessionFile : undefined;\n // Cancel old dialogs/settings work now, while the SDK context is still active.\n sessionAbort.abort(new DOMException(\"Session shutting down\", \"AbortError\"));\n let shutdownClient: PiDaemonClient | undefined;\n try {\n await initialization.catch(() => {});\n await check.stop();\n if (signal.aborted || owner !== client) return;\n if (reason !== \"reload\") {\n shutdownClient = bindPiDaemonClient(ctx, signal, publishTimings);\n await shutdownClient.setBusy(\"shutdown\", true);\n const attached = await shutdownClient.attachExisting();\n if (!signal.aborted && owner === client && attached)\n await withPiDaemonClient(ctx, () => autoPushSessions(ctx, signal, loaders));\n }\n } catch (error) {\n if (!signal.aborted && owner === client) {\n try {\n ctx.ui.notify(`pi-sync shutdown skipped: ${safeTerminalText(errorMessage(error))}`, \"warning\");\n } catch {\n /* SDK context was replaced. */\n }\n }\n } finally {\n if (owner === client) {\n owner = undefined;\n ownerManager = undefined;\n try {\n attention.reset(ctx);\n } catch {\n /* Cleanup never depends on an active SDK context. */\n }\n }\n try {\n await client.disposeForShutdown(reason, target);\n } finally {\n try {\n await shutdownClient?.disposeForShutdown(reason, target);\n } finally {\n controller.abort();\n releaseStatus();\n }\n }\n if (shutdownAbort === controller) shutdownAbort = undefined;\n }\n });\n}\nexport type { SyncDependencies } from \"./sync/sync-loaders.js\";\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;ACRP,SAAS,4BAA4B;;;ACArC,SAAS,4BAA4B;;;ACWrC,eAAsB,aACpB,KACA,QACA,SACiE;AACjE,iBAAe,MAAM;AACrB,QAAM,SAAS,eAAe,GAAG;AAGjC,MAAI,CAAC,IAAI,SAAS,CAAC,CAAC,OAAO,KAAK,EAAE,SAAS,IAAI,IAAI,GAAG;AACpD,UAAM,OAAO,eAAe;AAC5B,mBAAe,MAAM;AACrB,WAAO,EAAE,OAAO,MAAM;AAAA,EACxB;AACA,QAAM,UAAU,qBAAqB,OAAO;AAC5C,QAAM,WAAW,MAAM,QAAQ,QAAQ,iBAAiB,MAAM,OAAO,aAAa,CAAC;AACnF,iBAAe,M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SAAS;AAC5F,UAAM,SACJ,OAAO,UAAU,YAAY,QAAS,MAAyC,oBAAoB;AAErG,iBAAa,MAAM,IAAI,aAAa,yBAAyB,YAAY,CAAC;AAC1E,QAAI;AACJ,QAAI;AACF,YAAM,eAAe,MAAM,MAAM;AAAA,MAAC,CAAC;AACnC,YAAM,MAAM,KAAK;AACjB,UAAI,OAAO,WAAW,UAAU,OAAQ;AACxC,UAAI,WAAW,UAAU;AACvB,yBAAiB,mBAAmB,KAAK,QAAQ,cAAc;AAC/D,cAAM,eAAe,QAAQ,YAAY,IAAI;AAC7C,cAAM,WAAW,MAAM,eAAe,eAAe;AACrD,YAAI,CAAC,OAAO,WAAW,UAAU,UAAU;AACzC,gBAAM,mBAAmB,KAAK,MAAM,iBAAiB,KAAK,QAAQ,OAAO,CAAC;AAAA,MAC9E;AAAA,IACF,SAAS,OAAO;AACd,UAAI,CAAC,OAAO,WAAW,UAAU,QAAQ;AACvC,YAAI;AACF,cAAI,GAAG,OAAO,6BAA6B,iBAAiB,aAAa,KAAK,CAAC,CAAC,IAAI,SAAS;AAAA,QAC/F,QAAQ;AAAA,QAER;AAAA,MACF;AAAA,IACF,UAAE;AACA,UAAI,UAAU,QAAQ;AACpB,gBAAQ;AACR,uBAAe;AACf,YAAI;AACF,oBAAU,MAAM,GAAG;AAAA,QACrB,QAAQ;AAAA,QAER;AAAA,MACF;AACA,UAAI;AACF,cAAM,OAAO,mBAAmB,QAAQ,MAAM;AAAA,MAChD,UAAE;AACA,YAAI;AACF,gBAAM,gBAAgB,mBAAmB,QAAQ,MAAM;AAAA,QACzD,UAAE;AACA,qBAAW,MAAM;AACjB,wBAAc;AAAA,QAChB;AAAA,MACF;AACA,UAAI,kBAAkB,WAAY,iBAAgB;AAAA,IACpD;AAAA,EACF,CAAC;AACH;",
6
+ "names": ["ctx"]
7
7
  }
@@ -1,6 +1,6 @@
1
1
  # Autonomous sync implementation verification
2
2
 
3
- This record describes the original implementation and its verification scope. The [settings reference](settings.md#autonomous-sync) is authoritative for current user behavior, limits, privacy, and recovery.
3
+ This record describes the original implementation and its verification scope. The [settings reference](../skills/configure-pi-sync/references/configuration.md#autonomous-sync) is authoritative for current user behavior, limits, privacy, and recovery.
4
4
 
5
5
  Later recovery, cancellation, confirmed-refusal retry, and diagnostics changes are documented in [Autonomous and Continuous sync recovery boundaries](agent-continuous-hardening.md). The [synthetic quality corpus](agent-quality-verification.md) adds structural tests without claiming measured model accuracy. Historical verification below retains the former **Agent mode** name and the maturity labels used at that time; recorded results are unchanged.
6
6
 
@@ -1,6 +1,6 @@
1
1
  # Synthetic Autonomous sync merge-quality verification
2
2
 
3
- The [corpus](../test/agent-quality-corpus.ts) and [tests](../test/agent-quality.test.ts) check structural merge safety with synthetic data and fixed resolver responses. They do not measure real-model semantic accuracy. Autonomous sync is default-off; the [settings reference](settings.md#autonomous-sync) and [implementation verification](agent-mode-verification.md) retain their authority.
3
+ The [corpus](../test/agent-quality-corpus.ts) and [tests](../test/agent-quality.test.ts) check structural merge safety with synthetic data and fixed resolver responses. They do not measure real-model semantic accuracy. Autonomous sync is default-off; the [settings reference](../skills/configure-pi-sync/references/configuration.md#autonomous-sync) and [implementation verification](agent-mode-verification.md) retain their authority.
4
4
 
5
5
  ## Deterministic evidence
6
6
 
@@ -1,6 +1,6 @@
1
1
  # Continuous sync verification
2
2
 
3
- This record describes implementation evidence and test scope. The [settings reference](settings.md#continuous-sync) owns current user-facing behavior, limits and recovery.
3
+ This record describes implementation evidence and test scope. The [settings reference](../skills/configure-pi-sync/references/configuration.md#continuous-sync) owns current user-facing behavior, limits and recovery.
4
4
 
5
5
  Later recovery classification, deadline propagation, confirmed-refusal retry, and read-only allowance/capacity diagnostics are documented in [Autonomous and Continuous sync recovery boundaries](agent-continuous-hardening.md). Historical verification below retains the former **Agent mode** name for Autonomous sync and the maturity labels used at that time; recorded results are unchanged.
6
6
 
@@ -4,9 +4,54 @@ This daemon extraction is experimental. Deterministic Linux verification passed,
4
4
 
5
5
  ## Ownership and upgrade
6
6
 
7
- The non-extension npm package is `@narumitw/pi-sync-daemon`; its executable is `pi-sync-daemon`. These replace `@narumitw/sync-daemon` and `sync-daemon`; the new package does not provide the old executable alias. Stop an existing installation with `sync-daemon stop --root <agent-directory>` before replacing it, then use `pi-sync-daemon` after installation. The rename changes package identity, imports, the package directory, and executable names, not IPC names, authorization digests, or settings/state formats. The existing Pi extension remains `@narumitw/pi-sync`, with `/sync` as its user interface. Pi starts or connects to one detached service per canonical agent directory; the daemon, not an individual Pi shutdown hook, decides when the shared owner can exit. No OS service or supervisor is installed.
8
-
9
- Stop the service before updating its package or rebuilding a local checkout: a surviving Node process can otherwise combine cached code with newly loaded modules from the replaced directory. A compatible protocol handshake does not upgrade the running implementation; restart explicitly after installation.
7
+ The non-extension npm package is `@narumitw/pi-sync-daemon`; its executable is `pi-sync-daemon`. These replace `@narumitw/sync-daemon` and `sync-daemon`; the new package does not provide the old executable alias. The rename changes the package and executable names, not the IPC names, authorization digests, or
8
+ settings and state formats. The Pi extension remains `@narumitw/pi-sync`. Pi uses one detached service
9
+ per canonical agent directory. It does not install an OS service.
10
+
11
+ After an update, use `/reload` in open Pi sessions. On the next active connection, the new client
12
+ checks the owner's build over compatible, authenticated IPC. For an older or unversioned owner, the
13
+ client checks that no retained unattended permission blocks the upgrade. It then requests a stop
14
+ and starts the replacement only after the owner releases its identity and exits. If any check fails,
15
+ follow manual recovery. The upgrade does not run a transfer, replay an operation, or change sync
16
+ settings. Passive print, JSON, and shutdown paths do not replace an older owner. If an upgrade fails
17
+ while switching sessions, Pi Sync reports the failure and tries to attach the new session to the
18
+ same owner for file protection only. That attachment cannot submit sync work. Use `/reload`
19
+ after recovery.
20
+
21
+ Manual recovery:
22
+
23
+ 1. Revoke all retained unattended grants before updating. `/sync daemon revoke-after-exit` applies
24
+ only to the active setup. For each setup with a retained grant, make it active, run the command,
25
+ and confirm revocation. If the upgraded client blocks on consent before creating a pending
26
+ upgrade record, use an already available compatible Pi client to revoke each grant from the
27
+ still-running owner.
28
+ Without a pending record, `repair-upgrade` returns `repaired: false` and does not revoke permission.
29
+ If no compatible client is available or revocation fails, stop here and preserve the consent,
30
+ identity, and recovery files.
31
+ 2. Run `pi-sync-daemon status --root <agent-directory>`.
32
+ - A verified `pid` identifies the owner that answered the handshake. Record it before stopping
33
+ that owner. Check `pendingUpgradePid` for any pending owner, even if `running` is `false` or `null`.
34
+ - `running: null` means the handshake failed, even if there is no pending upgrade. `recordedPid`
35
+ comes from the validated identity file and is only a lead. Unknown status does not prove exit
36
+ or compatibility. Use diagnostics from an already available compatible version to identify the
37
+ owner. If you cannot identify it, stop here and preserve the records.
38
+
39
+ To stop an identified, running owner, use `pi-sync-daemon stop --root <agent-directory>` if
40
+ compatible. This works even if the old executable was removed. If the old executable is still
41
+ installed and compatible, you can use `sync-daemon stop --root <agent-directory>` instead.
42
+ 3. Check the recorded PID in the operating system. On macOS or Linux, use `ps -p <pid> -o pid,args`.
43
+ On Windows, look up the PID in Task Manager's **Details** tab. A successful `stop` confirms
44
+ identity release, not process exit. Wait for the old process to exit. If exit is uncertain, do
45
+ not force a second owner or delete recovery files.
46
+ 4. If a pending upgrade still blocks restart after exit, close other Pi sessions for that root.
47
+ Run `pi-sync-daemon repair-upgrade --root <agent-directory>`. It verifies exit, revokes all
48
+ retained after-exit grants for that root, and moves the upgrade record and any stale identity
49
+ to the private archive path it reports. It does not start a daemon or transfer data. If repair
50
+ fails, keep the records. Do not edit or delete them to force startup.
51
+ 5. Use `/reload`, then `/sync daemon status`. Review after-exit permission again if you need it.
52
+
53
+ Stop the service before rebuilding a local checkout in place. A source rebuild without a package
54
+ version change does not trigger automatic replacement.
10
55
 
11
56
  Before the first daemon-owned transfer, close or upgrade every older Pi process and review `/sync daemon handover`. The existing operation lock excludes observed transfers, but an idle older client cannot be detected from an absent lock. Older binaries cannot be made to honor a new handover record retroactively. Do not run an old and new engine as interchangeable writers.
12
57
 
@@ -28,20 +73,36 @@ The service owns synchronization scheduling and execution, not every writer on t
28
73
 
29
74
  Protect the union of all registered live-PID sessions, including ambiguously disconnected and orderly retired clients. Retired clients cannot authorize work or hold back zero-client scheduling, but their protection survives another attach and daemon restart until confirmed PID exit. A contact timeout revokes work; it is not permission to overwrite that session or release an acquired mutation grant. An uncertain grant remains quarantined until explicit release or confirmed daemon exit. Unregistered editors, shell commands, older clients, and extensions remain independent writers; preimages, conditional publication, backups, and journal recovery are still required.
30
75
 
76
+ When a running daemon expires a Pi client's heartbeat (for example, during
77
+ computer sleep), the TUI or RPC client tries to reconnect to that same daemon
78
+ without reloading Pi. The next `/sync` command also checks contact before
79
+ submitting work. `/sync daemon status` reports `connected` only after the daemon
80
+ accepts the current participant's facts. An older daemon can stay reachable
81
+ without supporting this repair; a healthy CLI status alone does not confirm Pi
82
+ participation.
83
+
84
+ Reconnect does not replay a submitted operation or restart startup transfers.
85
+ If a write or file-queue release cannot be confirmed, preserve the journals and
86
+ use the existing recovery path before retrying a transfer. Reconnect does not
87
+ stop or restart the service, and it does not extend transfer or model permission.
88
+
31
89
  ## Diagnostics and rollback
32
90
 
33
91
  If saving consent fails, that service instance blocks automatic work. Uncertain consent publication, failed revocation, or cleanup failure keeps the owner paused and retains evidence; automatic exit or implicit restart must not clear the barrier and restore an older persisted grant. Preserve the retained file, repair persistence, and revoke permission through the existing repair/revocation path before an explicit restart; a failed save does not prove the previous grant changed. Cleanup failure is not a successful exit.
34
92
 
35
- Use `pi-sync-daemon status --root <agent-directory>` without starting a missing service. `stop` drains compatible work. `restart` must not replace an incompatible, unavailable live, or uncertain owner silently. The Pi client must report failure rather than fall back to in-process transfers.
93
+ Use `pi-sync-daemon status --root <agent-directory>` without starting a missing service. `stop` drains compatible work. `restart` must not replace an incompatible, unavailable live, or uncertain owner silently. The Pi client must report failure rather than fall back to in-process transfers. If the initial consent check blocked the update before a pending record was created, follow step 1 of [manual recovery](#ownership-and-upgrade); `repair-upgrade` cannot help in that case.
36
94
 
37
- CLI `status` includes an owner-private, bounded lifecycle-log path. Only timestamps and lifecycle phases are retained; no request content, credentials, model output, or exception text is logged. This log is not transaction recovery evidence.
95
+ A successful CLI `status` handshake reports an owner-private, bounded lifecycle-log path. Only timestamps and lifecycle phases are retained; no request content, credentials, model output, or exception text is logged. This log is not transaction recovery evidence.
38
96
 
39
97
  Before rollback:
40
98
 
41
99
  1. Stop the daemon explicitly and verify owner exit.
42
100
  2. Close all upgraded clients and retain settings, state, journals, and backups.
43
101
  3. Reconcile pending or uncertain publication through the supported engine recovery path.
44
- 4. Only then consider a compatible code/package rollback; do not blindly restore old local or remote bytes.
102
+ 4. Check consent compatibility before rolling back. A repair can leave `daemon.json` larger than
103
+ 65,536 bytes because it keeps all other fields when revoking grants. Builds with the old
104
+ 65,536-byte limit cannot read that file. Preserve it and use a build that supports the larger
105
+ file. Do not delete it or restore an older copy to make the rollback work.
45
106
 
46
107
  Operation retries are instance-bound and deduplicated. An expired result or old instance requires journal reconciliation, not blind replay. A full bounded result ledger requires an explicit drained restart.
47
108
 
@@ -66,6 +127,20 @@ The semantic audit used `docs/extension-conventions.md`, `docs/extension-setting
66
127
 
67
128
  Intentional compatibility limits are explicit: there is no legacy in-process fallback; unsupported parent-only providers remain unavailable; print/JSON do not launch a service but protect sessions in an existing one; a cancelled SDK switch/fork stays paused until reload; arbitrary external writers are not covered by a universal filesystem compare-and-swap. Normal closed clients retain live-PID protection without blocking reviewed zero-client work. No package publication, tag, release dispatch, paid provider request, or production-storage action was performed.
68
129
 
130
+ ### Heartbeat recovery verification
131
+
132
+ An isolated daemon clock and real Pi RPC clients reproduced the stuck first
133
+ command before the fix. Regression tests now verify same-owner, same-session
134
+ recovery with and without a command, and no replay or remote write after an
135
+ interrupted loopback WebDAV push. Daemon tests exercise admission, lifecycle
136
+ cancellation, legacy replies, committed work, and uncertain queue release.
137
+ The Jiti tests load the built extension and exercise its lazy command path.
138
+
139
+ Physical suspend and wake timing on target devices remains unverified. See
140
+ [External handoff](#external-handoff) before making a platform claim or
141
+ preparing a release. This change neither publishes a package nor authorizes
142
+ production cutover.
143
+
69
144
  ## Measured process cost
70
145
 
71
146
  These are same-host observations on Linux with Node `v26.11.1`, not limits or statistically controlled performance claims. The baseline was reconstructed from archived commit `a01c1d75` after implementation, rather than measured before editing. Both Pi cases loaded generated Jiti entries through real offline RPC processes with the same installed parent SDK and synthetic loopback WebDAV/model endpoints. No production stores, credentials, or paid model calls were used.
@@ -92,6 +167,7 @@ The archived previous engine also held its real operation lock in a separate pro
92
167
  | Responsible role | Prerequisite and action | Expected result | Unverified behavior and restriction |
93
168
  | --- | --- | --- | --- |
94
169
  | npm/release account owner | Passing package gates and explicit approval; verify publication rights for `@narumitw/pi-sync-daemon` and dependency-first publication | The daemon resolves before the dependent Pi client is released | Scope permissions and first publication are not verified; no publication, visibility change, tags, or workflow dispatch without approval |
170
+ | Device operator | Verified builds and an isolated setup; suspend and wake the target device, then run `/sync daemon status` and `/sync status` in the same Pi session | Both commands work without reload; the daemon and session stay the same | Physical wake timing is not verified by clock-controlled tests; do not claim tested platforms without this check |
95
171
  | Deployment operator | Verified cutover/recovery evidence and backups; close older Pi processes and authorize each real root | One recognized owner with unchanged compatible data | Only the explicitly approved checkout-service stop/restart was used for package-identity and runtime maintenance; no production-storage transfer or settings change was made, and no real-data cutover is included |
96
172
  | Native platform maintainer | Prepared transport/process tests; run native Windows/macOS checks | Correct local transport, permissions, independent lifetime, and recovery | Native ACL/named-pipe, logout, and physical power-loss behavior remain unverified; do not advertise new unverified guarantees or silently remove previous support |
97
173
  | Provider/storage account owner | Explicit cost/network authorization and isolated data; optional live smoke | Authorized dispatch/publication without exposed credentials | Entitlements and custom-provider/production behavior remain unverified; deterministic providers and loopback stores are the default |
@@ -70,6 +70,12 @@ Startup transfer summaries report the preference and prerequisites, not a claim
70
70
 
71
71
  TUI Pull and Push reviews reuse the existing scrollable safe-default confirmation and exact Details document; RPC and History rollback retain their observable confirmation protocols. The existing History dialog ownership/cancellation flow is not replaced. All changed counts come from effective snapshot differences rather than raw merge decisions. Protected paths, preserved remote files, merged bytes, and withheld paths must be accounted for before rendering. Cancellation performs no transfer; pre-commit preparation may retain recovery evidence. After the commit boundary, existing completion/recovery rules apply instead of promising undo.
72
72
 
73
+ ## Resource reload after a transfer
74
+
75
+ If the user accepts the reload prompt after a pull or rollback, `/sync` waits for the daemon job and closes its dialogs before asking Pi to reload. Declining leaves the completed transfer in place without reloading. Reload still waits for session shutdown and daemon cleanup.
76
+
77
+ RPC and the TUI harness verify this ordering. The native Fedora/tmux flow from [issue #1935](https://github.com/narumiruna/pi-extensions/issues/1935) was not run. To verify it, repeat the issue's loopback WebDAV steps with a temporary agent directory. After accepting reload, check that the progress display closes and the next editor input or `/sync` command works.
78
+
73
79
  ## Review boundaries
74
80
 
75
81
  This change does not touch model prompts, tool exposure, shared-terminal handoff, settings formats, credentials, or default sync policies. Existing startup/session signals and Kit/custom-interaction disposal own new UI calls. Any awaited review is followed by owner validation, and each mutating operation revalidates its mutable inputs before its existing commit boundary. Status and differences actions use existing routes; manager opening/refresh remains observational and does not contact the remote. Diagnostics discloses its WebDAV write/repair behavior before execution.
@@ -119,7 +125,7 @@ Verification evidence:
119
125
 
120
126
  - Root `npm run check` and `npm test` passed: 935 test files, 20,528 passed tests, 34 existing skips, and no unhandled errors.
121
127
  - The focused Pi Sync suite passed: 185 files, 3,293 passed tests, and 19 existing skips. Cases cover all four Settings descriptions, TUI/RPC consent, cancellation, the RPC Done exit without authorization, durable saves and failure recovery, Continuous sync dependencies, non-default keys, narrow rendering, and current/legacy documentation anchors.
122
- - A fenced-code-aware heading audit passed for all 37 package READMEs. Legacy fragment aliases remain in the README, authoritative settings reference, and compatibility index.
128
+ - A fenced-code-aware heading audit passed for all 37 package READMEs. Legacy fragment aliases were verified in the README and authoritative settings reference.
123
129
  - `npm run package:pack -- sync` and an actual temporary tarball inspection passed: 330 entries include the runtime, source, docs, skill, license, and changelog, without tests or repository plans.
124
130
 
125
131
  The first direct-Vitest run used a symlinked macOS temporary path and triggered existing alias-path safety checks; the successful focused run used the canonical temporary root, as the root runner does. New RPC choice assertions were corrected to include Kit's existing Done exit, and both consent flows now test that exit. No runtime safety check or acceptance criterion was relaxed. Later full-suite command-level rechecks exceeded the harness's 300-second command limit. A background full-suite recheck hit the readiness watchdog in the unchanged `test/packed-publish-native.test.ts`; that file passed separately. The final full-suite recheck uses a managed background runner without changing per-test limits. Biome reports existing schema-version and unrelated lint advisories; its gates pass without changing repository tooling.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@narumitw/pi-sync",
3
- "version": "0.60.2",
3
+ "version": "0.60.4",
4
4
  "description": "Pi extension that syncs Pi configuration through Git, WebDAV, Cloudflare R2, or S3-compatible storage.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -46,8 +46,8 @@
46
46
  "typecheck": "tsc --noEmit"
47
47
  },
48
48
  "dependencies": {
49
- "@narumitw/pi-sync-daemon": "^0.3.0",
50
- "@narumitw/pi-tui-kit": "^0.70.0"
49
+ "@narumitw/pi-sync-daemon": "^0.5.0",
50
+ "@narumitw/pi-tui-kit": "^0.70.1"
51
51
  },
52
52
  "devDependencies": {
53
53
  "@earendil-works/pi-coding-agent": "1.5.0",
@@ -251,6 +251,7 @@ UI changes save immediately through the existing ordered, atomic settings writer
251
251
  There is no project or environment override.
252
252
 
253
253
  With `debug: true`, reports show local initialization after recovery and settings resolution, then background work when it ends.
254
+ The report shows one line per stage, followed by a total.
254
255
  TUI reports are stored as custom session entries, so they remain in the transcript after `/reload` and later notifications without entering model context.
255
256
  RPC reports remain notifications.
256
257
  When Continuous sync is enabled, the background report covers its first cycle rather than the separate one-shot startup check; later polls and same-session idle resumes do not publish more timing reports.
@@ -104,7 +104,7 @@ export async function executeCommand(
104
104
  options.signal,
105
105
  );
106
106
  } else if (action === "status") {
107
- const connection = await client.connect();
107
+ const connection = await client.verifyConnection(options.signal);
108
108
  ctx.ui.notify(
109
109
  `pi-sync-daemon: connected\nPID: ${connection.identity.pid}\nInstance: ${connection.identity.instance}\nUse pi-sync-daemon status/stop/restart --root <agent-directory> for explicit lifecycle control.`,
110
110
  "info",
@@ -73,11 +73,13 @@ export async function handleCommand(
73
73
  setSyncStatus(ctx, undefined);
74
74
  ctx.ui.notify(errorMessage(error), "error");
75
75
  }
76
+ if (sessionSignal.aborted) return;
76
77
  await reconcileObservation(attention, sessionSignal);
77
78
  if (!sessionSignal.aborted) await attention.publish(ctx, sessionSignal);
78
79
  return;
79
80
  }
80
81
  const result = await run(rawArgs);
82
+ if (sessionSignal.aborted) return;
81
83
  if (result.kind === "decision-required") {
82
84
  ctx.ui.notify(result.decision.directMessage, "error");
83
85
  } else if (result.kind === "remote-selection-required") {