@narumitw/pi-sync 0.68.1 → 0.69.0

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 (93) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/README.md +35 -21
  3. package/dist/chunks/{chunk-AYGMIMCV.ts → chunk-4KGDPLQ4.ts} +2 -2
  4. package/dist/chunks/chunk-4KGDPLQ4.ts.map +7 -0
  5. package/dist/chunks/{chunk-FR6A7ASZ.ts → chunk-EG6BUOUQ.ts} +3 -3
  6. package/dist/chunks/{chunk-WQXUZSY5.ts → chunk-EI2J5Z4Q.ts} +13 -6
  7. package/dist/chunks/chunk-EI2J5Z4Q.ts.map +7 -0
  8. package/dist/chunks/{chunk-BCDBT4X3.ts → chunk-GXB74FYB.ts} +4 -4
  9. package/dist/chunks/{chunk-J52GYZO6.ts → chunk-LNZRNXNQ.ts} +2 -4
  10. package/dist/chunks/{chunk-FQKWGVMA.ts → chunk-OWSKD5XG.ts} +10 -7
  11. package/dist/chunks/chunk-OWSKD5XG.ts.map +7 -0
  12. package/dist/chunks/{chunk-WCGLU526.ts → chunk-RXZVLBPU.ts} +3 -3
  13. package/dist/chunks/{chunk-KAIVTJIQ.ts → chunk-RZB2DPVU.ts} +2 -2
  14. package/dist/chunks/{chunk-335XTMMZ.ts → chunk-VQTYTUBU.ts} +24 -26
  15. package/dist/chunks/chunk-VQTYTUBU.ts.map +7 -0
  16. package/dist/chunks/{chunk-TLYT6HVI.ts → chunk-YX6DCQ7P.ts} +2 -2
  17. package/dist/chunks/{command-handler-5LDTCUJE.ts → command-handler-ZR26OSBX.ts} +39 -143
  18. package/dist/chunks/command-handler-ZR26OSBX.ts.map +7 -0
  19. package/dist/chunks/{conflict-review-SZ3AWTX6.ts → conflict-review-W5BCZIZG.ts} +2 -2
  20. package/dist/chunks/{file-selection-4BOQBXS7.ts → file-selection-STCIRKF6.ts} +3 -3
  21. package/dist/chunks/{manager-result-dispatcher-A4IWLS4J.ts → manager-result-dispatcher-MPLPDR2P.ts} +5 -5
  22. package/dist/chunks/{manager-ui-KHMCSLLV.ts → manager-ui-OMZOBGYT.ts} +99 -96
  23. package/dist/chunks/manager-ui-OMZOBGYT.ts.map +7 -0
  24. package/dist/chunks/{merge-review-LWMUE5IW.ts → merge-review-KTIQBRLL.ts} +2 -2
  25. package/dist/chunks/{remote-selection-ui-F6NJBQ3Y.ts → remote-selection-ui-CCHMCAHQ.ts} +4 -4
  26. package/dist/chunks/{setup-switch-7LMIRMZ7.ts → setup-switch-J3YLBB6N.ts} +4 -4
  27. package/dist/chunks/{setup-wizard-2NRPR433.ts → setup-wizard-J3YOR7BR.ts} +3 -4
  28. package/dist/chunks/{setup-wizard-2NRPR433.ts.map → setup-wizard-J3YOR7BR.ts.map} +1 -1
  29. package/dist/chunks/{sync-inspection-OTI4JDQ2.ts → sync-inspection-7OADBR57.ts} +3 -3
  30. package/dist/chunks/{sync-operations-ZUYJLWUN.ts → sync-operations-3K6WLPXY.ts} +2 -10
  31. package/dist/chunks/{sync-operations-ZUYJLWUN.ts.map → sync-operations-3K6WLPXY.ts.map} +2 -2
  32. package/dist/daemon/dist/build-id.json +1 -1
  33. package/dist/daemon/dist/engine/backends/git/git-backend.js +1 -1
  34. package/dist/daemon/dist/engine/backends/s3/s3-backend.js +2 -2
  35. package/dist/daemon/dist/engine/backends/webdav/webdav-backend.js +67 -6
  36. package/dist/daemon/dist/engine/debug-check.js +59 -0
  37. package/dist/daemon/dist/engine/debug-log.js +100 -1
  38. package/dist/daemon/dist/engine/sync/directional-conflict.js +31 -0
  39. package/dist/daemon/dist/engine/sync/push-review.js +1 -1
  40. package/dist/daemon/dist/engine/sync/sync-error-guidance.js +6 -5
  41. package/dist/daemon/dist/engine/sync/sync-inspection.js +5 -1
  42. package/dist/daemon/dist/engine/sync/sync-mutations.js +40 -7
  43. package/dist/daemon/dist/engine/sync/sync-queries.js +99 -25
  44. package/dist/daemon/dist/engine/sync/sync-state.js +1 -1
  45. package/dist/daemon/dist/engine/ui/transfer-review.js +2 -3
  46. package/dist/daemon/dist/engine-service.js +100 -25
  47. package/dist/daemon/dist/foreground-transfer.js +10 -0
  48. package/dist/daemon/dist/index.js +1 -0
  49. package/dist/daemon/dist/server.js +2 -1
  50. package/dist/daemon/package.json +1 -1
  51. package/dist/index.ts +111 -10
  52. package/dist/index.ts.map +3 -3
  53. package/docs/daemon-migration.md +2 -2
  54. package/docs/tui-contract.md +7 -7
  55. package/package.json +7 -4
  56. package/skills/configure-pi-sync/SKILL.md +4 -7
  57. package/skills/configure-pi-sync/references/configuration.md +20 -19
  58. package/src/commands/command-execution.ts +36 -136
  59. package/src/commands/command-handler.ts +3 -3
  60. package/src/commands/command.ts +28 -26
  61. package/src/daemon/directional-recovery.ts +3 -1
  62. package/src/daemon/pi-client.ts +6 -0
  63. package/src/sync/debug-tool.ts +96 -0
  64. package/src/sync/startup-check.ts +1 -1
  65. package/src/sync/sync-operations.ts +0 -6
  66. package/src/sync-extension.ts +13 -1
  67. package/src/ui/cancellable-operation.ts +11 -4
  68. package/src/ui/manager-state.ts +13 -12
  69. package/src/ui/manager-ui.ts +96 -81
  70. package/src/ui/operation-dialogs.ts +1 -1
  71. package/src/ui/settings-ui.ts +2 -3
  72. package/src/ui/setup/webdav-ui.ts +1 -1
  73. package/dist/chunks/chunk-335XTMMZ.ts.map +0 -7
  74. package/dist/chunks/chunk-AYGMIMCV.ts.map +0 -7
  75. package/dist/chunks/chunk-ECYCNZOE.ts +0 -12
  76. package/dist/chunks/chunk-ECYCNZOE.ts.map +0 -7
  77. package/dist/chunks/chunk-FQKWGVMA.ts.map +0 -7
  78. package/dist/chunks/chunk-WQXUZSY5.ts.map +0 -7
  79. package/dist/chunks/command-handler-5LDTCUJE.ts.map +0 -7
  80. package/dist/chunks/manager-ui-KHMCSLLV.ts.map +0 -7
  81. /package/dist/chunks/{chunk-FR6A7ASZ.ts.map → chunk-EG6BUOUQ.ts.map} +0 -0
  82. /package/dist/chunks/{chunk-BCDBT4X3.ts.map → chunk-GXB74FYB.ts.map} +0 -0
  83. /package/dist/chunks/{chunk-J52GYZO6.ts.map → chunk-LNZRNXNQ.ts.map} +0 -0
  84. /package/dist/chunks/{chunk-WCGLU526.ts.map → chunk-RXZVLBPU.ts.map} +0 -0
  85. /package/dist/chunks/{chunk-KAIVTJIQ.ts.map → chunk-RZB2DPVU.ts.map} +0 -0
  86. /package/dist/chunks/{chunk-TLYT6HVI.ts.map → chunk-YX6DCQ7P.ts.map} +0 -0
  87. /package/dist/chunks/{conflict-review-SZ3AWTX6.ts.map → conflict-review-W5BCZIZG.ts.map} +0 -0
  88. /package/dist/chunks/{file-selection-4BOQBXS7.ts.map → file-selection-STCIRKF6.ts.map} +0 -0
  89. /package/dist/chunks/{manager-result-dispatcher-A4IWLS4J.ts.map → manager-result-dispatcher-MPLPDR2P.ts.map} +0 -0
  90. /package/dist/chunks/{merge-review-LWMUE5IW.ts.map → merge-review-KTIQBRLL.ts.map} +0 -0
  91. /package/dist/chunks/{remote-selection-ui-F6NJBQ3Y.ts.map → remote-selection-ui-CCHMCAHQ.ts.map} +0 -0
  92. /package/dist/chunks/{setup-switch-7LMIRMZ7.ts.map → setup-switch-J3YLBB6N.ts.map} +0 -0
  93. /package/dist/chunks/{sync-inspection-OTI4JDQ2.ts.map → sync-inspection-7OADBR57.ts.map} +0 -0
package/dist/index.ts.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 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 { configFromSettings, loadConfigForCheck, syncCheckConfigFingerprint } from \"../settings/config.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\";\nimport { syncSessionsSelected } from \"./sync-policy.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 let showLocalTimings = false;\n let localStartupComplete = false;\n try {\n const { document, settings } = await timings.measure(\"settings read\", () => client.readStartupSettings(signal));\n client.validate();\n throwIfAborted(signal);\n const debug = settings?.debug ?? false;\n client.setDebugPreference(debug);\n configureSyncStatus(ctx, settings?.showStatus ?? true);\n const { stateDirectoryMigrationNotice } = await import(\"../state/state-directory.js\");\n client.validate();\n throwIfAborted(signal);\n const notice = stateDirectoryMigrationNotice();\n if (settings?.activeSyncSetup && document) {\n const ready = !notice && (await client.tryStartupBootstrap(document, debug, signal));\n client.validate();\n throwIfAborted(signal);\n if (ready) {\n setSyncSetupCompletions(Object.keys(settings.syncSetups).sort((a, b) => a.localeCompare(b)));\n showLocalTimings = debug;\n localStartupComplete = true;\n return { debug, config: configFromSettings(settings) };\n }\n } else {\n const { pendingTransactionEntries } = await import(\"../snapshot/snapshot-transaction-directory.js\");\n const recoveryNeeded = (await pendingTransactionEntries()).length > 0;\n client.validate();\n throwIfAborted(signal);\n if (!recoveryNeeded) {\n if (notice) ctx.ui.notify(notice, \"warning\");\n setSyncSetupCompletions([]);\n await client.markReady(debug);\n client.validate();\n throwIfAborted(signal);\n client.recordDebug({ event: \"job\", operation: \"initialize\", outcome: \"skipped\" });\n showLocalTimings = debug;\n localStartupComplete = true;\n return { debug };\n }\n }\n localStartupComplete = true;\n } finally {\n timings.publish(\n ctx,\n showLocalTimings,\n signal,\n \"local initialization\",\n localStartupComplete ? \"completed\" : \"stopped\",\n client.debugEnabled && !signal.aborted\n ? (report) => client.recordDebug({ event: \"startup-timings\", report })\n : undefined,\n );\n }\n const result = (await client.run(\"initialize\", {}, signal)) as {\n debug: boolean;\n config?: AnySyncConfig;\n settings?: PiSyncSettingsV3;\n handoverRequired: boolean;\n };\n client.validate();\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 const eligible = (config: AnySyncConfig) => config.automatic && syncSessionsSelected(config);\n if (!(await client.configured((settings) => eligible(configFromSettings(settings))))) {\n client.recordDebug({ event: \"job\", operation: \"shutdown\", outcome: \"skipped\" });\n return;\n }\n throwIfAborted(signal);\n const config = await loadConfigForCheck(undefined, signal);\n throwIfAborted(signal);\n if (!eligible(config)) {\n client.recordDebug({ event: \"job\", operation: \"shutdown\", outcome: \"skipped\" });\n return;\n }\n const automaticFingerprint = syncCheckConfigFingerprint(config);\n await client.run(\n \"shutdown\",\n { args: [], yes: true, force: false, stale: false, silent: true, reload: false, automaticFingerprint },\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:\n | { ctx: ExtensionContext; signal: AbortSignal; config: AnySyncConfig; logTimings?: (report: string) => void }\n | 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, queued.logTimings);\n },\n start(\n ctx: ExtensionContext,\n sessionSignal: AbortSignal,\n initialConfig?: AnySyncConfig,\n logTimings?: (report: string) => void,\n ) {\n if (!ctx.hasUI || sessionSignal.aborted) return;\n if (initialConfig && startupTransferEnabled(initialConfig) && !ctx.isIdle()) {\n pending = { ctx, signal: sessionSignal, config: initialConfig, logTimings };\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(undefined, signal));\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(undefined, signal);\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(undefined, signal);\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 const transferConfig = await loadConfigForCheck(undefined, signal);\n throwIfAborted(signal);\n if (!isCurrent() || syncCheckConfigFingerprint(transferConfig) !== identity) return;\n if (!ctx.isIdle()) {\n pending = { ctx, signal: sessionSignal, config: captured, logTimings };\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 automaticFingerprint: identity,\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 logTimings,\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, action, ...extra] = splitArgs(args);\n const recover = command === \"daemon\" && action === \"recover\";\n const ready = recover ? undefined : await initialization;\n if (signal.aborted || owner !== client) return;\n const needsDaemonRecovery = () => client.ownershipCleanupRequired;\n if (recover || (!command && needsDaemonRecovery())) {\n if (recover && extra.length) {\n ctx.ui.notify(\"Usage: /sync daemon recover\", \"error\");\n return;\n }\n const commands = await loaders.commands();\n if (signal.aborted || owner !== client) return;\n await commands.handleCommand(\n args,\n ctx,\n commandSignal,\n loaders,\n attention,\n undefined,\n needsDaemonRecovery,\n );\n return;\n }\n const daemonStatus = command === \"daemon\" && (!action || action === \"status\");\n const requiresContact = !daemonStatus && ![\"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 if (!daemonStatus) 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(\n args,\n ctx,\n commandSignal,\n loaders,\n attention,\n undefined,\n needsDaemonRecovery,\n );\n } catch (error) {\n client.recordOwnershipFailure(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 || daemonStatus || 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 && !needsDaemonRecovery()).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 previousClient = owner;\n shutdownAbort?.abort(new DOMException(\"Session replaced\", \"AbortError\"));\n shutdownAbort = undefined;\n sessionAbort.abort(new DOMException(\"Session replaced\", \"AbortError\"));\n const releaseStatus = status.start(ctx);\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 ctx.isIdle();\n client.recordOwnershipFailure(error);\n if (ctx.hasUI) {\n const advice = client.ownershipCleanupRequired ? \" Open /sync to recover the daemon.\" : \"\";\n ctx.ui.notify(`pi-sync recovery required: ${safeTerminalText(errorMessage(error))}${advice}`, \"error\");\n }\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) {\n client.disableQueueReleaseUI();\n releaseStatus();\n }\n if (ready && !signal.aborted && owner === client && (ready.automatic || startupTransferEnabled(ready)))\n await withPiDaemonClient(ctx, async () => {\n check.start(\n ctx,\n signal,\n ready,\n client.debugEnabled ? (report) => client.recordDebug({ event: \"startup-timings\", report }) : undefined,\n );\n });\n } catch (error) {\n client.disableQueueReleaseUI();\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 shutdownClient.setDebugPreference(client.debugEnabled);\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;;;ACarC,eAAsB,aACpB,KACA,Q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A,QAChB;AAAA,MACF;AACA,UAAI,kBAAkB,WAAY,iBAAgB;AAAA,IACpD;AAAA,EACF,CAAC;AACH;",
3
+ "sources": ["../src/sync/agent-policy.ts", "../src/settings/config-errors.ts", "../src/sync/startup-timings.ts", "../src/sync/automatic-sync.ts", "../src/sync/debug-tool.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 { configFromSettings, loadConfigForCheck, syncCheckConfigFingerprint } from \"../settings/config.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\";\nimport { syncSessionsSelected } from \"./sync-policy.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 let showLocalTimings = false;\n let localStartupComplete = false;\n try {\n const { document, settings } = await timings.measure(\"settings read\", () => client.readStartupSettings(signal));\n client.validate();\n throwIfAborted(signal);\n const debug = settings?.debug ?? false;\n client.setDebugPreference(debug);\n configureSyncStatus(ctx, settings?.showStatus ?? true);\n const { stateDirectoryMigrationNotice } = await import(\"../state/state-directory.js\");\n client.validate();\n throwIfAborted(signal);\n const notice = stateDirectoryMigrationNotice();\n if (settings?.activeSyncSetup && document) {\n const ready = !notice && (await client.tryStartupBootstrap(document, debug, signal));\n client.validate();\n throwIfAborted(signal);\n if (ready) {\n setSyncSetupCompletions(Object.keys(settings.syncSetups).sort((a, b) => a.localeCompare(b)));\n showLocalTimings = debug;\n localStartupComplete = true;\n return { debug, config: configFromSettings(settings) };\n }\n } else {\n const { pendingTransactionEntries } = await import(\"../snapshot/snapshot-transaction-directory.js\");\n const recoveryNeeded = (await pendingTransactionEntries()).length > 0;\n client.validate();\n throwIfAborted(signal);\n if (!recoveryNeeded) {\n if (notice) ctx.ui.notify(notice, \"warning\");\n setSyncSetupCompletions([]);\n await client.markReady(debug);\n client.validate();\n throwIfAborted(signal);\n client.recordDebug({ event: \"job\", operation: \"initialize\", outcome: \"skipped\" });\n showLocalTimings = debug;\n localStartupComplete = true;\n return { debug };\n }\n }\n localStartupComplete = true;\n } finally {\n timings.publish(\n ctx,\n showLocalTimings,\n signal,\n \"local initialization\",\n localStartupComplete ? \"completed\" : \"stopped\",\n client.debugEnabled && !signal.aborted\n ? (report) => client.recordDebug({ event: \"startup-timings\", report })\n : undefined,\n );\n }\n const result = (await client.run(\"initialize\", {}, signal)) as {\n debug: boolean;\n config?: AnySyncConfig;\n settings?: PiSyncSettingsV3;\n handoverRequired: boolean;\n };\n client.validate();\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 const eligible = (config: AnySyncConfig) => config.automatic && syncSessionsSelected(config);\n if (!(await client.configured((settings) => eligible(configFromSettings(settings))))) {\n client.recordDebug({ event: \"job\", operation: \"shutdown\", outcome: \"skipped\" });\n return;\n }\n throwIfAborted(signal);\n const config = await loadConfigForCheck(undefined, signal);\n throwIfAborted(signal);\n if (!eligible(config)) {\n client.recordDebug({ event: \"job\", operation: \"shutdown\", outcome: \"skipped\" });\n return;\n }\n const automaticFingerprint = syncCheckConfigFingerprint(config);\n await client.run(\n \"shutdown\",\n { args: [], yes: true, force: false, stale: false, silent: true, reload: false, automaticFingerprint },\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 { StringEnum } from \"@earendil-works/pi-ai\";\nimport type { ExtensionAPI, ExtensionContext } from \"@earendil-works/pi-coding-agent\";\nimport { debugCheckFailure, summarizeDebugInspection } from \"@narumitw/pi-sync-daemon/engine/debug-check\";\nimport { readLatestDebugCheck } from \"@narumitw/pi-sync-daemon/engine/debug-log\";\nimport { Type } from \"typebox\";\nimport type { PiDaemonClient } from \"../daemon/pi-client.js\";\nimport { configFromSettings, syncCheckConfigFingerprint, syncConfigReviewFingerprint } from \"../settings/config.js\";\n\nconst TOOL_NAME = \"pi_sync_debug\";\nconst RECHECK_TIMEOUT_MS = 30_000;\ntype DebugOwner = { client: PiDaemonClient; signal: AbortSignal };\n\nfunction toolResult(value: unknown) {\n return { content: [{ type: \"text\" as const, text: JSON.stringify(value) }], details: {} };\n}\n\nexport function registerPiSyncDebug(pi: ExtensionAPI, getOwner: (ctx: ExtensionContext) => DebugOwner | undefined) {\n pi.registerTool({\n name: TOOL_NAME,\n label: \"Pi Sync debug\",\n description:\n \"Read the latest sanitized Pi Sync check from the local log (latest), or read configured remote storage without confirmation to return a fresh sanitized summary (recheck). Does not publish or apply files.\",\n parameters: Type.Object({ action: StringEnum([\"latest\", \"recheck\"]) }, { additionalProperties: false }),\n defaultActive: false,\n exposure: \"direct\",\n executionMode: \"sequential\",\n async execute(_id, { action }, toolSignal, _update, ctx) {\n const owner = getOwner(ctx);\n if (!owner || !ctx.hasUI || (ctx.mode !== \"tui\" && ctx.mode !== \"rpc\"))\n throw new Error(\"Pi Sync debug requires an interactive session started with Debug mode on.\");\n const { client } = owner;\n const signal = toolSignal ? AbortSignal.any([owner.signal, toolSignal]) : owner.signal;\n const validate = () => {\n signal.throwIfAborted();\n if (getOwner(ctx)?.client !== client) throw new Error(\"Pi Sync session was replaced.\");\n try {\n client.validateDebugTool();\n } catch {\n throw new Error(\"The Pi Sync debug session is no longer available.\");\n }\n };\n async function readSetup() {\n validate();\n try {\n const { settings } = await client.readStartupSettings(signal);\n validate();\n if (settings) return configFromSettings(settings);\n } catch {\n validate();\n }\n throw new Error(\"The current Pi Sync setup is not available. Review /sync \u2192 Settings.\");\n }\n const setup = await readSetup();\n validate();\n if (action === \"latest\") {\n const last = readLatestDebugCheck(client.root, syncConfigReviewFingerprint(setup));\n if (last.kind === \"unavailable\") throw new Error(\"The private Pi Sync debug log is unavailable.\");\n if (last.kind === \"no-record\") return toolResult({ kind: \"no-record\" });\n return toolResult({ kind: \"historical\", ...last.check });\n }\n if (action !== \"recheck\") throw new Error(\"Choose latest or recheck.\");\n if (client.ownershipCleanupRequired) throw new Error(\"Pi Sync needs recovery. Open /sync daemon status.\");\n const fingerprint = syncCheckConfigFingerprint(setup);\n const deadline = AbortSignal.timeout(RECHECK_TIMEOUT_MS);\n const recheckSignal = AbortSignal.any([signal, deadline]);\n let result: unknown;\n try {\n result = await client.run(\n \"inspect\",\n { setup: setup.setupName, fingerprint, origin: \"recheck\" },\n recheckSignal,\n ctx,\n );\n } catch (error) {\n validate();\n const { reason } = debugCheckFailure(deadline.aborted ? deadline.reason : error);\n throw new Error(`Pi Sync recheck failed: ${reason}.`);\n }\n validate();\n if (deadline.aborted) throw new Error(\"Pi Sync recheck failed: timeout.\");\n const latest = await readSetup();\n validate();\n if (fingerprint !== syncCheckConfigFingerprint(latest))\n throw new Error(\"Pi Sync setup changed during recheck. Ask to recheck the new setup.\");\n const summary = summarizeDebugInspection(result);\n if (!summary) throw new Error(\"Pi Sync did not return a valid check result.\");\n return toolResult({ kind: \"fresh\", time: new Date().toISOString(), origin: \"recheck\", summary });\n },\n });\n\n return (enabled: boolean) => {\n const active = pi.getActiveTools();\n if (active.includes(TOOL_NAME) === enabled) return;\n pi.setActiveTools(enabled ? [...active, TOOL_NAME] : active.filter((name) => name !== TOOL_NAME));\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:\n | { ctx: ExtensionContext; signal: AbortSignal; config: AnySyncConfig; logTimings?: (report: string) => void }\n | 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, queued.logTimings);\n },\n start(\n ctx: ExtensionContext,\n sessionSignal: AbortSignal,\n initialConfig?: AnySyncConfig,\n logTimings?: (report: string) => void,\n ) {\n if (!ctx.hasUI || sessionSignal.aborted) return;\n if (initialConfig && startupTransferEnabled(initialConfig) && !ctx.isIdle()) {\n pending = { ctx, signal: sessionSignal, config: initialConfig, logTimings };\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(undefined, signal));\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(undefined, signal);\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(undefined, signal);\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 const transferConfig = await loadConfigForCheck(undefined, signal);\n throwIfAborted(signal);\n if (!isCurrent() || syncCheckConfigFingerprint(transferConfig) !== identity) return;\n if (!ctx.isIdle()) {\n pending = { ctx, signal: sessionSignal, config: captured, logTimings };\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 automaticFingerprint: identity,\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))}. Use View differences in /sync, or ask Pi to recheck in Debug mode. 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 logTimings,\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, retiredSyncCommandGuidance, 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 { registerPiSyncDebug } from \"./sync/debug-tool.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 const exposeDebugTool = registerPiSyncDebug(pi, (ctx) =>\n owner?.debugEnabled && !sessionAbort.signal.aborted && ownerManager === ctx.sessionManager\n ? { client: owner, signal: sessionAbort.signal }\n : undefined,\n );\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 const retired = retiredSyncCommandGuidance(splitArgs(args)[0]);\n if (retired) {\n ctx.ui.notify(retired, \"warning\");\n return;\n }\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, action, ...extra] = splitArgs(args);\n const recover = command === \"daemon\" && action === \"recover\";\n const ready = recover ? undefined : await initialization;\n if (signal.aborted || owner !== client) return;\n const needsDaemonRecovery = () => client.ownershipCleanupRequired;\n if (recover || (!command && needsDaemonRecovery())) {\n if (recover && extra.length) {\n ctx.ui.notify(\"Usage: /sync daemon recover\", \"error\");\n return;\n }\n const commands = await loaders.commands();\n if (signal.aborted || owner !== client) return;\n await commands.handleCommand(\n args,\n ctx,\n commandSignal,\n loaders,\n attention,\n undefined,\n needsDaemonRecovery,\n );\n return;\n }\n const daemonStatus = command === \"daemon\" && (!action || action === \"status\");\n const requiresContact = !daemonStatus && ![\"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 if (!daemonStatus) 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(\n args,\n ctx,\n commandSignal,\n loaders,\n attention,\n undefined,\n needsDaemonRecovery,\n );\n } catch (error) {\n client.recordOwnershipFailure(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 || daemonStatus || 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 && !needsDaemonRecovery()).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 previousClient = owner;\n shutdownAbort?.abort(new DOMException(\"Session replaced\", \"AbortError\"));\n shutdownAbort = undefined;\n sessionAbort.abort(new DOMException(\"Session replaced\", \"AbortError\"));\n const releaseStatus = status.start(ctx);\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 ctx.isIdle();\n client.recordOwnershipFailure(error);\n if (ctx.hasUI) {\n const advice = client.ownershipCleanupRequired ? \" Open /sync to recover the daemon.\" : \"\";\n ctx.ui.notify(`pi-sync recovery required: ${safeTerminalText(errorMessage(error))}${advice}`, \"error\");\n }\n } catch {\n /* SDK context was replaced. */\n }\n }\n return false;\n }\n });\n try {\n const ready = await initialization;\n if (!signal.aborted && owner === client) exposeDebugTool(client.debugEnabled);\n if (ready === false) {\n client.disableQueueReleaseUI();\n releaseStatus();\n }\n if (ready && !signal.aborted && owner === client && (ready.automatic || startupTransferEnabled(ready)))\n await withPiDaemonClient(ctx, async () => {\n check.start(\n ctx,\n signal,\n ready,\n client.debugEnabled ? (report) => client.recordDebug({ event: \"startup-timings\", report }) : undefined,\n );\n });\n } catch (error) {\n client.disableQueueReleaseUI();\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 shutdownClient.setDebugPreference(client.debugEnabled);\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;;;ACarC,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,MAAI,mBAAmB;AACvB,MAAI,uBAAuB;AAC3B,MAAI;AACF,UAAM,EAAE,UAAU,SAAS,IAAI,MAAM,QAAQ,QAAQ,iBAAiB,MAAM,OAAO,oBAAoB,MAAM,CAAC;AAC9G,WAAO,SAAS;AAChB,mBAAe,MAAM;AACrB,UAAM,QAAQ,UAAU,SAAS;AACjC,WAAO,mBAAmB,KAAK;AAC/B,wBAAoB,KAAK,UAAU,cAAc,IAAI;AACrD,UAAM,EAAE,8BAA8B,IAAI,MAAM,OAA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AgB,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
6
  "names": ["config", "ctx"]
7
7
  }
@@ -101,7 +101,7 @@ quiet; longer retries show `sync recovering` when sync status is enabled.
101
101
  If a background release remains unconfirmed during a command, Pi reports it
102
102
  after the command finishes.
103
103
  A release acknowledgement alone does not confirm that a transfer succeeded.
104
- For the manager's explicit **Push to remote** and **Pull from remote** actions, the client first resolves the original job with the same daemon. On an eligible file-queue failure it can then drain that exact owner and reconnect after verifying exit. It never repeats a verified result. It can resume after a proven pre-write failure only once and only when the original setup and source/destination evidence still match. It does not restart an owner that still has other live participating Pi clients, pending work, or unresolved consent or upgrade state. A missing result or conflicting evidence is not permission to replay. If recovery stops after a verified transfer, Pi Sync reports the restore point to the active session. If `/sync daemon status` is blocked by recovery, run it after recovery finishes. This path does not extend transfer or model permission.
104
+ For the manager's explicit **Push to remote** and **Pull from remote** actions, the client first resolves the original job with the same daemon. On an eligible file-queue failure it can then drain that exact owner and reconnect after verifying exit. It never repeats a verified result. It can retry a non-forced transfer after a proven pre-write failure only once and only when the original setup and source/destination evidence still match. A Force transfer stopped before writing needs a new review; recovery can report a verified result but cannot replay Force. It does not restart an owner that still has other live participating Pi clients, pending work, or unresolved consent or upgrade state. A missing result or conflicting evidence is not permission to replay. If recovery stops after a verified transfer, Pi Sync reports the restore point to the active session. If `/sync daemon status` is blocked by recovery, run it after recovery finishes. This path does not extend transfer or model permission.
105
105
 
106
106
  ## Recover from uncertain daemon cleanup
107
107
 
@@ -219,7 +219,7 @@ The archived previous engine also held its real operation lock in a separate pro
219
219
  | Responsible role | Prerequisite and action | Expected result | Unverified behavior and restriction |
220
220
  | --- | --- | --- | --- |
221
221
  | npm/release account owner | Passing package gates and explicit approval; verify publication rights for each selected package, the embedded daemon version in the Pi Sync tarball, and the required Kit artifact | Pi Sync publishes without waiting for a standalone daemon artifact; standalone daemon releases stay independent | No publication, visibility change, tags, or workflow dispatch without approval |
222
- | 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 |
222
+ | Device operator | Verified builds and an isolated setup; suspend and wake the target device, then run `/sync daemon status` and `/sync diff` 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 |
223
223
  | 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 |
224
224
  | 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 |
225
225
  | 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 |
@@ -4,15 +4,15 @@ This reference records the setting and transfer contracts used by the TUI. It do
4
4
 
5
5
  ## Action palette
6
6
 
7
- The `/sync` TUI manager uses Kit's public searchable `ChoiceScreen` with at most five visible choices. Ordinary rows contain only labels; the selected action's short description appears below the list and is included in search. Searching for `storage connections` finds **Settings** in the configured manager. Search and selection survive a cancelled operation. Navigation, confirmation, cancellation, paste, focus, scrolling and constrained-height framing remain Kit-owned. RPC keeps an unfiltered list with the established **Sync now** label and a **Done** exit; TUI displays **Sync…** for that same action.
7
+ The `/sync` TUI manager uses Kit's public `ChoiceScreen` without search. It shows up to six choices and scrolls when more are available or the terminal is short. Ordinary rows contain only labels; the selected action's short description appears below the list. Selection survives a cancelled operation. Navigation, confirmation, cancellation, focus and constrained-height framing remain Kit-owned. Normal bracketed paste delivered by Pi does not navigate or activate actions. RPC keeps an unfiltered list with the established **Sync now** label and a **Done** exit; TUI displays **Sync…** for that same action.
8
8
 
9
9
  The homepage shows setup/storage, cached remote observations, last applied state and relevant automatic-transfer permissions. It does not render scheduler owners, leases, request accounting or candidate limits. Recorded background phases and successful background-transfer timestamps are explicitly historical; neither replaces a fresh remote check. Missing records show **not yet observed**, and unreadable or invalid records show **Unknown**. Last applied does not invent a timestamp or direction.
10
10
 
11
- **Diagnostics** requires backend-probe consent and rechecks the setup fingerprint after confirmation. The direct `/sync doctor` route remains unchanged.
11
+ **View differences** remains an explicit read action. **History** offers repair only when the active WebDAV snapshot is missing from History. It discloses the temporary conditional-write probe and history update before asking for consent and revalidates the reviewed setup and remote head before changing history.
12
12
 
13
13
  The attention widget retains its labeled muted separator and one body row: **Open /sync to review** with the setup name. It remains passive, preserves collapse state and observation classification, and exposes detailed reasons through the manager and existing notifications. Session replacement, shutdown and stale asynchronous publication retain their existing cleanup guards.
14
14
 
15
- Verification follows `docs/extension-conventions.md`, `docs/extension-settings.md`, and `docs/readme-conventions.md`. Palette tests cover bounded rendering, stable normal-height navigation, selected-action help, search/paste, non-default bindings, RPC and owner cancellation; existing transfer and stale-setup tests remain applicable. Physical-terminal appearance with the target font and pane sizes requires maintainer inspection. Live provider/backend behavior, Windows and Android were not newly verified by this presentation change. No settings schema, Kit API, transfer authorization or model-visible prefix changes are intended.
15
+ Verification follows `docs/extension-conventions.md`, `docs/extension-settings.md`, and `docs/readme-conventions.md`. Palette tests cover bounded rendering, stable normal-height navigation, selected-action help, ignored typing and paste, non-default bindings, RPC and owner cancellation; existing transfer and stale-setup tests remain applicable. Physical-terminal appearance with the target font and pane sizes requires maintainer inspection. Live provider/backend behavior, Windows and Android were not newly verified by this presentation change. No settings schema, Kit API, transfer authorization or model-visible prefix changes are intended.
16
16
 
17
17
  ## Settings
18
18
 
@@ -32,9 +32,9 @@ All settings are private to this device. There are no project overrides. Default
32
32
  | Merge settings fields | `sync.mergeSettings`, false | Current setup | Immediate save; opt-in merge on subsequent sync with a verified ancestor |
33
33
  | Content merge / partial progress | `sync.mergeContent`, `sync.partialSync`, false/false | Current setup | Explicit compatibility review and atomic save; Off, Merge only, Merge + partial, Partial only preserve all combinations |
34
34
  | Max file size / Max directory size | `sync.maxFileSizeMiB`, `sync.maxDirectorySizeMiB`, both absent | Current setup | Independent inputs; review before upgrading the settings document to version 9; subsequent transfers only. See [transfer size limits](../skills/configure-pi-sync/references/configuration.md#transfer-size-limits). |
35
- | Skip secret scan | `skipSecretScan`, false | All setups | Immediate save; subsequent manual/automatic pushes; Diagnostics still scans |
35
+ | Skip secret scan | `skipSecretScan`, false | All setups | Immediate save; subsequent manual/automatic pushes |
36
36
  | Show sync status | `showStatus`, true | All setups | Immediate save and immediate status visibility change; notifications/widgets remain |
37
- | Debug mode | `debug`, false | All setups | Immediate save; Pi logging and timing display use the next session start in TUI/RPC; daemon log uses the next owner or job boundary |
37
+ | Debug mode | `debug`, false | All setups | Immediate save; Pi logging, timing display, and `pi_sync_debug` use the next TUI/RPC session start or `/reload`; daemon log uses the next owner or job boundary |
38
38
 
39
39
  Opening foreground Settings cancels and drains startup work. Simple changes report saving, then one setting-specific confirmation or an error in Pi's notifications. Back does not undo successful saves; cancelling a draft or compatibility review leaves that change unsaved. In a transfer-size input or its version-upgrade review, Ctrl+C discards the draft and closes the `/sync` flow; ordinary cancellation returns to Settings. A failed save retains the previous document and effective/displayed value. Completed transfers are never undone by changing a preference.
40
40
 
@@ -52,7 +52,7 @@ Selecting **Settings** in `/sync` opens **Pi Sync Settings** directly as one sea
52
52
 
53
53
  The existing public Kit settings adapter is retained rather than adding a second selector or accessing private Pi fields. Installed `SettingsList` provides `updateValue()` and `selectItem()`, but has no injected keybinding or awaited-save/rejection contract and does not expose search focus. Kit already owns ordered pending changes, rollback, retained search/selection, IME focus, bounded frames, and clipped mouse coordinates. This is an intentional existing deviation from the literal native-component convention. No new Kit API, dependency floor, or release is required. A package-owned public rendering boundary returns no lines at zero width and retains the selected row (or search when nothing matches) below five content rows; compact mouse events map back to the original rendered row. It does not access private component state or add key handlers. Search placeholder and position-footer relocation remain unsupported by that public API; the existing native-style hints and position indicator are retained rather than patched through private fields.
54
54
 
55
- Last applied shows a compact opaque snapshot ID and explicitly states that application time is unavailable. History retains the full recorded ID even when the remote history no longer lists that snapshot. Snapshot `createdAt` is not a local application time; opening the manager performs no remote timestamp fetch.
55
+ **Last applied snapshot** shows an opaque ID, shortened only if it exceeds the menu's display limit. **History** retains the full recorded ID even when the remote history no longer lists that snapshot. The application time is unavailable; snapshot creation time does not substitute for it. Opening the manager performs no remote timestamp fetch.
56
56
 
57
57
  Startup transfer summaries report the preference and prerequisites, not a claim that a transfer is eligible now. Runtime evidence in `merged-sync.ts` and `s3/s3-backend.ts` permits Git, conditional WebDAV, and R2/S3 with verified conditional writes. `read-check-write-verify` publication is refused for automatic operations. Baseline, matching authoritative include policy, idle ownership, and conflict/secret checks remain mandatory. This corrects the earlier settings reference's manual-only R2/S3 statement without expanding backend authorization.
58
58
 
@@ -83,7 +83,7 @@ RPC and the TUI harness verify this ordering. The native Fedora/tmux flow from [
83
83
 
84
84
  ## Review boundaries
85
85
 
86
- 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.
86
+ Manager opening and refresh remain observational and do not contact remote storage. Existing startup/session signals and Kit/custom-interaction disposal own the UI calls. After a review, operations validate the session owner and revalidate mutable inputs before committing. Pi Sync activates `pi_sync_debug` at the session boundary only when the saved Debug mode and session mode allow it. Pi exposes the active tool directly and through codemode; `codemode.mode: "only"` hides the direct declaration and lists the tool in codemode instead. Pi Sync adds no prompt messages or per-turn tool updates. `recheck` does not request UI confirmation. It keeps session and setup revalidation, cancellation, and sanitized read-only results.
87
87
 
88
88
  ## Quiet footer presentation
89
89
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@narumitw/pi-sync",
3
- "version": "0.68.1",
3
+ "version": "0.69.0",
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",
@@ -47,25 +47,28 @@
47
47
  },
48
48
  "dependencies": {
49
49
  "@narumitw/sync-node-sdk": "npm:@earendil-works/pi-coding-agent@1.6.0",
50
- "@narumitw/pi-tui-kit": "^0.71.0",
50
+ "@narumitw/pi-tui-kit": "^0.72.0",
51
51
  "fast-xml-parser": "^5.12.1",
52
52
  "minimatch": "^11.0.9",
53
53
  "proper-lockfile": "^4.1.2",
54
54
  "semver": "^7.8.6"
55
55
  },
56
56
  "devDependencies": {
57
+ "@earendil-works/pi-ai": "1.6.0",
57
58
  "@earendil-works/pi-coding-agent": "1.6.0",
58
59
  "@earendil-works/pi-tui": "1.6.0",
59
- "@narumitw/pi-sync-daemon": "^0.14.1",
60
+ "@narumitw/pi-sync-daemon": "^0.15.0",
60
61
  "@types/proper-lockfile": "^4.1.4",
61
62
  "@types/semver": "^7.8.0",
62
63
  "esbuild": "0.28.2",
64
+ "typebox": "1.4.7",
63
65
  "typescript": "7.0.2"
64
66
  },
65
67
  "peerDependencies": {
66
68
  "@earendil-works/pi-ai": "*",
67
69
  "@earendil-works/pi-coding-agent": ">=1.1.0",
68
- "@earendil-works/pi-tui": "*"
70
+ "@earendil-works/pi-tui": "*",
71
+ "typebox": "*"
69
72
  },
70
73
  "repository": {
71
74
  "type": "git",
@@ -68,14 +68,11 @@ Explain that **Autonomous sync** and **Continuous sync** are retired and that th
68
68
  Inspect only the necessary local metadata and relevant non-secret configuration facts; do not expose raw settings, credentials, session contents, daemon records, journals, or backups in tool output or chat.
69
69
  Do not ask the user to paste those contents or execute text copied from them.
70
70
 
71
- For relevant startup, connection, or transfer symptoms, inspect recent [Debug mode log](references/configuration.md#shared-log) records in `<getAgentDir()>/pi-sync.log` (normally `~/.pi/agent/pi-sync.log`) under the agent directory identified above.
72
- Read only a bounded tail of an existing private regular file; skip it if it is missing, unsafe, symlinked, or hard-linked.
73
- Parse the JSON lines locally, filter by `source` (`pi-sync` for the client, `pi-sync-daemon` for the daemon), and report only relevant non-secret events and outcomes, never raw log lines.
74
- Missing records do not rule out a failure; do not enable Debug mode or start a transfer just to collect evidence.
71
+ For relevant startup or transfer symptoms, use `pi_sync_debug` with `latest` if the tool is available. It reads bounded summaries from the [private local log](references/configuration.md#shared-log) without contacting the daemon. Report only relevant outcomes, never raw log lines. Missing records do not rule out a failure; do not enable Debug mode or start a transfer just to collect evidence.
72
+ If the user requests a fresh comparison, use `pi_sync_debug` with `recheck` only when available. It reads the configured remote and returns a sanitized summary without a confirmation prompt. If it is unavailable, do not use another tool to make the read. Point the user to **View differences** for a manual file comparison.
75
73
 
76
74
  Leave operations that Pi Sync requires the user to review in `/sync`, including initial setup, credential and destination changes, reviewed legacy path selection and policy changes, session opt-in, secret-scan bypass, enabling automatic behavior, upgrading the settings document to enable a [transfer size limit](references/configuration.md#transfer-size-limits), and remote policy publication.
77
75
  Use the masked credential input in Pi; do not infer transfer or model consent from a settings edit.
78
- Do not start sync, run `/sync doctor` or backend/network commands, remove locks or recovery evidence, or bypass scan checks.
76
+ Do not start sync, run backend/network commands, remove locks or recovery evidence, or bypass scan checks. Leave any WebDAV history repair to the user in **/sync → History**.
79
77
 
80
- Report what changed or what was verified locally, whether anything remains uncertain, and the next step if blocked.
81
- State that no sync or remote connectivity check was performed; do not claim a live runtime update without evidence.
78
+ Report what changed or what was verified, whether anything remains uncertain, and the next step if blocked. Distinguish local evidence from a confirmed remote comparison. Do not claim a live runtime update without evidence.
@@ -79,13 +79,13 @@ Escape closes the screen without undoing successful saves.
79
79
  Complex values retain their input/review flows.
80
80
  This navigation change does not alter schema, defaults, automatic-sync behavior, or explicit opt-ins.
81
81
 
82
- The main menu shows cached status separately from transfer, inspection, and management actions. **Check remote status** and **View differences** run their checks only when selected. **Check remote status** (`/sync status`) shows local and remote changes first, or indicates that no previous sync was recorded. Storage, snapshot details, and sync scope follow.
83
- **Last applied** shows a compact snapshot ID and marks application time as unavailable instead of substituting snapshot creation time. **History** shows the full IDs.
82
+ The main menu shows cached status separately from transfer, inspection, and management actions. **View differences** (`/sync diff`) reads current file differences only when selected. It works with Debug mode off and is not a comparison against the last sync.
83
+ **Last applied snapshot** shows an ID, not an application time. The menu shortens long IDs; **History** shows the full IDs.
84
84
  See the [TUI behavior contract](https://github.com/narumiruna/pi-extensions/blob/main/packages/pi-sync/docs/tui-contract.md) for scopes and transfer branches.
85
85
 
86
86
  RPC reports the manual settings path and offers the existing setup/connection catalog dialogs, not the TUI preference or masked-credential editors.
87
87
  Print/JSON do not support `/sync`; use the private settings file directly.
88
- Command hints list `/sync status`, `/sync diff`, and `/sync help`.
88
+ Use `/sync help` to list supported commands.
89
89
 
90
90
  ### Complete version 3 example
91
91
 
@@ -192,7 +192,7 @@ The setting still permits automatic shutdown pushes of selected content when `se
192
192
  Reload skips shutdown push.
193
193
  Settings changes apply to subsequent operations; changing this setting does not schedule another startup check until the next session start.
194
194
  Foreground `/sync` cancels a pending check before opening Settings.
195
- The check deadline is 30 seconds plus bounded cleanup, with manual retry through `/sync status`; this one-shot policy has no polling.
195
+ The check deadline is 30 seconds plus bounded cleanup. This one-shot policy has no polling. For a fresh baseline-relative comparison, ask Pi to recheck in [Debug mode](#debug-mode).
196
196
  See [Background startup checks](https://github.com/narumiruna/pi-extensions/blob/main/packages/pi-sync/README.md#background-startup-checks) for recovery and Git cache exceptions.
197
197
 
198
198
  New TUI setups recommend **Selected paths**: Recommended includes the nine non-session Pi roots below, and Minimal includes only `settings.json` and `AGENTS.md`. Agent-directory scope is an explicit alternative.
@@ -236,7 +236,7 @@ This is not permission to sync, change retry policy, or erase recovery evidence.
236
236
  Retry and blocked states keep a short reason: `temp` (temporary service/network failure), `busy` (lock contention), `stale` (changed evidence), `auth` (authentication), `storage` (local storage), `review` (safety barrier), `model` (resolver/model failure or exhausted candidate attempts), `limit` (request-window allowance), or `unknown` (unclassified failure).
237
237
  Settings or private-state repair uses `repair`.
238
238
  A request-window limit is not a currency budget; exhausted attempts for one candidate remain a model block, not a timer-based allowance reset.
239
- Use the existing manager and **Check remote status** guidance to inspect recovery requirements rather than treating a short marker as a complete diagnosis.
239
+ Use the manager and [local troubleshooting](#local-troubleshooting) to inspect recovery requirements rather than treating a short marker as a complete diagnosis.
240
240
 
241
241
  <a id="debug-startup-timings"></a>
242
242
 
@@ -244,7 +244,13 @@ Use the existing manager and **Check remote status** guidance to inspect recover
244
244
 
245
245
  The top-level user setting `debug` is an optional boolean and defaults to `false` for every setup. Use **/sync → Settings → Debug mode** or edit `<getAgentDir()>/pi-sync.json` (normally `~/.pi/agent/pi-sync.json`). UI changes save immediately through the existing ordered, atomic settings writer. There is no project or environment override.
246
246
 
247
- Pi uses the saved value from session start, including `/reload`, new, resume, and fork, for client logging and timing display. The daemon uses the agent directory's validated setting for file logging, not a connected client's value. It applies changes at the next applicable owner or job boundary without a restart. A missing or false `debug` value does not enable logging; the daemon can skip records when it cannot validate settings. Turning on Debug mode does not start a new check or transfer, or grant permission for work after Pi exits.
247
+ Pi uses the saved value from session start, including `/reload`, new, resume, and fork, for client logging, timing display, and `pi_sync_debug` availability in TUI and RPC. The daemon uses the agent directory's validated setting for file logging, not a connected client's value. It applies changes at the next applicable owner or job boundary without a restart. A missing or false `debug` value does not enable logging; the daemon can skip records when it cannot validate settings. Turning on Debug mode does not start a new check or transfer, or grant permission for work after Pi exits.
248
+
249
+ #### Ask Pi to explain a check
250
+
251
+ `pi_sync_debug` is available only in TUI and RPC sessions started or reloaded with Debug mode on, subject to Pi's tool allowlist. `latest` reads the most recent matching summary within the last 64 KiB of the private log. `recheck` reads the current setup's remote storage and returns a sanitized summary without prompting. The tool does not publish, apply, test writes, or repair History.
252
+
253
+ A summary can include times, where the check came from, whether a previous sync was recorded, which side changed, whether file selections agree, file counts, and fixed failure categories. Stale, unavailable, and not-run results are not evidence of equality. Results omit secrets, setup names and fingerprints, addresses, paths, device names, snapshot IDs, content, and raw errors or log lines.
248
254
 
249
255
  #### Shared log
250
256
 
@@ -284,17 +290,12 @@ The global `skipSecretScan` setting accepts a boolean and defaults to `false`, i
284
290
  Set it through **/sync → Settings → Skip secret scan**; changes are saved immediately and apply to subsequent pushes for every sync setup, including automatic pushes.
285
291
  When `true`, pushes skip the local secret scan; other safety checks and confirmations remain unchanged.
286
292
  Enable it only after reviewing the destination and selected content because files containing secrets can be uploaded.
287
- `/sync doctor` still scans and reports possible secrets regardless of this setting.
288
293
 
289
294
  ### Diagnostics
290
295
 
291
- **/sync → Diagnostics** and `/sync doctor` use the same route. The report puts findings that need attention first, followed by local checks, storage checks, and sync scope.
292
- S3/R2 reads the selected setup's latest pointer with a ten-second deadline and bounded error details; it never writes, deletes, lists buckets, or changes settings.
293
- HTTP success does not validate snapshot contents or write access.
294
- `NoSuchKey` indicates no snapshot at the path; `NoSuchBucket` indicates a missing bucket; other 404 responses cannot distinguish the two.
295
- Authentication and transport failures give credentials/permissions or address/network guidance.
296
- Git reads remote snapshots and checks its local cache; write access is not tested.
297
- WebDAV retains its isolated conditional-write/cleanup probe and repair of a missing active-snapshot history entry.
296
+ Use **/sync → Settings** to review sync setups and storage connections. Use **View differences** to compare files without transferring them, or ask Pi to use the [Debug tool](#ask-pi-to-explain-a-check) for a baseline-relative check. Neither read proves that storage accepts writes. Push keeps its existing safety checks, including temporary conditional-write probes on WebDAV and S3/R2.
297
+
298
+ If a WebDAV publication activated a snapshot but left its entry missing, open **/sync → History** and select **Repair active snapshot history** when offered. The confirmation names the setup, destination, and snapshot. After approval, Pi Sync runs an isolated conditional-write probe and cleans it up, then adds the missing entry if it is still needed and safe. The active snapshot and local files stay unchanged. This action is separate from diagnostics and is never automatic.
298
299
 
299
300
  ### Local troubleshooting
300
301
 
@@ -306,9 +307,9 @@ Use the first concrete error, not a generic recovery hint appended to it. Start
306
307
  | **Agent directory changed or has an unsafe filesystem layout** | The local scan could not establish a stable filesystem view. Use file metadata to check the agent root, Pi's `settings.json`, the effective session directory (including any `--session-dir` override), and in-scope paths. Symlinks in the session directory path and hard-linked candidate files can trigger this error; ordinary symlinks encountered in the directory scan are skipped. Check whether another Pi process or editor is changing files during the scan. Do not change synchronization settings unless the evidence identifies a relevant setting; this error alone does not identify a path or field. |
307
308
  | **Transfer blocked by size limits** | Check the reported paths and byte counts. Use `/sync diff`, then narrow the selection or review a different source. See [transfer size limits](#transfer-size-limits). |
308
309
  | **Malformed or unsupported settings** | Check the canonical path and documented version and field constraints. Preserve the original private bytes and follow [settings recovery](#unsupported-old-settings-and-recovery); do not replace the document with defaults. |
309
- | **Backend access or publication failure** | Use the reported error class to distinguish credentials, a missing location, transport, and publication safety. A 404 alone does not identify which remote resource is missing. If local checks are insufficient, explain the backend-specific effects of [Diagnostics](#diagnostics) and leave that action to the user. |
310
+ | **Backend access or publication failure** | Use the reported error class to distinguish credentials, a missing location, transport, and publication safety. A 404 alone does not identify which remote resource is missing. If local checks are insufficient, explain the [read and recovery options](#diagnostics). Do not treat a successful read as proof of write access. |
310
311
 
311
- A local check does not verify remote connectivity or permissions. Diagnostics can stop at the same local scan error before backend checks run.
312
+ A local check does not verify remote connectivity or permissions. A fresh comparison can also stop at a local scan error before contacting storage.
312
313
 
313
314
  ### Retired ignore-file policy
314
315
 
@@ -759,7 +760,7 @@ Keep the directory as private evidence; do not delete it to repair a transfer.
759
760
 
760
761
  The existing raw status key shows waiting, checking/syncing, scheduled retry, another local owner, or a stable blocked reason.
761
762
  A compatible Statusline uses the [quiet presentation described above](#status-display); normal hidden standby does not mean monitoring or another owner's work has stopped.
762
- **Check remote status** and the manager show advisory ownership, the last successful background check/transfer and safe next actions.
763
+ The manager shows cached observations and safe next actions; use `/sync daemon status` for current daemon ownership.
763
764
  Status also shows normalized rolling-window usage, the next window allowance, exhausted-candidate counts, serialized accounting bytes/capacity and on-disk bytes.
764
765
  Window allowance is not dispatch permission: candidate, capacity, ownership and safety checks still apply.
765
766
  Status normalization affects only the detached read; it does not expire durable calls, reserve requests, create private directories or reset limits.
@@ -863,7 +864,7 @@ Older codecs refuse version-3 partial snapshots and older settings readers refus
863
864
  `/sync conflicts` (also the conditional main **Review unresolved conflicts** action) shows private versions only when requested, in TUI or paginated RPC.
864
865
  It rejects confirmation/force bypass flags, reviews an entire group, then separately asks for local or remote authority.
865
866
  It revalidates the reviewed artifact fingerprint, group versions, baseline, configuration, ownership and current observed head before apply; stale/cancelled review performs no transfer.
866
- The manager always reports unresolved groups and the observed head separately from Last applied.
867
+ The manager always reports unresolved groups and the observed head separately from **Last applied snapshot**.
867
868
  Repeated unchanged conflicts retain one stable opaque identity rather than creating more evidence or modal reviews.
868
869
 
869
870
  Artifacts are private immutable records below denied state storage with a 192 MiB/record cap; accepted ancestor records use the same bound, and actual content strategies have smaller limits.
@@ -889,7 +890,7 @@ Recovery:
889
890
  1. retain the old file byte-for-byte;
890
891
  2. move it aside manually;
891
892
  3. create a new version 3 document or run the setup manager;
892
- 4. run `/sync doctor`, inspect the exact storage path, and review the first pull or push;
893
+ 4. review **Storage location** in **/sync → Settings**, inspect file differences with `/sync diff`, and review the first pull or push;
893
894
  5. restore the retained file and a compatible older package only if rolling back.
894
895
 
895
896
  If your processes reject a newer settings version, keep the document and use compatible Pi Sync and daemon builds. In particular, [clearing transfer size limits](#transfer-size-limits) never downgrades version 9. Do not use the recovery steps above to replace a newer document.