@narumitw/pi-sync 0.60.4 → 0.61.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 (88) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +14 -6
  3. package/dist/chunks/chunk-2JHAN3ZO.ts +139 -0
  4. package/dist/chunks/chunk-2JHAN3ZO.ts.map +7 -0
  5. package/dist/chunks/chunk-2ZGV5KNC.ts +274 -0
  6. package/dist/chunks/chunk-2ZGV5KNC.ts.map +7 -0
  7. package/dist/chunks/{chunk-LAXTCSX4.ts → chunk-4KTJLJSJ.ts} +117 -132
  8. package/dist/chunks/chunk-4KTJLJSJ.ts.map +7 -0
  9. package/dist/chunks/chunk-4SR3ZYHA.ts +14 -0
  10. package/dist/chunks/chunk-4SR3ZYHA.ts.map +7 -0
  11. package/dist/chunks/{chunk-VQRDL3SY.ts → chunk-E3YLRLJM.ts} +155 -27
  12. package/dist/chunks/chunk-E3YLRLJM.ts.map +7 -0
  13. package/dist/chunks/{chunk-KPWZNMKM.ts → chunk-ECYCNZOE.ts} +1 -5
  14. package/dist/chunks/chunk-ECYCNZOE.ts.map +7 -0
  15. package/dist/chunks/{chunk-IGDI5CIH.ts → chunk-EMVZL4PH.ts} +2 -2
  16. package/dist/chunks/{chunk-OVCP2SOB.ts → chunk-H7VOTY5N.ts} +21 -8
  17. package/dist/chunks/chunk-H7VOTY5N.ts.map +7 -0
  18. package/dist/chunks/{chunk-SE7HHBKH.ts → chunk-JVFCVPPD.ts} +105 -51
  19. package/dist/chunks/chunk-JVFCVPPD.ts.map +7 -0
  20. package/dist/chunks/{chunk-MCUZFUHY.ts → chunk-PJMM75W5.ts} +6 -6
  21. package/dist/chunks/{chunk-RJZIKZI3.ts → chunk-S7F4FOAS.ts} +11 -6
  22. package/dist/chunks/chunk-S7F4FOAS.ts.map +7 -0
  23. package/dist/chunks/{chunk-6W2SNZ5P.ts → chunk-YQSFJLJ3.ts} +6 -2
  24. package/dist/chunks/{chunk-6W2SNZ5P.ts.map → chunk-YQSFJLJ3.ts.map} +3 -3
  25. package/dist/chunks/{chunk-V4AMI3VL.ts → chunk-ZVGRZD4C.ts} +9 -1
  26. package/dist/chunks/chunk-ZVGRZD4C.ts.map +7 -0
  27. package/dist/chunks/{command-handler-TMH4US44.ts → command-handler-K4XJOGYC.ts} +41 -37
  28. package/dist/chunks/{command-handler-TMH4US44.ts.map → command-handler-K4XJOGYC.ts.map} +2 -2
  29. package/dist/chunks/{conflict-review-QGUCODDH.ts → conflict-review-IGKY2TOJ.ts} +4 -4
  30. package/dist/chunks/{file-selection-DD6X4J2K.ts → file-selection-MGGVOKM7.ts} +26 -13
  31. package/dist/chunks/file-selection-MGGVOKM7.ts.map +7 -0
  32. package/dist/chunks/{manager-result-dispatcher-YVVD44QD.ts → manager-result-dispatcher-4VJVDEUD.ts} +8 -7
  33. package/dist/chunks/{manager-ui-Q54OHOPR.ts → manager-ui-KYQ5AZJS.ts} +134 -203
  34. package/dist/chunks/manager-ui-KYQ5AZJS.ts.map +7 -0
  35. package/dist/chunks/{remote-selection-ui-ODSUHX5N.ts → remote-selection-ui-W3KOZM3W.ts} +7 -6
  36. package/dist/chunks/{setup-switch-SPZE7HIQ.ts → setup-switch-D6K6PBPC.ts} +3 -3
  37. package/dist/chunks/{setup-wizard-5JYKAEIT.ts → setup-wizard-4DYUDHJR.ts} +13 -11
  38. package/dist/chunks/setup-wizard-4DYUDHJR.ts.map +7 -0
  39. package/dist/chunks/{sync-inspection-ECUTWISE.ts → sync-inspection-J3CRBORL.ts} +6 -6
  40. package/dist/chunks/{sync-operations-REXODWZB.ts → sync-operations-BVWYYKH3.ts} +4 -4
  41. package/dist/index.ts +28 -24
  42. package/dist/index.ts.map +2 -2
  43. package/docs/daemon-migration.md +6 -0
  44. package/package.json +4 -4
  45. package/skills/configure-pi-sync/references/configuration.md +59 -32
  46. package/src/commands/command-execution.ts +7 -1
  47. package/src/daemon/pi-client.ts +79 -22
  48. package/src/daemon/queue-release-ui.ts +88 -0
  49. package/src/sync/sync-policy.ts +5 -0
  50. package/src/sync-extension.ts +6 -2
  51. package/src/ui/agent-mode-setting.ts +9 -1
  52. package/src/ui/excluded-paths-ui.ts +154 -2
  53. package/src/ui/file-selection.ts +12 -7
  54. package/src/ui/manager-state.ts +13 -8
  55. package/src/ui/remote-selection-ui.ts +120 -27
  56. package/src/ui/settings-frame.ts +2 -8
  57. package/src/ui/settings-ui.ts +51 -26
  58. package/src/ui/setup/directory-rules.ts +81 -0
  59. package/src/ui/setup/git-ui.ts +14 -24
  60. package/src/ui/setup/s3-ui.ts +13 -26
  61. package/src/ui/setup/setup-actions.ts +0 -4
  62. package/src/ui/setup/setup-prompts.ts +99 -17
  63. package/src/ui/setup/setup-switcher.ts +4 -2
  64. package/src/ui/setup/setup-wizard.ts +5 -4
  65. package/src/ui/setup/webdav-ui.ts +13 -27
  66. package/src/ui/storage-connections-ui.ts +2 -2
  67. package/src/ui/sync-attention.ts +8 -3
  68. package/src/ui/sync-format.ts +8 -1
  69. package/src/ui/sync-setups-ui.ts +5 -3
  70. package/src/ui/sync-status.ts +27 -7
  71. package/dist/chunks/chunk-KPWZNMKM.ts.map +0 -7
  72. package/dist/chunks/chunk-LAXTCSX4.ts.map +0 -7
  73. package/dist/chunks/chunk-OVCP2SOB.ts.map +0 -7
  74. package/dist/chunks/chunk-RJZIKZI3.ts.map +0 -7
  75. package/dist/chunks/chunk-SE7HHBKH.ts.map +0 -7
  76. package/dist/chunks/chunk-V4AMI3VL.ts.map +0 -7
  77. package/dist/chunks/chunk-VQRDL3SY.ts.map +0 -7
  78. package/dist/chunks/file-selection-DD6X4J2K.ts.map +0 -7
  79. package/dist/chunks/manager-ui-Q54OHOPR.ts.map +0 -7
  80. package/dist/chunks/setup-wizard-5JYKAEIT.ts.map +0 -7
  81. /package/dist/chunks/{chunk-IGDI5CIH.ts.map → chunk-EMVZL4PH.ts.map} +0 -0
  82. /package/dist/chunks/{chunk-MCUZFUHY.ts.map → chunk-PJMM75W5.ts.map} +0 -0
  83. /package/dist/chunks/{conflict-review-QGUCODDH.ts.map → conflict-review-IGKY2TOJ.ts.map} +0 -0
  84. /package/dist/chunks/{manager-result-dispatcher-YVVD44QD.ts.map → manager-result-dispatcher-4VJVDEUD.ts.map} +0 -0
  85. /package/dist/chunks/{remote-selection-ui-ODSUHX5N.ts.map → remote-selection-ui-W3KOZM3W.ts.map} +0 -0
  86. /package/dist/chunks/{setup-switch-SPZE7HIQ.ts.map → setup-switch-D6K6PBPC.ts.map} +0 -0
  87. /package/dist/chunks/{sync-inspection-ECUTWISE.ts.map → sync-inspection-J3CRBORL.ts.map} +0 -0
  88. /package/dist/chunks/{sync-operations-REXODWZB.ts.map → sync-operations-BVWYYKH3.ts.map} +0 -0
package/dist/index.ts CHANGED
@@ -4,45 +4,45 @@ import {
4
4
  createSyncAttentionController,
5
5
  readStateForConfig,
6
6
  syncStateFingerprint
7
- } from "./chunks/chunk-RJZIKZI3.ts";
8
- import "./chunks/chunk-HEB6YT64.ts";
7
+ } from "./chunks/chunk-S7F4FOAS.ts";
8
+ import {
9
+ completeSyncArguments,
10
+ setSyncSetupCompletions,
11
+ splitArgs
12
+ } from "./chunks/chunk-HLCML3OW.ts";
9
13
  import {
10
14
  withStateDirectoryAccess
11
15
  } from "./chunks/chunk-RNIEVDTR.ts";
12
16
  import {
13
17
  snapshotOptionsForContext
14
18
  } from "./chunks/chunk-SMVKMYLK.ts";
15
- import {
16
- loadConfigForCheck,
17
- syncCheckConfigFingerprint
18
- } from "./chunks/chunk-277VHM2P.ts";
19
19
  import {
20
20
  bindPiDaemonClient,
21
21
  installPiDaemonHost,
22
22
  piDaemonClient,
23
23
  withPiDaemonClient
24
- } from "./chunks/chunk-VQRDL3SY.ts";
25
- import {
26
- configureSyncStatus,
27
- createSyncStatusPublisher,
28
- setSyncStatus
29
- } from "./chunks/chunk-OVCP2SOB.ts";
30
- import {
31
- completeSyncArguments,
32
- setSyncSetupCompletions,
33
- splitArgs
34
- } from "./chunks/chunk-HLCML3OW.ts";
24
+ } from "./chunks/chunk-E3YLRLJM.ts";
35
25
  import {
36
26
  combineSignals,
37
27
  throwIfAborted
38
28
  } from "./chunks/chunk-S3R3W3KF.ts";
29
+ import "./chunks/chunk-HEB6YT64.ts";
30
+ import {
31
+ loadConfigForCheck,
32
+ syncCheckConfigFingerprint
33
+ } from "./chunks/chunk-277VHM2P.ts";
34
+ import {
35
+ configureSyncStatus,
36
+ createSyncStatusPublisher,
37
+ setSyncStatus
38
+ } from "./chunks/chunk-H7VOTY5N.ts";
39
39
  import {
40
40
  errorMessage
41
41
  } from "./chunks/chunk-ZIL6PW5L.ts";
42
+ import "./chunks/chunk-ZVGRZD4C.ts";
42
43
  import {
43
44
  safeTerminalText
44
45
  } from "./chunks/chunk-2JNFEZ3V.ts";
45
- import "./chunks/chunk-V4AMI3VL.ts";
46
46
 
47
47
  // src/sync/agent-policy.ts
48
48
  import {
@@ -289,12 +289,12 @@ function createStartupCheck(loaders, attention, timeoutMs = 3e4, publish) {
289
289
  // src/sync/sync-loaders.ts
290
290
  function createSyncLoaders(dependencies) {
291
291
  const loaders = {
292
- commands: cachedModuleLoader(dependencies.loadCommandHandler ?? (() => import("./chunks/command-handler-TMH4US44.ts"))),
293
- inspection: cachedModuleLoader(dependencies.loadSyncInspection ?? (() => import("./chunks/sync-inspection-ECUTWISE.ts"))),
294
- setupSwitch: cachedModuleLoader(dependencies.loadSetupSwitch ?? (() => import("./chunks/setup-switch-SPZE7HIQ.ts"))),
292
+ commands: cachedModuleLoader(dependencies.loadCommandHandler ?? (() => import("./chunks/command-handler-K4XJOGYC.ts"))),
293
+ inspection: cachedModuleLoader(dependencies.loadSyncInspection ?? (() => import("./chunks/sync-inspection-J3CRBORL.ts"))),
294
+ setupSwitch: cachedModuleLoader(dependencies.loadSetupSwitch ?? (() => import("./chunks/setup-switch-D6K6PBPC.ts"))),
295
295
  snapshot: cachedModuleLoader(dependencies.loadSnapshot ?? (() => import("./chunks/snapshot-5HY3M2NL.ts"))),
296
296
  syncState: cachedModuleLoader(dependencies.loadSyncState ?? (() => import("./chunks/sync-state-2LMIXJ2C.ts"))),
297
- operations: cachedModuleLoader(dependencies.loadSyncOperations ?? (() => import("./chunks/sync-operations-REXODWZB.ts")))
297
+ operations: cachedModuleLoader(dependencies.loadSyncOperations ?? (() => import("./chunks/sync-operations-BVWYYKH3.ts")))
298
298
  };
299
299
  return loaders;
300
300
  }
@@ -418,11 +418,11 @@ function sync(pi, dependencies = {}) {
418
418
  }
419
419
  });
420
420
  pi.on("session_start", async (_event, ctx) => {
421
- const releaseStatus = status.start(ctx);
422
421
  const previousClient = owner;
423
422
  shutdownAbort?.abort(new DOMException("Session replaced", "AbortError"));
424
423
  shutdownAbort = void 0;
425
424
  sessionAbort.abort(new DOMException("Session replaced", "AbortError"));
425
+ const releaseStatus = status.start(ctx);
426
426
  sessionAbort = new AbortController();
427
427
  const signal = sessionAbort.signal;
428
428
  const client = bindPiDaemonClient(ctx, signal, publishTimings);
@@ -464,12 +464,16 @@ function sync(pi, dependencies = {}) {
464
464
  });
465
465
  try {
466
466
  const ready = await initialization;
467
- if (ready === false) releaseStatus();
467
+ if (ready === false) {
468
+ client.disableQueueReleaseUI();
469
+ releaseStatus();
470
+ }
468
471
  if (ready && !signal.aborted && owner === client && !(ready.continuous && ready.agentMode) && (ready.automatic || startupTransferEnabled(ready)))
469
472
  await withPiDaemonClient(ctx, async () => {
470
473
  check.start(ctx, signal, ready);
471
474
  });
472
475
  } catch (error) {
476
+ client.disableQueueReleaseUI();
473
477
  releaseStatus();
474
478
  throw error;
475
479
  }
package/dist/index.ts.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/sync/agent-policy.ts", "../src/settings/config-errors.ts", "../src/sync/startup-timings.ts", "../src/sync/automatic-sync.ts", "../src/sync/startup-check.ts", "../src/sync/sync-loaders.ts", "../src/ui/startup-timings-entry.ts", "../src/sync-extension.ts"],
4
- "sourcesContent": ["export type * from \"@narumitw/pi-sync-daemon/engine/sync/agent-policy\";\nexport {\n AGENT_INPUT_BYTES,\n AGENT_MAX_ATTEMPTS,\n AGENT_MAX_TOKENS,\n AGENT_MAX_UNITS,\n AGENT_OUTPUT_BYTES,\n AGENT_TIMEOUT_MS,\n startupTransferEnabled,\n} from \"@narumitw/pi-sync-daemon/engine/sync/agent-policy\";\n", "export type * from \"@narumitw/pi-sync-daemon/engine/settings/config-errors\";\nexport { isMissingConfigError } from \"@narumitw/pi-sync-daemon/engine/settings/config-errors\";\n", "export type * from \"@narumitw/pi-sync-daemon/engine/sync/startup-timings\";\nexport { createStartupTimings } from \"@narumitw/pi-sync-daemon/engine/sync/startup-timings\";\n", "import type { ExtensionContext } from \"@earendil-works/pi-coding-agent\";\nimport { setSyncSetupCompletions } from \"../commands/command.js\";\nimport { piDaemonClient } from \"../daemon/pi-client.js\";\nimport { isMissingConfigError } from \"../settings/config-errors.js\";\nimport type { AnySyncConfig, PiSyncSettingsV3 } from \"../settings/settings-types.js\";\nimport { configureSyncStatus } from \"../ui/sync-status.js\";\nimport { safeTerminalText } from \"../ui/terminal-text.js\";\nimport { throwIfAborted } from \"./signals.js\";\nimport { createStartupTimings, type StartupTimingPublisher } from \"./startup-timings.js\";\nimport { errorMessage } from \"./sync-errors.js\";\nimport type { SyncLoaders } from \"./sync-loaders.js\";\n\nexport async function startSession(\n ctx: ExtensionContext,\n signal: AbortSignal,\n publish?: StartupTimingPublisher,\n): Promise<{ debug: boolean; config?: AnySyncConfig } | undefined> {\n throwIfAborted(signal);\n const client = piDaemonClient(ctx);\n // One-off sessions only protect their files in an already existing service.\n // They never launch it or authorize observations, transfers, or model work.\n if (!ctx.hasUI || ![\"tui\", \"rpc\"].includes(ctx.mode)) {\n await client.attachExisting();\n throwIfAborted(signal);\n return { debug: false };\n }\n const timings = createStartupTimings(publish);\n const document = await timings.measure(\"settings read\", () => client.readSettings());\n throwIfAborted(signal);\n configureSyncStatus(ctx, (document?.parsed.showStatus as boolean | undefined) ?? true);\n const { stateDirectoryMigrationNotice } = await import(\"../state/state-directory.js\");\n const notice = stateDirectoryMigrationNotice();\n const { pendingTransactionEntries } = await import(\"../snapshot/snapshot-transaction-directory.js\");\n const recoveryNeeded = (await pendingTransactionEntries()).some((entry) => entry.isDirectory());\n throwIfAborted(signal);\n if (!(await client.configured()) && !recoveryNeeded) {\n if (notice) ctx.ui.notify(notice, \"warning\");\n setSyncSetupCompletions([]);\n const debug = document?.parsed.debug === true;\n await client.markReady(debug);\n timings.publish(ctx, debug, signal, \"local initialization\", \"completed\");\n return { debug };\n }\n throwIfAborted(signal);\n const result = (await client.run(\"initialize\", {}, signal)) as {\n debug: boolean;\n config?: AnySyncConfig;\n settings?: PiSyncSettingsV3;\n handoverRequired: boolean;\n };\n throwIfAborted(signal);\n configureSyncStatus(ctx, result.settings?.showStatus ?? true);\n setSyncSetupCompletions(Object.keys(result.settings?.syncSetups ?? {}).sort((a, b) => a.localeCompare(b)));\n await client.markReady(result.debug);\n throwIfAborted(signal);\n if (result.handoverRequired) {\n ctx.ui.notify(\n \"pi-sync: close or upgrade older Pi processes, then use /sync to review daemon handover. No automatic transfer is authorized yet.\",\n \"warning\",\n );\n return { debug: result.debug };\n }\n return { debug: result.debug, config: result.config };\n}\nexport async function autoPushSessions(ctx: ExtensionContext, signal: AbortSignal, _loaders: SyncLoaders) {\n try {\n const client = piDaemonClient(ctx);\n if (!(await client.configured())) return;\n throwIfAborted(signal);\n await client.run(\n \"shutdown\",\n { args: [], yes: true, force: false, stale: false, silent: true, reload: false },\n signal,\n );\n } catch (error) {\n if (signal.aborted || isMissingConfigError(error)) return;\n ctx.ui.notify(`pi-sync session push skipped: ${safeTerminalText(errorMessage(error))}`, \"warning\");\n }\n}\n", "import type { ExtensionContext } from \"@earendil-works/pi-coding-agent\";\nimport { loadConfigForCheck, syncCheckConfigFingerprint } from \"../settings/config.js\";\nimport { isMissingConfigError } from \"../settings/config-errors.js\";\nimport type { AnySyncConfig } from \"../settings/settings-types.js\";\nimport { snapshotOptionsForContext } from \"../snapshot/session-paths.js\";\nimport { withStateDirectoryAccess } from \"../state/state-directory.js\";\nimport { readStateForConfig, syncStateFingerprint } from \"../state/sync-state-store.js\";\nimport type { SyncAttentionController } from \"../ui/sync-attention.js\";\nimport { setSyncStatus } from \"../ui/sync-status.js\";\nimport { safeTerminalText } from \"../ui/terminal-text.js\";\nimport { startupTransferEnabled } from \"./agent-policy.js\";\nimport { combineSignals, throwIfAborted } from \"./signals.js\";\nimport { createStartupTimings, type StartupTimingPublisher } from \"./startup-timings.js\";\nimport { errorMessage } from \"./sync-errors.js\";\nimport type { SyncLoaders } from \"./sync-loaders.js\";\n\n/** One owned task per extension session, never keyed by the shared headless UI. */\nexport function createStartupCheck(\n loaders: SyncLoaders,\n attention: SyncAttentionController,\n timeoutMs = 30_000,\n publish?: StartupTimingPublisher,\n) {\n let active:\n | {\n controller: AbortController;\n promise: Promise<void>;\n owner: ExtensionContext[\"sessionManager\"];\n transfer: boolean;\n }\n | undefined;\n\n let pending: { ctx: ExtensionContext; signal: AbortSignal; config: AnySyncConfig } | undefined;\n\n const controllerApi = {\n async interrupt(ctx: ExtensionContext) {\n const task = active;\n if (!task?.transfer || task.owner !== ctx.sessionManager) return;\n task.controller.abort(new DOMException(\"Agent became busy\", \"AbortError\"));\n await task.promise;\n },\n settled(ctx: ExtensionContext) {\n const queued = pending;\n if (!queued || queued.ctx.sessionManager !== ctx.sessionManager || queued.signal.aborted || !ctx.isIdle()) return;\n pending = undefined;\n controllerApi.start(ctx, queued.signal, queued.config);\n },\n start(ctx: ExtensionContext, sessionSignal: AbortSignal, initialConfig?: AnySyncConfig) {\n if (!ctx.hasUI || sessionSignal.aborted) return;\n if (initialConfig && startupTransferEnabled(initialConfig) && !ctx.isIdle()) {\n pending = { ctx, signal: sessionSignal, config: initialConfig };\n return;\n }\n if (active) throw new Error(\"Previous startup check has not been drained.\");\n const timings = createStartupTimings(publish);\n const controller = new AbortController();\n const signal = combineSignals(sessionSignal, controller.signal);\n const task = {\n controller,\n owner: ctx.sessionManager,\n promise: Promise.resolve(),\n transfer: Boolean(initialConfig && startupTransferEnabled(initialConfig)),\n };\n active = task;\n const isCurrent = () => !sessionSignal.aborted && active === task && task.owner === ctx.sessionManager;\n const timer = setTimeout(\n () => controller.abort(new DOMException(\"Startup check timed out\", \"TimeoutError\")),\n timeoutMs,\n );\n timer.unref();\n let config: AnySyncConfig | undefined;\n let checking = false;\n let stopped = false;\n // Handle every detached rejection here; Pi's awaited event runner cannot catch it.\n task.promise = Promise.resolve()\n .then(async () => {\n try {\n throwIfAborted(signal);\n config = initialConfig ?? (await loadConfigForCheck());\n task.transfer = startupTransferEnabled(config);\n throwIfAborted(signal);\n if (!config.automatic && !startupTransferEnabled(config)) return;\n const captured = config;\n const identity = syncCheckConfigFingerprint(captured);\n checking = true;\n setSyncStatus(ctx, \"sync ...\", { activity: \"checking\" });\n const { inspectSync } = await timings.measure(\"inspection import\", () => loaders.inspection());\n throwIfAborted(signal);\n const currentConfig = await loadConfigForCheck();\n throwIfAborted(signal);\n if (syncCheckConfigFingerprint(currentConfig) !== identity) return;\n // The daemon owns the operation and cache guards.\n const inspection = await timings.measure(\"inspection and guards\", () =>\n inspectSync(captured, snapshotOptionsForContext(ctx, captured), signal, undefined, timings),\n );\n throwIfAborted(signal);\n const latest = await loadConfigForCheck();\n throwIfAborted(signal);\n if (syncCheckConfigFingerprint(latest) !== identity) return;\n const state = await withStateDirectoryAccess(() => readStateForConfig(latest));\n throwIfAborted(signal);\n if (syncStateFingerprint(state) !== inspection.stateIdentity || !isCurrent()) return;\n attention.observe({\n setupName: captured.setupName,\n configIdentity: identity,\n checkedAt: new Date().toISOString(),\n inspection,\n automaticTransfer: startupTransferEnabled(captured),\n });\n if (\n startupTransferEnabled(captured) &&\n !inspection.firstSync &&\n inspection.head &&\n inspection.selectionState?.kind === \"same\"\n ) {\n const operations = await timings.measure(\"operations import\", () => loaders.operations());\n throwIfAborted(signal);\n if (!isCurrent()) return;\n if (!ctx.isIdle()) {\n pending = { ctx, signal: sessionSignal, config: captured };\n return;\n }\n await timings.measure(\"automatic transfer\", () =>\n operations.syncBoth(ctx, {\n args: [],\n yes: true,\n force: false,\n stale: false,\n silent: true,\n reload: false,\n auto: true,\n signal,\n startupTimings: timings,\n onCommit: () => attention.clearObservation(),\n }),\n );\n throwIfAborted(signal);\n if (!isCurrent()) return;\n attention.clearObservation();\n return;\n }\n attention.observe({\n setupName: captured.setupName,\n configIdentity: identity,\n checkedAt: new Date().toISOString(),\n inspection,\n automaticTransfer: startupTransferEnabled(captured),\n });\n if (ctx.mode === \"rpc\") attention.notifyObservation(ctx);\n } catch (error) {\n stopped = true;\n if (!isCurrent() || sessionSignal.aborted || isMissingConfigError(error)) return;\n if (signal.aborted && controller.signal.reason?.name !== \"TimeoutError\") return;\n // A settings edit invalidates failures as well as successful observations.\n if (config) {\n const latest = await loadConfigForCheck().catch(() => undefined);\n if (!isCurrent() || (signal.aborted && controller.signal.reason?.name !== \"TimeoutError\")) return;\n if (!latest || syncCheckConfigFingerprint(latest) !== syncCheckConfigFingerprint(config)) return;\n }\n ctx.ui.notify(\n config && startupTransferEnabled(config)\n ? `pi-sync automatic transfer stopped: ${safeTerminalText(errorMessage(error))}. Run /sync to review or reconcile retained recovery evidence. No resources were reloaded.`\n : `pi-sync startup check skipped: ${safeTerminalText(errorMessage(error))}. Run /sync status to retry. No startup transfer was performed.`,\n \"warning\",\n );\n } finally {\n clearTimeout(timer);\n if (isCurrent() && checking) {\n if (!signal.aborted || controller.signal.reason?.name === \"TimeoutError\") {\n const latest = await loadConfigForCheck().catch(() => undefined);\n if (isCurrent()) {\n if (signal.aborted && controller.signal.reason?.name !== \"TimeoutError\")\n setSyncStatus(ctx, undefined);\n else if (\n config &&\n latest &&\n syncCheckConfigFingerprint(latest) === syncCheckConfigFingerprint(config)\n )\n await attention.publish(ctx, sessionSignal);\n else attention.reset(ctx);\n }\n } else setSyncStatus(ctx, undefined);\n }\n if (isCurrent()) {\n timings.publish(\n ctx,\n config?.debug ?? false,\n sessionSignal,\n \"background startup\",\n signal.aborted || stopped ? \"stopped\" : \"completed\",\n );\n }\n if (active === task) active = undefined;\n }\n })\n .catch(() => {\n // UI teardown can itself throw. No unhandled rejection or retained timer.\n clearTimeout(timer);\n if (active === task) active = undefined;\n });\n },\n async stop() {\n pending = undefined;\n const task = active;\n if (!task) return;\n task.controller.abort(new DOMException(\"Startup check cancelled\", \"AbortError\"));\n // Drain the actual work, including child/ref cleanup, before foreground guards.\n await task.promise;\n },\n };\n return controllerApi;\n}\n", "type SetupSwitchModule = Pick<typeof import(\"./setup-switch.js\"), \"useSyncSetup\">;\ntype SnapshotModule = Pick<typeof import(\"../snapshot/snapshot.js\"), \"createSnapshot\">;\ntype SyncStateModule = Pick<typeof import(\"./sync-state.js\"), \"hasLocalChanges\">;\ntype SyncOperations = typeof import(\"./sync-operations.js\");\ntype CommandHandlerModule = Pick<typeof import(\"../commands/command-handler.js\"), \"handleCommand\">;\n\ntype SyncInspectionModule = Pick<typeof import(\"./sync-inspection.js\"), \"inspectSync\">;\n\nexport interface SyncDependencies {\n loadCommandHandler(): Promise<CommandHandlerModule>;\n loadSyncInspection(): Promise<SyncInspectionModule>;\n loadSetupSwitch(): Promise<SetupSwitchModule>;\n loadSnapshot(): Promise<SnapshotModule>;\n loadSyncState(): Promise<SyncStateModule>;\n loadSyncOperations(): Promise<SyncOperations>;\n}\n\nexport interface SyncLoaders {\n commands(): Promise<CommandHandlerModule>;\n inspection(): Promise<SyncInspectionModule>;\n setupSwitch(): Promise<SetupSwitchModule>;\n snapshot(): Promise<SnapshotModule>;\n syncState(): Promise<SyncStateModule>;\n operations(): Promise<SyncOperations>;\n}\n\nexport function createSyncLoaders(dependencies: Partial<SyncDependencies>): SyncLoaders {\n const loaders: SyncLoaders = {\n commands: cachedModuleLoader(dependencies.loadCommandHandler ?? (() => import(\"../commands/command-handler.js\"))),\n inspection: cachedModuleLoader(dependencies.loadSyncInspection ?? (() => import(\"./sync-inspection.js\"))),\n setupSwitch: cachedModuleLoader(dependencies.loadSetupSwitch ?? (() => import(\"./setup-switch.js\"))),\n snapshot: cachedModuleLoader(dependencies.loadSnapshot ?? (() => import(\"../snapshot/snapshot.js\"))),\n syncState: cachedModuleLoader(dependencies.loadSyncState ?? (() => import(\"./sync-state.js\"))),\n operations: cachedModuleLoader(dependencies.loadSyncOperations ?? (() => import(\"./sync-operations.js\"))),\n };\n return loaders;\n}\n\nfunction cachedModuleLoader<Module>(load: () => Promise<Module>): () => Promise<Module> {\n let pending: Promise<Module> | undefined;\n return () => {\n if (!pending) {\n pending = load().catch((error) => {\n pending = undefined;\n throw error;\n });\n }\n return pending;\n };\n}\n", "import type { ExtensionAPI } from \"@earendil-works/pi-coding-agent\";\nimport { Text, truncateToWidth } from \"@earendil-works/pi-tui\";\nimport type { StartupTimingPublisher } from \"../sync/startup-timings.js\";\nimport { safeTerminalText } from \"./terminal-text.js\";\n\nexport const STARTUP_TIMING_ENTRY = \"pi-sync-startup-timings\";\n\nexport interface StartupTimingEntry {\n version: 1;\n report: string;\n}\n\nexport function registerStartupTimings(pi: ExtensionAPI): StartupTimingPublisher {\n pi.registerEntryRenderer<StartupTimingEntry>(STARTUP_TIMING_ENTRY, (entry, _options, theme) => {\n const data = entry.data;\n if (data?.version !== 1 || typeof data.report !== \"string\") return undefined;\n const text = new Text(\n data.report\n .split(\"\\n\")\n .map((line, index) => theme.fg(index === 0 ? \"accent\" : \"muted\", safeTerminalText(line)))\n .join(\"\\n\"),\n 0,\n 0,\n );\n return {\n render: (width) => (width > 0 ? text.render(width).map((line) => truncateToWidth(line, width)) : []),\n invalidate: () => text.invalidate(),\n };\n });\n return (ctx, report) => {\n // Pi coalesces consecutive info notifications, including the final /reload notice.\n // Custom entries remain visible without adding messages to model context.\n if (ctx.mode === \"tui\") pi.appendEntry<StartupTimingEntry>(STARTUP_TIMING_ENTRY, { version: 1, report });\n else ctx.ui.notify(report, \"info\");\n };\n}\n", "import type { ExtensionAPI, ExtensionContext } from \"@earendil-works/pi-coding-agent\";\nimport { completeSyncArguments, splitArgs } from \"./commands/command.js\";\nimport {\n bindPiDaemonClient,\n installPiDaemonHost,\n type PiDaemonClient,\n withPiDaemonClient,\n} from \"./daemon/pi-client.js\";\nimport type { AnySyncConfig } from \"./settings/settings-types.js\";\nimport { startupTransferEnabled } from \"./sync/agent-policy.js\";\nimport { autoPushSessions, startSession } from \"./sync/automatic-sync.js\";\nimport { combineSignals } from \"./sync/signals.js\";\nimport { createStartupCheck } from \"./sync/startup-check.js\";\nimport { errorMessage } from \"./sync/sync-errors.js\";\nimport { createSyncLoaders, type SyncDependencies } from \"./sync/sync-loaders.js\";\nimport { registerStartupTimings } from \"./ui/startup-timings-entry.js\";\nimport { createSyncAttentionController } from \"./ui/sync-attention.js\";\nimport { createSyncStatusPublisher } from \"./ui/sync-status.js\";\nimport { safeTerminalText } from \"./ui/terminal-text.js\";\n\nexport default function sync(pi: ExtensionAPI, dependencies: Partial<SyncDependencies> = {}) {\n installPiDaemonHost();\n const loaders = createSyncLoaders(dependencies);\n const attention = createSyncAttentionController();\n const status = createSyncStatusPublisher(pi.events);\n const publishTimings = registerStartupTimings(pi);\n const check = createStartupCheck(loaders, attention, 30_000, publishTimings);\n let sessionAbort = new AbortController();\n let shutdownAbort: AbortController | undefined;\n let initialization = Promise.resolve<AnySyncConfig | false | undefined>(undefined);\n let owner: PiDaemonClient | undefined;\n let ownerManager: ExtensionContext[\"sessionManager\"] | undefined;\n\n pi.registerCommand(\"sync\", {\n description: \"Sync Pi settings through Git, WebDAV, R2, or S3-compatible storage\",\n getArgumentCompletions: completeSyncArguments,\n handler: async (args, ctx) => {\n if (!ctx.hasUI) throw new Error(\"/sync requires TUI or RPC mode so results and safety prompts are observable.\");\n status.bind(ctx);\n const signal = sessionAbort.signal;\n const client = owner;\n if (!client || ownerManager !== ctx.sessionManager) {\n if (splitArgs(args)[0] !== \"help\") throw new Error(\"pi-sync session is not ready.\");\n const commands = await loaders.commands();\n if (signal.aborted || owner) return;\n ctx.isIdle();\n await commands.handleCommand(args, ctx, signal, loaders, attention);\n return;\n }\n const reload = new AbortController();\n const commandSignal = combineSignals(signal, reload.signal);\n try {\n await withPiDaemonClient(\n ctx,\n async (ctx) => {\n const command = splitArgs(args)[0];\n const ready = await initialization;\n if (signal.aborted || owner !== client) return;\n const requiresContact = ![\"help\", \"unlock\", \"migrate-state\"].includes(command ?? \"\");\n let busyPublished = false;\n try {\n await client.setBusy(\"command\", true, requiresContact);\n busyPublished = requiresContact;\n if (signal.aborted || owner !== client) return;\n await check.stop();\n if (signal.aborted || owner !== client) return;\n if (\n ready === false &&\n command !== \"help\" &&\n command !== \"unlock\" &&\n command !== \"migrate-state\" &&\n command !== \"daemon\"\n ) {\n ctx.ui.notify(\n \"pi-sync recovery required. Repair the startup error, then /reload before syncing. Use /sync help for recovery guidance.\",\n \"error\",\n );\n return;\n }\n if (command === \"unlock\" || command === \"migrate-state\") {\n const { stateDirectoryMigrationNotice } = await import(\"./state/state-directory.js\");\n if (signal.aborted || owner !== client) return;\n // Recovery cannot guess an authoritative root when roots coexist or are unsafe.\n stateDirectoryMigrationNotice();\n }\n const commands = await loaders.commands();\n if (signal.aborted || owner !== client) return;\n await commands.handleCommand(args, ctx, commandSignal, loaders, attention);\n } catch (error) {\n if (!commandSignal.aborted && owner === client) {\n ctx.ui.notify(`pi-sync command unavailable: ${safeTerminalText(errorMessage(error))}`, \"error\");\n if (command === \"unlock\" || command === \"migrate-state\") throw error;\n }\n } finally {\n if (!signal.aborted && owner === client) {\n // Recovery can publish busy facts after bypassing the initial contact check.\n const publish = busyPublished || command === \"unlock\" || command === \"migrate-state\";\n // Release local busy state even if contact failed; do not mask the command result.\n await client.setBusy(\"command\", false, publish).catch(() => {});\n }\n }\n },\n reload,\n );\n // Pi reload awaits our shutdown hook. Neither daemon work nor old UI may await reload.\n if (!signal.aborted && owner === client && client.canReload(reload)) await ctx.reload();\n } finally {\n client.releaseReload(reload);\n reload.abort();\n }\n },\n });\n pi.on(\"session_start\", async (_event, ctx) => {\n const releaseStatus = status.start(ctx);\n const previousClient = owner;\n shutdownAbort?.abort(new DOMException(\"Session replaced\", \"AbortError\"));\n shutdownAbort = undefined;\n sessionAbort.abort(new DOMException(\"Session replaced\", \"AbortError\"));\n sessionAbort = new AbortController();\n const signal = sessionAbort.signal;\n const client = bindPiDaemonClient(ctx, signal, publishTimings);\n owner = client;\n ownerManager = ctx.sessionManager;\n const replacementFile = ctx.sessionManager.getSessionFile?.();\n attention.reset(ctx);\n const previous = initialization;\n initialization = withPiDaemonClient(ctx, async () => {\n await previous.catch(() => {});\n if (signal.aborted || owner !== client) return false;\n try {\n await check.stop();\n if (previousClient) {\n // Protect the replacement session before removing old session protection.\n try {\n await client.attachExisting({ allowUpgrade: true });\n } catch {\n /* Initialization below reports an unavailable owner. */\n }\n try {\n await previousClient.disposeForShutdown(\"resume\", replacementFile);\n } catch {\n /* Plain, detached recovery owns uncertain grants; no closed ctx is retained. */\n }\n await client.finishReattachment();\n }\n if (signal.aborted || owner !== client) return false;\n return (await startSession(ctx, signal, publishTimings))?.config;\n } catch (error) {\n if (!signal.aborted && owner === client) {\n try {\n client.validate();\n if (ctx.hasUI)\n ctx.ui.notify(`pi-sync recovery required: ${safeTerminalText(errorMessage(error))}`, \"error\");\n } catch {\n /* SDK context was replaced. */\n }\n }\n return false;\n }\n });\n try {\n const ready = await initialization;\n if (ready === false) releaseStatus();\n if (\n ready &&\n !signal.aborted &&\n owner === client &&\n !(ready.continuous && ready.agentMode) &&\n (ready.automatic || startupTransferEnabled(ready))\n )\n await withPiDaemonClient(ctx, async () => {\n check.start(ctx, signal, ready);\n });\n } catch (error) {\n releaseStatus();\n throw error;\n }\n });\n pi.on(\"agent_start\", async (_event, ctx) => {\n const client = owner;\n if (!client || ownerManager !== ctx.sessionManager || sessionAbort.signal.aborted) return;\n if (!ctx.hasUI || ![\"tui\", \"rpc\"].includes(ctx.mode)) await client.attachExisting();\n await client.setBusy(\"agent\", true);\n if (owner === client && !sessionAbort.signal.aborted) await check.interrupt(ctx);\n });\n pi.on(\"agent_settled\", async (_event, ctx) => {\n const client = owner;\n if (!client || ownerManager !== ctx.sessionManager || sessionAbort.signal.aborted) return;\n await client.setBusy(\"agent\", false);\n if (owner === client && !sessionAbort.signal.aborted)\n await withPiDaemonClient(ctx, async () => {\n check.settled(ctx);\n });\n });\n pi.on(\"model_select\", async (_event, ctx) => {\n if (owner && ownerManager === ctx.sessionManager && !sessionAbort.signal.aborted) await owner.update();\n });\n const pauseForReplacement = async (_event: unknown, ctx: ExtensionContext) => {\n const client = owner;\n if (!client || ownerManager !== ctx.sessionManager || sessionAbort.signal.aborted) return;\n const results = await Promise.allSettled([client.pauseForSessionChange(), check.stop()]);\n if (results.some((result) => result.status === \"rejected\")) {\n if (owner === client && !sessionAbort.signal.aborted)\n ctx.ui.notify(\n \"pi-sync could not drain its writer. Repair or stop the existing daemon before changing sessions.\",\n \"error\",\n );\n return { cancel: true };\n }\n // Another handler can still cancel the SDK transition. Stay paused until\n // /reload instead of guessing that it is safe to resume while handlers run.\n };\n pi.on(\"session_before_switch\", pauseForReplacement);\n pi.on(\"session_before_fork\", pauseForReplacement);\n pi.on(\"session_shutdown\", async (event, ctx) => {\n const releaseStatus = status.cleanupFor(ctx);\n const client = owner;\n if (!client || ownerManager !== ctx.sessionManager) {\n releaseStatus();\n return;\n }\n const controller = new AbortController();\n shutdownAbort?.abort(new DOMException(\"Session shut down again\", \"AbortError\"));\n shutdownAbort = controller;\n const signal = combineSignals(controller.signal, AbortSignal.timeout(30_000));\n const reason = typeof event === \"object\" && event ? (event as { reason?: string }).reason : undefined;\n const target =\n typeof event === \"object\" && event ? (event as { targetSessionFile?: string }).targetSessionFile : undefined;\n // Cancel old dialogs/settings work now, while the SDK context is still active.\n sessionAbort.abort(new DOMException(\"Session shutting down\", \"AbortError\"));\n let shutdownClient: PiDaemonClient | undefined;\n try {\n await initialization.catch(() => {});\n await check.stop();\n if (signal.aborted || owner !== client) return;\n if (reason !== \"reload\") {\n shutdownClient = bindPiDaemonClient(ctx, signal, publishTimings);\n await shutdownClient.setBusy(\"shutdown\", true);\n const attached = await shutdownClient.attachExisting();\n if (!signal.aborted && owner === client && attached)\n await withPiDaemonClient(ctx, () => autoPushSessions(ctx, signal, loaders));\n }\n } catch (error) {\n if (!signal.aborted && owner === client) {\n try {\n ctx.ui.notify(`pi-sync shutdown skipped: ${safeTerminalText(errorMessage(error))}`, \"warning\");\n } catch {\n /* SDK context was replaced. */\n }\n }\n } finally {\n if (owner === client) {\n owner = undefined;\n ownerManager = undefined;\n try {\n attention.reset(ctx);\n } catch {\n /* Cleanup never depends on an active SDK context. */\n }\n }\n try {\n await client.disposeForShutdown(reason, target);\n } finally {\n try {\n await shutdownClient?.disposeForShutdown(reason, target);\n } finally {\n controller.abort();\n releaseStatus();\n }\n }\n if (shutdownAbort === controller) shutdownAbort = undefined;\n }\n });\n}\nexport type { SyncDependencies } from \"./sync/sync-loaders.js\";\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;ACRP,SAAS,4BAA4B;;;ACArC,SAAS,4BAA4B;;;ACWrC,eAAsB,aACpB,KACA,QACA,SACiE;AACjE,iBAAe,MAAM;AACrB,QAAM,SAAS,eAAe,GAAG;AAGjC,MAAI,CAAC,IAAI,SAAS,CAAC,CAAC,OAAO,KAAK,EAAE,SAAS,IAAI,IAAI,GAAG;AACpD,UAAM,OAAO,eAAe;AAC5B,mBAAe,MAAM;AACrB,WAAO,EAAE,OAAO,MAAM;AAAA,EACxB;AACA,QAAM,UAAU,qBAAqB,OAAO;AAC5C,QAAM,WAAW,MAAM,QAAQ,QAAQ,iBAAiB,MAAM,OAAO,aAAa,C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_ATTEMPTS,\n AGENT_MAX_TOKENS,\n AGENT_MAX_UNITS,\n AGENT_OUTPUT_BYTES,\n AGENT_TIMEOUT_MS,\n startupTransferEnabled,\n} from \"@narumitw/pi-sync-daemon/engine/sync/agent-policy\";\n", "export type * from \"@narumitw/pi-sync-daemon/engine/settings/config-errors\";\nexport { isMissingConfigError } from \"@narumitw/pi-sync-daemon/engine/settings/config-errors\";\n", "export type * from \"@narumitw/pi-sync-daemon/engine/sync/startup-timings\";\nexport { createStartupTimings } from \"@narumitw/pi-sync-daemon/engine/sync/startup-timings\";\n", "import type { ExtensionContext } from \"@earendil-works/pi-coding-agent\";\nimport { setSyncSetupCompletions } from \"../commands/command.js\";\nimport { piDaemonClient } from \"../daemon/pi-client.js\";\nimport { isMissingConfigError } from \"../settings/config-errors.js\";\nimport type { AnySyncConfig, PiSyncSettingsV3 } from \"../settings/settings-types.js\";\nimport { configureSyncStatus } from \"../ui/sync-status.js\";\nimport { safeTerminalText } from \"../ui/terminal-text.js\";\nimport { throwIfAborted } from \"./signals.js\";\nimport { createStartupTimings, type StartupTimingPublisher } from \"./startup-timings.js\";\nimport { errorMessage } from \"./sync-errors.js\";\nimport type { SyncLoaders } from \"./sync-loaders.js\";\n\nexport async function startSession(\n ctx: ExtensionContext,\n signal: AbortSignal,\n publish?: StartupTimingPublisher,\n): Promise<{ debug: boolean; config?: AnySyncConfig } | undefined> {\n throwIfAborted(signal);\n const client = piDaemonClient(ctx);\n // One-off sessions only protect their files in an already existing service.\n // They never launch it or authorize observations, transfers, or model work.\n if (!ctx.hasUI || ![\"tui\", \"rpc\"].includes(ctx.mode)) {\n await client.attachExisting();\n throwIfAborted(signal);\n return { debug: false };\n }\n const timings = createStartupTimings(publish);\n const document = await timings.measure(\"settings read\", () => client.readSettings());\n throwIfAborted(signal);\n configureSyncStatus(ctx, (document?.parsed.showStatus as boolean | undefined) ?? true);\n const { stateDirectoryMigrationNotice } = await import(\"../state/state-directory.js\");\n const notice = stateDirectoryMigrationNotice();\n const { pendingTransactionEntries } = await import(\"../snapshot/snapshot-transaction-directory.js\");\n const recoveryNeeded = (await pendingTransactionEntries()).some((entry) => entry.isDirectory());\n throwIfAborted(signal);\n if (!(await client.configured()) && !recoveryNeeded) {\n if (notice) ctx.ui.notify(notice, \"warning\");\n setSyncSetupCompletions([]);\n const debug = document?.parsed.debug === true;\n await client.markReady(debug);\n timings.publish(ctx, debug, signal, \"local initialization\", \"completed\");\n return { debug };\n }\n throwIfAborted(signal);\n const result = (await client.run(\"initialize\", {}, signal)) as {\n debug: boolean;\n config?: AnySyncConfig;\n settings?: PiSyncSettingsV3;\n handoverRequired: boolean;\n };\n throwIfAborted(signal);\n configureSyncStatus(ctx, result.settings?.showStatus ?? true);\n setSyncSetupCompletions(Object.keys(result.settings?.syncSetups ?? {}).sort((a, b) => a.localeCompare(b)));\n await client.markReady(result.debug);\n throwIfAborted(signal);\n if (result.handoverRequired) {\n ctx.ui.notify(\n \"pi-sync: close or upgrade older Pi processes, then use /sync to review daemon handover. No automatic transfer is authorized yet.\",\n \"warning\",\n );\n return { debug: result.debug };\n }\n return { debug: result.debug, config: result.config };\n}\nexport async function autoPushSessions(ctx: ExtensionContext, signal: AbortSignal, _loaders: SyncLoaders) {\n try {\n const client = piDaemonClient(ctx);\n if (!(await client.configured())) return;\n throwIfAborted(signal);\n await client.run(\n \"shutdown\",\n { args: [], yes: true, force: false, stale: false, silent: true, reload: false },\n signal,\n );\n } catch (error) {\n if (signal.aborted || isMissingConfigError(error)) return;\n ctx.ui.notify(`pi-sync session push skipped: ${safeTerminalText(errorMessage(error))}`, \"warning\");\n }\n}\n", "import type { ExtensionContext } from \"@earendil-works/pi-coding-agent\";\nimport { loadConfigForCheck, syncCheckConfigFingerprint } from \"../settings/config.js\";\nimport { isMissingConfigError } from \"../settings/config-errors.js\";\nimport type { AnySyncConfig } from \"../settings/settings-types.js\";\nimport { snapshotOptionsForContext } from \"../snapshot/session-paths.js\";\nimport { withStateDirectoryAccess } from \"../state/state-directory.js\";\nimport { readStateForConfig, syncStateFingerprint } from \"../state/sync-state-store.js\";\nimport type { SyncAttentionController } from \"../ui/sync-attention.js\";\nimport { setSyncStatus } from \"../ui/sync-status.js\";\nimport { safeTerminalText } from \"../ui/terminal-text.js\";\nimport { startupTransferEnabled } from \"./agent-policy.js\";\nimport { combineSignals, throwIfAborted } from \"./signals.js\";\nimport { createStartupTimings, type StartupTimingPublisher } from \"./startup-timings.js\";\nimport { errorMessage } from \"./sync-errors.js\";\nimport type { SyncLoaders } from \"./sync-loaders.js\";\n\n/** One owned task per extension session, never keyed by the shared headless UI. */\nexport function createStartupCheck(\n loaders: SyncLoaders,\n attention: SyncAttentionController,\n timeoutMs = 30_000,\n publish?: StartupTimingPublisher,\n) {\n let active:\n | {\n controller: AbortController;\n promise: Promise<void>;\n owner: ExtensionContext[\"sessionManager\"];\n transfer: boolean;\n }\n | undefined;\n\n let pending: { ctx: ExtensionContext; signal: AbortSignal; config: AnySyncConfig } | undefined;\n\n const controllerApi = {\n async interrupt(ctx: ExtensionContext) {\n const task = active;\n if (!task?.transfer || task.owner !== ctx.sessionManager) return;\n task.controller.abort(new DOMException(\"Agent became busy\", \"AbortError\"));\n await task.promise;\n },\n settled(ctx: ExtensionContext) {\n const queued = pending;\n if (!queued || queued.ctx.sessionManager !== ctx.sessionManager || queued.signal.aborted || !ctx.isIdle()) return;\n pending = undefined;\n controllerApi.start(ctx, queued.signal, queued.config);\n },\n start(ctx: ExtensionContext, sessionSignal: AbortSignal, initialConfig?: AnySyncConfig) {\n if (!ctx.hasUI || sessionSignal.aborted) return;\n if (initialConfig && startupTransferEnabled(initialConfig) && !ctx.isIdle()) {\n pending = { ctx, signal: sessionSignal, config: initialConfig };\n return;\n }\n if (active) throw new Error(\"Previous startup check has not been drained.\");\n const timings = createStartupTimings(publish);\n const controller = new AbortController();\n const signal = combineSignals(sessionSignal, controller.signal);\n const task = {\n controller,\n owner: ctx.sessionManager,\n promise: Promise.resolve(),\n transfer: Boolean(initialConfig && startupTransferEnabled(initialConfig)),\n };\n active = task;\n const isCurrent = () => !sessionSignal.aborted && active === task && task.owner === ctx.sessionManager;\n const timer = setTimeout(\n () => controller.abort(new DOMException(\"Startup check timed out\", \"TimeoutError\")),\n timeoutMs,\n );\n timer.unref();\n let config: AnySyncConfig | undefined;\n let checking = false;\n let stopped = false;\n // Handle every detached rejection here; Pi's awaited event runner cannot catch it.\n task.promise = Promise.resolve()\n .then(async () => {\n try {\n throwIfAborted(signal);\n config = initialConfig ?? (await loadConfigForCheck());\n task.transfer = startupTransferEnabled(config);\n throwIfAborted(signal);\n if (!config.automatic && !startupTransferEnabled(config)) return;\n const captured = config;\n const identity = syncCheckConfigFingerprint(captured);\n checking = true;\n setSyncStatus(ctx, \"sync ...\", { activity: \"checking\" });\n const { inspectSync } = await timings.measure(\"inspection import\", () => loaders.inspection());\n throwIfAborted(signal);\n const currentConfig = await loadConfigForCheck();\n throwIfAborted(signal);\n if (syncCheckConfigFingerprint(currentConfig) !== identity) return;\n // The daemon owns the operation and cache guards.\n const inspection = await timings.measure(\"inspection and guards\", () =>\n inspectSync(captured, snapshotOptionsForContext(ctx, captured), signal, undefined, timings),\n );\n throwIfAborted(signal);\n const latest = await loadConfigForCheck();\n throwIfAborted(signal);\n if (syncCheckConfigFingerprint(latest) !== identity) return;\n const state = await withStateDirectoryAccess(() => readStateForConfig(latest));\n throwIfAborted(signal);\n if (syncStateFingerprint(state) !== inspection.stateIdentity || !isCurrent()) return;\n attention.observe({\n setupName: captured.setupName,\n configIdentity: identity,\n checkedAt: new Date().toISOString(),\n inspection,\n automaticTransfer: startupTransferEnabled(captured),\n });\n if (\n startupTransferEnabled(captured) &&\n !inspection.firstSync &&\n inspection.head &&\n inspection.selectionState?.kind === \"same\"\n ) {\n const operations = await timings.measure(\"operations import\", () => loaders.operations());\n throwIfAborted(signal);\n if (!isCurrent()) return;\n if (!ctx.isIdle()) {\n pending = { ctx, signal: sessionSignal, config: captured };\n return;\n }\n await timings.measure(\"automatic transfer\", () =>\n operations.syncBoth(ctx, {\n args: [],\n yes: true,\n force: false,\n stale: false,\n silent: true,\n reload: false,\n auto: true,\n signal,\n startupTimings: timings,\n onCommit: () => attention.clearObservation(),\n }),\n );\n throwIfAborted(signal);\n if (!isCurrent()) return;\n attention.clearObservation();\n return;\n }\n attention.observe({\n setupName: captured.setupName,\n configIdentity: identity,\n checkedAt: new Date().toISOString(),\n inspection,\n automaticTransfer: startupTransferEnabled(captured),\n });\n if (ctx.mode === \"rpc\") attention.notifyObservation(ctx);\n } catch (error) {\n stopped = true;\n if (!isCurrent() || sessionSignal.aborted || isMissingConfigError(error)) return;\n if (signal.aborted && controller.signal.reason?.name !== \"TimeoutError\") return;\n // A settings edit invalidates failures as well as successful observations.\n if (config) {\n const latest = await loadConfigForCheck().catch(() => undefined);\n if (!isCurrent() || (signal.aborted && controller.signal.reason?.name !== \"TimeoutError\")) return;\n if (!latest || syncCheckConfigFingerprint(latest) !== syncCheckConfigFingerprint(config)) return;\n }\n ctx.ui.notify(\n config && startupTransferEnabled(config)\n ? `pi-sync automatic transfer stopped: ${safeTerminalText(errorMessage(error))}. Run /sync to review or reconcile retained recovery evidence. No resources were reloaded.`\n : `pi-sync startup check skipped: ${safeTerminalText(errorMessage(error))}. Run /sync status to retry. No startup transfer was performed.`,\n \"warning\",\n );\n } finally {\n clearTimeout(timer);\n if (isCurrent() && checking) {\n if (!signal.aborted || controller.signal.reason?.name === \"TimeoutError\") {\n const latest = await loadConfigForCheck().catch(() => undefined);\n if (isCurrent()) {\n if (signal.aborted && controller.signal.reason?.name !== \"TimeoutError\")\n setSyncStatus(ctx, undefined);\n else if (\n config &&\n latest &&\n syncCheckConfigFingerprint(latest) === syncCheckConfigFingerprint(config)\n )\n await attention.publish(ctx, sessionSignal);\n else attention.reset(ctx);\n }\n } else setSyncStatus(ctx, undefined);\n }\n if (isCurrent()) {\n timings.publish(\n ctx,\n config?.debug ?? false,\n sessionSignal,\n \"background startup\",\n signal.aborted || stopped ? \"stopped\" : \"completed\",\n );\n }\n if (active === task) active = undefined;\n }\n })\n .catch(() => {\n // UI teardown can itself throw. No unhandled rejection or retained timer.\n clearTimeout(timer);\n if (active === task) active = undefined;\n });\n },\n async stop() {\n pending = undefined;\n const task = active;\n if (!task) return;\n task.controller.abort(new DOMException(\"Startup check cancelled\", \"AbortError\"));\n // Drain the actual work, including child/ref cleanup, before foreground guards.\n await task.promise;\n },\n };\n return controllerApi;\n}\n", "type SetupSwitchModule = Pick<typeof import(\"./setup-switch.js\"), \"useSyncSetup\">;\ntype SnapshotModule = Pick<typeof import(\"../snapshot/snapshot.js\"), \"createSnapshot\">;\ntype SyncStateModule = Pick<typeof import(\"./sync-state.js\"), \"hasLocalChanges\">;\ntype SyncOperations = typeof import(\"./sync-operations.js\");\ntype CommandHandlerModule = Pick<typeof import(\"../commands/command-handler.js\"), \"handleCommand\">;\n\ntype SyncInspectionModule = Pick<typeof import(\"./sync-inspection.js\"), \"inspectSync\">;\n\nexport interface SyncDependencies {\n loadCommandHandler(): Promise<CommandHandlerModule>;\n loadSyncInspection(): Promise<SyncInspectionModule>;\n loadSetupSwitch(): Promise<SetupSwitchModule>;\n loadSnapshot(): Promise<SnapshotModule>;\n loadSyncState(): Promise<SyncStateModule>;\n loadSyncOperations(): Promise<SyncOperations>;\n}\n\nexport interface SyncLoaders {\n commands(): Promise<CommandHandlerModule>;\n inspection(): Promise<SyncInspectionModule>;\n setupSwitch(): Promise<SetupSwitchModule>;\n snapshot(): Promise<SnapshotModule>;\n syncState(): Promise<SyncStateModule>;\n operations(): Promise<SyncOperations>;\n}\n\nexport function createSyncLoaders(dependencies: Partial<SyncDependencies>): SyncLoaders {\n const loaders: SyncLoaders = {\n commands: cachedModuleLoader(dependencies.loadCommandHandler ?? (() => import(\"../commands/command-handler.js\"))),\n inspection: cachedModuleLoader(dependencies.loadSyncInspection ?? (() => import(\"./sync-inspection.js\"))),\n setupSwitch: cachedModuleLoader(dependencies.loadSetupSwitch ?? (() => import(\"./setup-switch.js\"))),\n snapshot: cachedModuleLoader(dependencies.loadSnapshot ?? (() => import(\"../snapshot/snapshot.js\"))),\n syncState: cachedModuleLoader(dependencies.loadSyncState ?? (() => import(\"./sync-state.js\"))),\n operations: cachedModuleLoader(dependencies.loadSyncOperations ?? (() => import(\"./sync-operations.js\"))),\n };\n return loaders;\n}\n\nfunction cachedModuleLoader<Module>(load: () => Promise<Module>): () => Promise<Module> {\n let pending: Promise<Module> | undefined;\n return () => {\n if (!pending) {\n pending = load().catch((error) => {\n pending = undefined;\n throw error;\n });\n }\n return pending;\n };\n}\n", "import type { ExtensionAPI } from \"@earendil-works/pi-coding-agent\";\nimport { Text, truncateToWidth } from \"@earendil-works/pi-tui\";\nimport type { StartupTimingPublisher } from \"../sync/startup-timings.js\";\nimport { safeTerminalText } from \"./terminal-text.js\";\n\nexport const STARTUP_TIMING_ENTRY = \"pi-sync-startup-timings\";\n\nexport interface StartupTimingEntry {\n version: 1;\n report: string;\n}\n\nexport function registerStartupTimings(pi: ExtensionAPI): StartupTimingPublisher {\n pi.registerEntryRenderer<StartupTimingEntry>(STARTUP_TIMING_ENTRY, (entry, _options, theme) => {\n const data = entry.data;\n if (data?.version !== 1 || typeof data.report !== \"string\") return undefined;\n const text = new Text(\n data.report\n .split(\"\\n\")\n .map((line, index) => theme.fg(index === 0 ? \"accent\" : \"muted\", safeTerminalText(line)))\n .join(\"\\n\"),\n 0,\n 0,\n );\n return {\n render: (width) => (width > 0 ? text.render(width).map((line) => truncateToWidth(line, width)) : []),\n invalidate: () => text.invalidate(),\n };\n });\n return (ctx, report) => {\n // Pi coalesces consecutive info notifications, including the final /reload notice.\n // Custom entries remain visible without adding messages to model context.\n if (ctx.mode === \"tui\") pi.appendEntry<StartupTimingEntry>(STARTUP_TIMING_ENTRY, { version: 1, report });\n else ctx.ui.notify(report, \"info\");\n };\n}\n", "import type { ExtensionAPI, ExtensionContext } from \"@earendil-works/pi-coding-agent\";\nimport { completeSyncArguments, splitArgs } from \"./commands/command.js\";\nimport {\n bindPiDaemonClient,\n installPiDaemonHost,\n type PiDaemonClient,\n withPiDaemonClient,\n} from \"./daemon/pi-client.js\";\nimport type { AnySyncConfig } from \"./settings/settings-types.js\";\nimport { startupTransferEnabled } from \"./sync/agent-policy.js\";\nimport { autoPushSessions, startSession } from \"./sync/automatic-sync.js\";\nimport { combineSignals } from \"./sync/signals.js\";\nimport { createStartupCheck } from \"./sync/startup-check.js\";\nimport { errorMessage } from \"./sync/sync-errors.js\";\nimport { createSyncLoaders, type SyncDependencies } from \"./sync/sync-loaders.js\";\nimport { registerStartupTimings } from \"./ui/startup-timings-entry.js\";\nimport { createSyncAttentionController } from \"./ui/sync-attention.js\";\nimport { createSyncStatusPublisher } from \"./ui/sync-status.js\";\nimport { safeTerminalText } from \"./ui/terminal-text.js\";\n\nexport default function sync(pi: ExtensionAPI, dependencies: Partial<SyncDependencies> = {}) {\n installPiDaemonHost();\n const loaders = createSyncLoaders(dependencies);\n const attention = createSyncAttentionController();\n const status = createSyncStatusPublisher(pi.events);\n const publishTimings = registerStartupTimings(pi);\n const check = createStartupCheck(loaders, attention, 30_000, publishTimings);\n let sessionAbort = new AbortController();\n let shutdownAbort: AbortController | undefined;\n let initialization = Promise.resolve<AnySyncConfig | false | undefined>(undefined);\n let owner: PiDaemonClient | undefined;\n let ownerManager: ExtensionContext[\"sessionManager\"] | undefined;\n\n pi.registerCommand(\"sync\", {\n description: \"Sync Pi settings through Git, WebDAV, R2, or S3-compatible storage\",\n getArgumentCompletions: completeSyncArguments,\n handler: async (args, ctx) => {\n if (!ctx.hasUI) throw new Error(\"/sync requires TUI or RPC mode so results and safety prompts are observable.\");\n status.bind(ctx);\n const signal = sessionAbort.signal;\n const client = owner;\n if (!client || ownerManager !== ctx.sessionManager) {\n if (splitArgs(args)[0] !== \"help\") throw new Error(\"pi-sync session is not ready.\");\n const commands = await loaders.commands();\n if (signal.aborted || owner) return;\n ctx.isIdle();\n await commands.handleCommand(args, ctx, signal, loaders, attention);\n return;\n }\n const reload = new AbortController();\n const commandSignal = combineSignals(signal, reload.signal);\n try {\n await withPiDaemonClient(\n ctx,\n async (ctx) => {\n const command = splitArgs(args)[0];\n const ready = await initialization;\n if (signal.aborted || owner !== client) return;\n const requiresContact = ![\"help\", \"unlock\", \"migrate-state\"].includes(command ?? \"\");\n let busyPublished = false;\n try {\n await client.setBusy(\"command\", true, requiresContact);\n busyPublished = requiresContact;\n if (signal.aborted || owner !== client) return;\n await check.stop();\n if (signal.aborted || owner !== client) return;\n if (\n ready === false &&\n command !== \"help\" &&\n command !== \"unlock\" &&\n command !== \"migrate-state\" &&\n command !== \"daemon\"\n ) {\n ctx.ui.notify(\n \"pi-sync recovery required. Repair the startup error, then /reload before syncing. Use /sync help for recovery guidance.\",\n \"error\",\n );\n return;\n }\n if (command === \"unlock\" || command === \"migrate-state\") {\n const { stateDirectoryMigrationNotice } = await import(\"./state/state-directory.js\");\n if (signal.aborted || owner !== client) return;\n // Recovery cannot guess an authoritative root when roots coexist or are unsafe.\n stateDirectoryMigrationNotice();\n }\n const commands = await loaders.commands();\n if (signal.aborted || owner !== client) return;\n await commands.handleCommand(args, ctx, commandSignal, loaders, attention);\n } catch (error) {\n if (!commandSignal.aborted && owner === client) {\n ctx.ui.notify(`pi-sync command unavailable: ${safeTerminalText(errorMessage(error))}`, \"error\");\n if (command === \"unlock\" || command === \"migrate-state\") throw error;\n }\n } finally {\n if (!signal.aborted && owner === client) {\n // Recovery can publish busy facts after bypassing the initial contact check.\n const publish = busyPublished || command === \"unlock\" || command === \"migrate-state\";\n // Release local busy state even if contact failed; do not mask the command result.\n await client.setBusy(\"command\", false, publish).catch(() => {});\n }\n }\n },\n reload,\n );\n // Pi reload awaits our shutdown hook. Neither daemon work nor old UI may await reload.\n if (!signal.aborted && owner === client && client.canReload(reload)) await ctx.reload();\n } finally {\n client.releaseReload(reload);\n reload.abort();\n }\n },\n });\n pi.on(\"session_start\", async (_event, ctx) => {\n const 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 client.validate();\n if (ctx.hasUI)\n ctx.ui.notify(`pi-sync recovery required: ${safeTerminalText(errorMessage(error))}`, \"error\");\n } catch {\n /* SDK context was replaced. */\n }\n }\n return false;\n }\n });\n try {\n const ready = await initialization;\n if (ready === false) {\n client.disableQueueReleaseUI();\n releaseStatus();\n }\n if (\n ready &&\n !signal.aborted &&\n owner === client &&\n !(ready.continuous && ready.agentMode) &&\n (ready.automatic || startupTransferEnabled(ready))\n )\n await withPiDaemonClient(ctx, async () => {\n check.start(ctx, signal, ready);\n });\n } catch (error) {\n 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 await shutdownClient.setBusy(\"shutdown\", true);\n const attached = await shutdownClient.attachExisting();\n if (!signal.aborted && owner === client && attached)\n await withPiDaemonClient(ctx, () => autoPushSessions(ctx, signal, loaders));\n }\n } catch (error) {\n if (!signal.aborted && owner === client) {\n try {\n ctx.ui.notify(`pi-sync shutdown skipped: ${safeTerminalText(errorMessage(error))}`, \"warning\");\n } catch {\n /* SDK context was replaced. */\n }\n }\n } finally {\n if (owner === client) {\n owner = undefined;\n ownerManager = undefined;\n try {\n attention.reset(ctx);\n } catch {\n /* Cleanup never depends on an active SDK context. */\n }\n }\n try {\n await client.disposeForShutdown(reason, target);\n } finally {\n try {\n await shutdownClient?.disposeForShutdown(reason, target);\n } finally {\n controller.abort();\n releaseStatus();\n }\n }\n if (shutdownAbort === controller) shutdownAbort = undefined;\n }\n });\n}\nexport type { SyncDependencies } from \"./sync/sync-loaders.js\";\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;ACRP,SAAS,4BAA4B;;;ACArC,SAAS,4BAA4B;;;ACWrC,eAAsB,aACpB,KACA,QACA,SACiE;AACjE,iBAAe,MAAM;AACrB,QAAM,SAAS,eAAe,GAAG;AAGjC,MAAI,CAAC,IAAI,SAAS,CAAC,CAAC,OAAO,KAAK,EAAE,SAAS,IAAI,IAAI,GAAG;AACpD,UAAM,OAAO,eAAe;AAC5B,mBAAe,MAAM;AACrB,WAAO,EAAE,OAAO,MAAM;AAAA,EACxB;AACA,QAAM,UAAU,qBAAqB,OAAO;AAC5C,QAAM,WAAW,MAAM,QAAQ,QAAQ,iBAAiB,MAAM,OAAO,aAAa,CAAC;AACnF,iBAAe,MAAM;AACrB,sBAAoB,KAAM,UAAU,OAAO,cA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U,YAAY,QAAS,MAA8B,SAAS;AAC5F,UAAM,SACJ,OAAO,UAAU,YAAY,QAAS,MAAyC,oBAAoB;AAErG,iBAAa,MAAM,IAAI,aAAa,yBAAyB,YAAY,CAAC;AAC1E,QAAI;AACJ,QAAI;AACF,YAAM,eAAe,MAAM,MAAM;AAAA,MAAC,CAAC;AACnC,YAAM,MAAM,KAAK;AACjB,UAAI,OAAO,WAAW,UAAU,OAAQ;AACxC,UAAI,WAAW,UAAU;AACvB,yBAAiB,mBAAmB,KAAK,QAAQ,cAAc;AAC/D,cAAM,eAAe,QAAQ,YAAY,IAAI;AAC7C,cAAM,WAAW,MAAM,eAAe,eAAe;AACrD,YAAI,CAAC,OAAO,WAAW,UAAU,UAAU;AACzC,gBAAM,mBAAmB,KAAK,MAAM,iBAAiB,KAAK,QAAQ,OAAO,CAAC;AAAA,MAC9E;AAAA,IACF,SAAS,OAAO;AACd,UAAI,CAAC,OAAO,WAAW,UAAU,QAAQ;AACvC,YAAI;AACF,cAAI,GAAG,OAAO,6BAA6B,iBAAiB,aAAa,KAAK,CAAC,CAAC,IAAI,SAAS;AAAA,QAC/F,QAAQ;AAAA,QAER;AAAA,MACF;AAAA,IACF,UAAE;AACA,UAAI,UAAU,QAAQ;AACpB,gBAAQ;AACR,uBAAe;AACf,YAAI;AACF,oBAAU,MAAM,GAAG;AAAA,QACrB,QAAQ;AAAA,QAER;AAAA,MACF;AACA,UAAI;AACF,cAAM,OAAO,mBAAmB,QAAQ,MAAM;AAAA,MAChD,UAAE;AACA,YAAI;AACF,gBAAM,gBAAgB,mBAAmB,QAAQ,MAAM;AAAA,QACzD,UAAE;AACA,qBAAW,MAAM;AACjB,wBAAc;AAAA,QAChB;AAAA,MACF;AACA,UAAI,kBAAkB,WAAY,iBAAgB;AAAA,IACpD;AAAA,EACF,CAAC;AACH;",
6
6
  "names": ["ctx"]
7
7
  }
@@ -82,6 +82,12 @@ without supporting this repair; a healthy CLI status alone does not confirm Pi
82
82
  participation.
83
83
 
84
84
  Reconnect does not replay a submitted operation or restart startup transfers.
85
+ If Pi releases a file queue but the local acknowledgement is lost in transit,
86
+ it retries that acknowledgement with the same daemon. Brief retries stay
87
+ quiet; longer retries show `sync recovering` when sync status is enabled.
88
+ If a background release remains unconfirmed during a command, Pi reports it
89
+ after the command finishes.
90
+ A release acknowledgement alone does not confirm that a transfer succeeded.
85
91
  If a write or file-queue release cannot be confirmed, preserve the journals and
86
92
  use the existing recovery path before retrying a transfer. Reconnect does not
87
93
  stop or restart the service, and it does not extend transfer or model permission.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@narumitw/pi-sync",
3
- "version": "0.60.4",
3
+ "version": "0.61.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",
@@ -46,12 +46,12 @@
46
46
  "typecheck": "tsc --noEmit"
47
47
  },
48
48
  "dependencies": {
49
- "@narumitw/pi-sync-daemon": "^0.5.0",
49
+ "@narumitw/pi-sync-daemon": "^0.7.0",
50
50
  "@narumitw/pi-tui-kit": "^0.70.1"
51
51
  },
52
52
  "devDependencies": {
53
- "@earendil-works/pi-coding-agent": "1.5.0",
54
- "@earendil-works/pi-tui": "1.5.0",
53
+ "@earendil-works/pi-coding-agent": "1.6.0",
54
+ "@earendil-works/pi-tui": "1.6.0",
55
55
  "@types/proper-lockfile": "^4.1.4",
56
56
  "@types/semver": "^7.8.0",
57
57
  "esbuild": "0.28.2",
@@ -29,10 +29,10 @@ An explicit setup creates the file atomically.
29
29
  On POSIX, pi-sync creates and replaces it with mode `0600`.
30
30
  Pi-sync processes coordinate settings access through `pi-sync.json.mutation-lock`; lock-unaware editors are outside that serialization boundary and should not save the file while a pi-sync settings operation is running.
31
31
  Within one process, settings reads wait for earlier writes, including writes that have not acquired the lock yet.
32
- Replacement writes and flushes a private temporary file before renaming it over the canonical file; the active file is not moved away first.
32
+ Under that lock, a save validates the existing document before editing it. A malformed, invalid, or unsupported source cannot be replaced by relabeling it as a supported version. The writer validates the proposed document before flushing a private temporary file and renaming it over the canonical file; the active file is not moved away first.
33
33
  Credentials stay in this canonical private file and are never shown in menus, reviews, status, notifications, errors, logs, or completion metadata.
34
34
 
35
- A private `pi-sync.local.json` containing a valid version 3 document is copied byte-for-byte to `pi-sync.json`.
35
+ A private `pi-sync.local.json` containing a valid supported document is copied byte-for-byte to `pi-sync.json`.
36
36
  The old file remains as a recovery copy.
37
37
  If both paths exist, `pi-sync.json` wins and the legacy file remains untouched.
38
38
  If an older interrupted replacement left `pi-sync.json` missing and a hidden `.pi-sync.json.*.schema-migration-source` or `.pi-sync.json.*.migration-retired` file remains, settings access stops instead of loading the legacy copy.
@@ -48,16 +48,17 @@ Global settings apply to all setups on this device; they are not remote policy.
48
48
 
49
49
  | Scope | Fields | Required values and defaults |
50
50
  | --- | --- | --- |
51
- | Document | `version`, `onSwitch`, `storageConnections`, `syncSetups` | All are required in a manually written document; supported versions are 3, 4, 5, and 6. |
51
+ | Document | `version`, `onSwitch`, `storageConnections`, `syncSetups` | All are required in a manually written document; versions 3 through 7 are supported. |
52
52
  | Current setup | `activeSyncSetup` | Required when setups exist; absent when the setup catalog is empty. |
53
53
  | Global preferences | `skipSecretScan`, `showStatus`, `debug` | Optional booleans; defaults are false, true, and false. |
54
- | Setup selection | `sync.include`, `sync.automatic` | Both are required; the manager starts with automatic sync Off. |
54
+ | Setup selection | `sync.scope`, `sync.include`, `sync.automatic` | Directory scope requires version 7 and omits `include`; selected-path setups require `include`. Both require explicit `automatic`. |
55
55
  | Setup behavior | `sync.automaticTransfer`, `sync.agentMode`, `sync.continuous`, `sync.mergeSettings`, `sync.mergeContent`, `sync.partialSync` | Optional booleans; all default to false. |
56
- | Portable policy | `sync.localFields` | Optional array; any explicit array, including `[]`, requires version 4, 5, or 6. |
57
- | Content/partial policy | `sync.mergeContent`, `sync.partialSync` | Enabling either requires version 5 or 6. |
58
- | Path exclusions | `sync.exclude` | Optional array; an explicit array, including `[]`, requires version 6. |
56
+ | Portable policy | `sync.localFields` | Optional array; any explicit array, including `[]`, requires version 4 or later. |
57
+ | Content/partial policy | `sync.mergeContent`, `sync.partialSync` | Enabling either requires version 5 or later. |
58
+ | Path exclusions | `sync.exclude` | Optional array; an explicit array, including `[]`, requires version 6 or later. |
59
+ | Directory exceptions | `sync.reinclude`, `sync.sessions` | Optional with directory scope. `reinclude` wins over `exclude`; sessions require `true`. |
59
60
 
60
- Do not downgrade version 4, 5, or 6 merely because an option is turned off.
61
+ Do not downgrade the settings version when an option is turned off.
61
62
  The four automatic controls have separate effects:
62
63
 
63
64
  - **Automatic sync** (`sync.automatic`) enables startup observation and selected-content shutdown pushes when sessions are included.
@@ -70,8 +71,7 @@ None of these controls is enabled by invoking the configuration skill.
70
71
  ### Editing in the manager
71
72
 
72
73
  Open `/sync` → **Settings** to go directly to **Pi Sync Settings**.
73
- The screen has one searchable flat list with 17 rows and no category navigation or headings.
74
- **Included paths**, **Excluded paths**, and **Compare included paths** keep content policy together; comparison covers both rule lists, not file contents.
74
+ The screen uses a searchable flat list without category navigation. Compare content rules separately from file contents; directory scope also exposes its re-inclusion and session settings.
75
75
  **Storage location** edits the current setup's coordinates, while **Manage sync setups** and **Manage storage connections** retain the catalog and affected-setup reviews.
76
76
  Returning from catalog management refreshes the rows; switching or removing the owning setup closes its old Settings screen.
77
77
 
@@ -185,8 +185,8 @@ When adding a setup, locally configured destinations are checked before content
185
185
  An occupied destination requires an explicit different path; Git requires a different branch because directories do not isolate publications on one branch.
186
186
  This check does not contact the server or discover setups configured only on other machines.
187
187
 
188
- Every setup requires `sync.include` and explicit `sync.automatic`.
189
- Setup asks for automatic sync with Off first; existing values are not rewritten.
188
+ Every setup requires explicit `sync.automatic`. Set `sync.scope` for directory scope, or set `sync.include` for selected paths.
189
+ Setup offers automatic sync with Off first. **Join an existing remote** instead saves with automatic sync and sessions off, then reviews the remote policy without transferring files. Existing values are not rewritten.
190
190
  When enabled, the current setup receives one background startup check in TUI/RPC, including reload/new/resume/fork.
191
191
  Automatic sync alone does not perform startup transfers or open dialogs; review changes through `/sync`.
192
192
  Print/JSON skip startup checks.
@@ -200,8 +200,8 @@ The check deadline is 30 seconds plus bounded cleanup, with manual retry through
200
200
  Continuous sync is a separate opt-in.
201
201
  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.
202
202
 
203
- Recommended includes the nine non-session Pi roots listed below; Minimal includes `settings.json` and `AGENTS.md`.
204
- The save review lists every selected path and the full backend destination.
203
+ New setups default to directory scope. For selected paths, Recommended includes the nine non-session Pi roots listed below and Minimal includes `settings.json` and `AGENTS.md`.
204
+ The save review shows the scope, path rules or selected paths, and the full backend destination.
205
205
  R2/S3 requires an explicitly entered existing bucket and never creates one.
206
206
  Saving setup or connection settings does not contact remote storage.
207
207
 
@@ -291,9 +291,36 @@ Authentication and transport failures give credentials/permissions or address/ne
291
291
  Git reads remote snapshots and checks its local cache; write access is not tested.
292
292
  WebDAV retains its isolated conditional-write/cleanup probe and repair of a missing active-snapshot history entry.
293
293
 
294
+ ### Agent-directory scope
295
+
296
+ In a version 7 document, a new sync setup can use:
297
+
298
+ ```json
299
+ {
300
+ "scope": "agent-directory",
301
+ "exclude": ["sessions", "bin", "npm", "skills/private"],
302
+ "reinclude": ["skills/private/shared.md"],
303
+ "automatic": false
304
+ }
305
+ ```
306
+
307
+ The agent directory is Pi's active agent root, normally `~/.pi/agent/`. Every eligible file is selected unless excluded. A re-inclusion restores an excluded path and only the descendants its rule matches. Literal directories match their subtrees. Rules are relative to the agent root; `sessions/` and `sessions` are equivalent in this scope. The `*`, `?`, and `**` syntax below applies to both lists. List order does not affect matching. If both lists are omitted, all eligible files are selected; the setup wizard saves its starter exclusions explicitly instead of adding them on every read.
308
+
309
+ Pi's `auth.json`, `trust.json`, their locks, and Pi Sync's settings and service state cannot be re-included. Pi's settings lock, dynamic model catalog cache and its lock, `crashes.json`, and `pi-debug.log` also stay local. Session paths remain local until explicitly enabled with `sync.sessions: true` (and not still excluded by a rule). The interactive flow requires a privacy acknowledgement. Symlinks are not followed. Agent-directory transfers do not move Pi's session storage root. Before moving a custom session store yourself, remove its old copy from the agent directory or exclude its old path explicitly. Pi Sync protects the current and default session locations, not unidentified old copies. Review what will transfer; the secret scan cannot identify every sensitive file.
310
+
311
+ The agent-directory scan and projected transfer result are limited to 64 MiB of file content, 16,384 files, and 65,536 visited entries. The projected result counts retained protected sessions and entries such as empty directories that are not stored in a snapshot. Directional apply and merged apply rescan before planned deletions and again before writes. The projection uses current sizes for retained files, but it does not lock out unrelated writers. `settings.json` has a separate 1 MiB limit for session routing. If local files change after review, reopen the transfer preview. A directory replacement is refused if it would remove an unreviewed or excluded descendant.
312
+
313
+ For new directory-scope transactions, the recovery journal records which image was being removed, which staging files it owns, and when the destination can remain empty. Recovery can resume if the remaining files match that evidence. If a staging attempt stops before ownership is saved, recovery can use a fresh staging path without adopting or deleting the unrecorded files. These files remain local and are excluded from sync. If Node cannot verify a stable filesystem creation time, an operation that needs a durable identity, such as resumed staging or removing a nonempty directory, stops and preserves the evidence. Recovery also stops for unrecognized data at a recorded path. Preserve the journal, backups, and remaining files for manual review. Older journals do not gain ownership evidence when you upgrade; do not downgrade with a pending journal.
314
+
315
+ Enabling sessions in the unedited recommended setup removes its starter `sessions` exclusion. If you choose to edit the starter rules or change session opt-in later in **Settings → Agent directory scope**, the toggle leaves both rule lists unchanged. For example, keep `exclude: ["sessions"]` and set `reinclude: ["sessions/work.jsonl"]` with `sessions: true` to select only that session.
316
+
317
+ **Compare sync policies** reviews the remote scope and rules without comparing file contents.
318
+
319
+ Settings version 7 and snapshot version 5 carry the new policy; older clients must refuse it. A local and remote scope mismatch stops transfer, even when forcing it. Use a matching setup or choose a new location. Adopting same-scope rules does not enable sessions on a device that has not opted in. Existing selected-path setups keep their behavior and stored settings. Changing rules does not transfer data, and excluding a path does not erase its old snapshots.
320
+
294
321
  ### Included content
295
322
 
296
- `sync.include` is ordered and duplicate-free.
323
+ Selected-path setups use ordered, duplicate-free `sync.include`.
297
324
  Supported Pi roots are:
298
325
 
299
326
  ```text
@@ -339,8 +366,7 @@ Pull protects the currently open session file; restart Pi or resume a pulled ses
339
366
  ### Excluded paths
340
367
 
341
368
  `sync.exclude` is an optional per-setup array of relative paths or basic glob patterns; absence means no rules.
342
- An explicit array requires settings version 6 and publishes snapshot version 4 with selection policy version 2.
343
- Other setups without an explicit array keep their existing snapshot format.
369
+ For selected-path setups, an explicit array requires settings version 6 or later and publishes snapshot version 4 with selection policy version 2. Selected-path setups without an explicit array keep their existing snapshot format. Directory scope uses snapshot version 5.
344
370
  New clients still read old settings and snapshots; older clients must refuse the opted-in formats.
345
371
 
346
372
  For an existing setup in a version-6 document, the `sync` object can contain:
@@ -353,7 +379,7 @@ For an existing setup in a version-6 document, the `sync` object can contain:
353
379
  }
354
380
  ```
355
381
 
356
- Rules win over includes and are anchored to the logical snapshot root, with `/` separators on every platform.
382
+ Rules win over `include` in selected-path setups and are anchored to the logical snapshot root, with `/` separators on every platform. In directory scope, a matching `reinclude` rule can restore an excluded path.
357
383
  Literal paths match themselves and their descendants; `skills/private` does not match `skills/private-copy`.
358
384
  `*` and `?` match within one segment; whole-segment `**` matches zero or more segments.
359
385
  A matching directory excludes its whole subtree, including hidden files.
@@ -362,14 +388,14 @@ Use `**/*.log` for a filename pattern at any depth; `*.log` matches only at the
362
388
  Sessions use virtual `sessions/...` paths even when stored in a custom physical directory.
363
389
  A trailing `/**` also excludes its root; excluding `sessions` or `sessions/**` disables the legacy sessions-enabled shutdown push before state/backend work.
364
390
 
365
- Negation/re-inclusion, comments, braces, character classes, extglobs, absolute/drive/UNC paths, traversal, backslashes, controls, empty rules, and case-equivalent duplicates are rejected.
391
+ Inline `!` negation, comments, braces, character classes, extglobs, absolute/drive/UNC paths, traversal, backslashes, controls, empty rules, and case-equivalent duplicates are rejected.
366
392
  The limits are 1,024 rules, 4,096 UTF-8 bytes per rule, and 256 KiB total.
367
393
  Overlapping rules and rules for currently absent or unselected paths are allowed.
368
394
  This syntax is not Git ignore compatibility and does not load an ignore file.
369
395
 
370
396
  **Settings → Excluded paths** uses a JSON-array draft and an exact **Save changes**, **Discard changes**, or **Continue editing** review.
371
397
  Empty input keeps the current draft; `[]` clears rules.
372
- Only Save writes settings and upgrades to version 6; cancelling or a stale/failed save leaves the previous valid settings intact.
398
+ Only Save writes settings; it upgrades a selected-path setup's settings to at least version 6. Cancelling or a stale/failed save leaves the previous valid settings intact.
373
399
  Changes apply to subsequent operations and do not start a transfer.
374
400
  The canonical user file is the only scope; no project override or environment-variable mirror is added.
375
401
  RPC remains read-only and shows the manual settings path.
@@ -424,8 +450,8 @@ Unknown fields remain preserved and malformed/invalid files block saves, just as
424
450
 
425
451
  ### Autonomous sync
426
452
 
427
- Autonomous sync uses the unchanged `sync.agentMode` key, an optional per-setup boolean, default `false`, in settings versions 3, 4, 5, and 6.
428
- Open **Settings → Autonomous sync** and review the setup, destination, selected paths, transfer authorization, model disclosure, costs, and autonomous writes before enabling.
453
+ Autonomous sync uses the unchanged `sync.agentMode` key, an optional per-setup boolean, default `false`, in settings versions 3 through 7.
454
+ Open **Settings → Autonomous sync** and review the setup, destination, content policy, transfer authorization, model disclosure, costs, and autonomous writes before enabling. For directory scope, the review shows session opt-in separately from path rules.
429
455
  RPC users can explicitly set the same field in the private settings file.
430
456
  Setting it to `true` is authorization, not just a display preference.
431
457
 
@@ -446,8 +472,10 @@ First-source selection, policy migrations, explicit push/pull, and rollback keep
446
472
  `--yes` does not enable Autonomous sync or authorize model disclosure.
447
473
  Completed transfers never reload resources automatically.
448
474
 
449
- The resolver uses the initiating session's selected model through Pi's public provider/authentication registry.
450
- It has an independent in-memory SDK conversation, no tools, no parent conversation, and no discovered extensions, skills, project instructions, or MCP servers.
475
+ The daemon uses the initiating session's selected model only if both agree on its full definition and authentication source.
476
+ If the daemon refuses the model, align the Pi host and the daemon's bundled Pi catalog or verify a model that matches on both sides. Selecting an older ID does not help if its definition still differs.
477
+ The daemon does not choose a fallback; ordinary sync without model resolution is unaffected.
478
+ The resolver has an independent in-memory SDK conversation, no tools, no parent conversation, and no discovered extensions, skills, project instructions, or MCP servers.
451
479
  Only conflict units are disclosed.
452
480
  Settings units contain only the conflicting root fields, with coupled fields kept together; the model selects a complete local or remote unit.
453
481
  Other fields are assembled by deterministic code.
@@ -541,8 +569,8 @@ A failed consent write blocks automatic work in that service instance. Uncertain
541
569
 
542
570
  ### Continuous sync
543
571
 
544
- `sync.continuous` is an optional per-setup boolean, default `false`, in settings versions 3, 4, 5 and 6.
545
- Open **Settings → Continuous sync** after enabling Autonomous sync.
572
+ `sync.continuous` is an optional per-setup boolean, default `false`, in settings versions 3 through 7.
573
+ Open **Settings → Continuous sync** after enabling Autonomous sync. For directory scope, the review shows session opt-in separately from path rules.
546
574
  RPC users can set the field explicitly in the private settings file.
547
575
  Existing Autonomous sync consent does not enable recurring requests.
548
576
 
@@ -674,11 +702,10 @@ Field merging and nonempty portable projections also refuse unsafe integers, non
674
702
  `sync.localFields` is an explicit sorted string array of whole global `settings.json` root field names, not a heuristic or project override.
675
703
  Example: `"localFields": ["shellPath"]`.
676
704
  Coupled fields must be excluded together.
677
- Nonempty rules require `settings.json` in `sync.include`; absent or explicitly empty rules remain valid for other selections.
678
- Saving nonempty rules in Settings confirms an upgrade to at least settings version 4; manual edits must declare version 4 or newer.
679
- Existing version-5/6 settings are never downgraded by a field-policy edit.
705
+ Selected-path setups with nonempty rules must include `settings.json` in `sync.include`. Directory-scope setups must omit `sync.include` and can configure local fields without it. Path rules still govern whether `settings.json` syncs, and nonempty field rules require that exact file spelling if it is synced. Absent or explicitly empty rules remain valid for either scope.
706
+ Settings asks for confirmation before saving changes to these rules. An explicit array requires settings version 4 or later, and editing the rules does not downgrade an existing settings version.
680
707
  Absent rules keep a setup nonportable, including unrelated setups in a version-4 document.
681
- An explicit array opts that setup into at least snapshot version 2; exclude-enabled setups retain version 4.
708
+ An explicit array opts that setup into at least snapshot version 2; exclusion-enabled selected-path setups retain version 4, and directory scope retains version 5.
682
709
  `[]` after rule removal retains this reviewed opt-in and differs from absence.
683
710
  Older clients must refuse portable data rather than replace local-only values.
684
711
 
@@ -717,8 +744,8 @@ Never reinterpret portable snapshots with an old binary.
717
744
 
718
745
  `sync.mergeContent` and `sync.partialSync` are independent opt-in booleans, both default `false`.
719
746
  The owning **Settings → Content merge / partial progress** setting offers Off, Merge only, Merge + partial, and Partial only and confirms an explicit upgrade to at least settings version 5.
720
- Manual configuration must also declare version 5 or 6.
721
- Exclude-enabled partial publications retain snapshot version 4 instead of downgrading to version 3.
747
+ Manual configuration must use a supported settings version of at least 5 (version 7 for directory scope).
748
+ Partial publications retain snapshot version 4 for exclusion-enabled selected paths and version 5 for directory scope.
722
749
  Settings version 5 retains the portable-policy behavior of version 4; moving from a legacy setup can require the existing separately confirmed directional policy migration.
723
750
  Disabling options retains the schema and recovery evidence.
724
751
 
@@ -275,7 +275,13 @@ async function showConfig(ctx: ExtensionCommandContext, options: CommandOptions)
275
275
  `startup transfer: ${startupTransferSummary(config)}`,
276
276
  `autonomous sync: ${config.agentMode ? "On" : "Off"}`,
277
277
  `continuous sync: ${config.continuous ? (config.agentMode ? "On" : "paused; Autonomous sync is Off") : "Off"}`,
278
- `included content: ${config.include.join(", ") || "none"}`,
278
+ config.scope ? "sync scope: Pi agent directory" : `included content: ${config.include.join(", ") || "none"}`,
279
+ ...(config.scope
280
+ ? [
281
+ `excluded paths: ${config.exclude?.map(safeTerminalText).join(", ") || "none"}`,
282
+ `re-included paths: ${config.reinclude?.map(safeTerminalText).join(", ") || "none"}`,
283
+ ]
284
+ : []),
279
285
  `sessions: ${syncSessionsSelected(config) ? "included" : "not included"}`,
280
286
  `settings file: ${localConfigPath()}`,
281
287
  ...warnings,