@narumitw/pi-sync-daemon 0.2.0 → 0.3.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,14 @@
1
1
  # @narumitw/pi-sync-daemon
2
2
 
3
+ ## 0.3.0
4
+
5
+ ### Minor Changes
6
+
7
+ - ea5b9f1: Exit the daemon after a 30-second grace period when no registered client PID remains and no valid active-setup after-exit grant applies. Keep live, passive, disconnected, and retired clients protected; preserve paused authorization barriers and drain committed work before releasing ownership. No new setting or final synchronization is added.
8
+
9
+ Let Pi Sync retry an authenticated idle-closing owner after confirmed process exit, with bounded, cancellable startup and no replay of submitted operations. Add the lightweight `waitForDaemonExit()` client helper. Let a later Pi Sync command reconnect after a cancelled unpublished attach by draining the old connection and using a fresh client ID and generation; keep failed cleanup blocked and never replay the cancelled operation. Publish and verify the daemon dependency before releasing Pi Sync; publication and real-data cutover still require separate approval.
10
+ - 5e251a8: Rename the daemon package to `@narumitw/pi-sync-daemon` and its executable to `pi-sync-daemon`, and update Pi Sync to use the renamed dependency. The new package does not provide the old `sync-daemon` executable alias. Stop an existing daemon before replacing its package, then use the new executable after installation. Preserve IPC identity, settings, state, recovery evidence, and authorization digests. Publish and verify the renamed dependency before releasing Pi Sync; publication and real-data cutover still require separate approval.
11
+
3
12
  ## 0.2.0
4
13
 
5
14
  ### Minor Changes
package/README.md CHANGED
@@ -44,13 +44,13 @@ node packages/pi-sync-daemon/dist/cli.js stop --root /tmp/my-pi-sync-daemon-smok
44
44
 
45
45
  `pi-sync-daemon <start|status|stop|restart|serve> --root <agent-directory>` uses an explicit root. `status` and `stop` never launch an absent service. `restart` drains the compatible owner before replacement; an incompatible or unreachable live owner fails closed. `serve` is the internal foreground launch target, not an OS registration command.
46
46
 
47
- Pi starts the service only after configured interactive synchronization is needed or an explicit setup/command authorizes it. Closing Pi detaches that client, not the shared service. `/new` and `/reload` attach a new session generation. Use `/sync daemon` for status, reviewed old-process handover, and setup-bound unattended authorization.
47
+ Pi starts the service only after configured interactive synchronization is needed or an explicit setup/command authorizes it. Closing Pi detaches that client; the daemon owns the shared lifetime decision. After no registered live client PID remains for that canonical root, a fixed 30-second grace period starts unless a valid after-exit grant keeps the service running. Explicit CLI `start` without clients follows the same rule. A client arriving before shutdown becomes final cancels automatic exit. `/new`, `/reload`, fork, and resume retain protection while their Pi process is alive. Use `/sync daemon` for status, reviewed old-process handover, and setup-bound unattended authorization.
48
48
 
49
49
  ## ⚙️ Settings
50
50
 
51
51
  Existing `pi-sync.json`, canonical `pi-sync/`, and legacy `.pisync/` remain in the selected agent directory. There is no second backend or credential configuration format. The daemon is the authoritative Pi Sync settings writer; stale reviews must reopen rather than overwrite a newer document.
52
52
 
53
- Automatic, Autonomous, and Continuous defaults remain unchanged. Old permission for work while Pi is open does not permit work after the last client exits. `/sync daemon allow-after-exit` reviews that extra permission for the current setup and selected independently reproducible provider/model; `/sync daemon revoke-after-exit` revokes it. Setup changes invalidate the saved digest. Changes to an interactive client’s model, working directory, or session-directory binding revoke older unattended grants, including across restart. Print/JSON never launch a service; passive attachment to an existing service protects their sessions and pauses automatic work. An idle service can remain alive without unattended permission.
53
+ Automatic, Autonomous, and Continuous defaults remain unchanged. Old permission for work while Pi is open does not permit work after the last client exits. `/sync daemon allow-after-exit` reviews that extra permission for the current setup and selected independently reproducible provider/model; `/sync daemon revoke-after-exit` revokes it. Setup changes invalidate the saved digest. Changes to an interactive client’s model, working directory, or session-directory binding revoke older unattended grants, including across restart. Print/JSON never launch a service; passive attachment to an existing service protects their sessions and pauses automatic work. Registered live PIDs keep the service alive, including passive, disconnected, publishing, and orderly retired clients. A valid explicit after-exit grant for the active setup keeps service lifetime under the existing fingerprint and binding rules; it does not expand transfer or model permission. Temporary provider or backend unavailability does not itself revoke that grant. Lifetime checks do not call a model, contact a provider or storage, or execute credential commands. There is no new setting, environment variable, or keep-alive flag.
54
54
 
55
55
  ## 🔒 Security and privacy
56
56
 
@@ -68,6 +68,8 @@ Close or upgrade every old Pi process before reviewed handover. An absent operat
68
68
 
69
69
  ## Recovery and development
70
70
 
71
+ Automatic exit first stops new automatic work, cancels cancellable work, and drains writes, queue-release acknowledgements, persistence, and owned callbacks before releasing ownership. It adds no final sync or model request. Uncertain consent publication, failed revocation, or cleanup failure keeps the owner paused with evidence retained; automatic restart must not restore an older grant. Repair persistence and use the existing revocation/repair path before explicit restart. The next eligible interactive client or explicit command can restart through singleton startup only after the old owner's exit is proven; print/JSON never launch a replacement.
72
+
71
73
  Stop the service before package updates, local rebuilds, or rollback, verify owner exit, and preserve pending journals and backups. A compatible connection does not upgrade a running implementation; restart explicitly after installation. Do not downgrade over pending/newer recovery evidence or restore old settings over newer bytes. Expired or old-instance operation IDs must reconcile existing journals rather than replay a possible commit. The bounded per-instance result ledger requires an explicit drained restart when full.
72
74
 
73
75
  CLI `status` reports the private lifecycle-log path. It retains at most 8 KiB of timestamps and lifecycle phases, not exception text, credentials, model output, or sync content; older entries roll over. It is diagnostic evidence, not a recovery journal. Child stdio is detached and discarded.
package/dist/cli.js CHANGED
@@ -35,14 +35,13 @@ export async function main(args) {
35
35
  try {
36
36
  server = await startServer(paths.root, service.execute, {
37
37
  ...service.hooks,
38
- close: async () => {
39
- try {
40
- await service.hooks.close();
41
- }
42
- finally {
43
- note("drained");
44
- log?.close();
45
- }
38
+ stopped: () => {
39
+ note("drained");
40
+ log?.close();
41
+ },
42
+ failure: () => {
43
+ service.hooks.failure();
44
+ note("failed");
46
45
  },
47
46
  });
48
47
  // Only the published owner may open or modify its shared diagnostic file.
package/dist/client.d.ts CHANGED
@@ -10,6 +10,8 @@ export declare function ensureDaemon(root: string, signal?: AbortSignal): Promis
10
10
  paths: import("./identity.js").DaemonPaths;
11
11
  identity: Identity;
12
12
  }>;
13
+ /** Wait only for a previously authenticated owner; never kill it or infer exit from lost contact. */
14
+ export declare function waitForDaemonExit(identity: Identity, signal?: AbortSignal): Promise<void>;
13
15
  /** Inspect an existing compatible owner without starting one. */
14
16
  export declare function findDaemon(root: string): Promise<{
15
17
  paths: import("./identity.js").DaemonPaths;
@@ -42,7 +44,7 @@ export declare class DaemonConnection {
42
44
  private polling;
43
45
  private closed;
44
46
  constructor(paths: RuntimePaths, identity: Identity, facts: ClientFacts, options: ConnectionOptions);
45
- attach(): Promise<this>;
47
+ attach(signal?: AbortSignal): Promise<this>;
46
48
  update(facts: ClientFacts): Promise<void>;
47
49
  run(operation: string, payload: unknown, signal?: AbortSignal, onCommit?: () => void): Promise<unknown>;
48
50
  private consume;
package/dist/client.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import { createHash, randomUUID } from "node:crypto";
3
3
  import { request as httpRequest } from "node:http";
4
+ import { setTimeout as delay } from "node:timers/promises";
4
5
  import { fileURLToPath } from "node:url";
5
6
  import lockfile from "proper-lockfile";
6
7
  import { daemonPaths, privateDirectory, processExists, readIdentity, readJsonBody, runtimePaths, } from "./identity.js";
@@ -53,8 +54,8 @@ export async function requestDaemon(paths, identity, method, params, signal) {
53
54
  request.end(body);
54
55
  });
55
56
  }
56
- async function hello(paths, identity) {
57
- const value = await requestDaemon(paths, identity, "hello", {});
57
+ async function hello(paths, identity, signal) {
58
+ const value = await requestDaemon(paths, identity, "hello", {}, signal);
58
59
  if (!record(value) ||
59
60
  value.version !== 1 ||
60
61
  value.root !== paths.root ||
@@ -77,18 +78,27 @@ export async function ensureDaemon(root, signal) {
77
78
  });
78
79
  try {
79
80
  signal?.throwIfAborted();
80
- const existing = await readIdentity(paths);
81
- if (existing) {
81
+ let waited = false;
82
+ for (;;) {
83
+ const existing = await readIdentity(paths);
84
+ if (!existing)
85
+ break;
82
86
  try {
83
- await hello(paths, existing);
87
+ await hello(paths, existing, signal);
84
88
  signal?.throwIfAborted();
85
89
  return { paths: daemonPaths(paths, existing.instance), identity: existing };
86
90
  }
87
91
  catch (error) {
88
92
  if (signal?.aborted)
89
93
  throw signal.reason;
94
+ if (error instanceof DaemonError && error.remote.name === "DaemonStoppingError" && !waited) {
95
+ waited = true;
96
+ await waitForDaemonExit(existing, signal);
97
+ continue;
98
+ }
90
99
  if (processExists(existing.pid))
91
100
  throw new Error("A daemon owner is alive but unavailable; use diagnostics instead of starting a second owner.", { cause: error });
101
+ break;
92
102
  }
93
103
  }
94
104
  const executable = process.versions.bun ? "node" : process.execPath;
@@ -142,7 +152,7 @@ export async function ensureDaemon(root, signal) {
142
152
  child.unref();
143
153
  });
144
154
  // Never kill a published shared daemon on caller cancellation.
145
- await hello(paths, ready);
155
+ await hello(paths, ready, signal);
146
156
  signal?.throwIfAborted();
147
157
  return { paths: daemonPaths(paths, ready.instance), identity: ready };
148
158
  }
@@ -150,6 +160,17 @@ export async function ensureDaemon(root, signal) {
150
160
  await release();
151
161
  }
152
162
  }
163
+ /** Wait only for a previously authenticated owner; never kill it or infer exit from lost contact. */
164
+ export async function waitForDaemonExit(identity, signal) {
165
+ const deadline = Date.now() + 30_000;
166
+ signal?.throwIfAborted();
167
+ while (processExists(identity.pid)) {
168
+ if (Date.now() >= deadline)
169
+ throw new Error("Closing daemon is still alive; replacement was not attempted.");
170
+ await delay(25, undefined, { signal });
171
+ }
172
+ signal?.throwIfAborted();
173
+ }
153
174
  /** Inspect an existing compatible owner without starting one. */
154
175
  export async function findDaemon(root) {
155
176
  let paths;
@@ -164,7 +185,14 @@ export async function findDaemon(root) {
164
185
  const identity = await readIdentity(paths);
165
186
  if (!identity || !processExists(identity.pid))
166
187
  return undefined;
167
- await hello(paths, identity);
188
+ try {
189
+ await hello(paths, identity);
190
+ }
191
+ catch (error) {
192
+ if (error instanceof DaemonError && error.remote.name === "DaemonStoppingError")
193
+ return undefined;
194
+ throw error;
195
+ }
168
196
  return { paths: daemonPaths(paths, identity.instance), identity };
169
197
  }
170
198
  /** Gracefully stop an existing compatible owner without creating a new service. */
@@ -211,15 +239,17 @@ export class DaemonConnection {
211
239
  this.facts = facts;
212
240
  this.options = options;
213
241
  }
214
- async attach() {
242
+ async attach(signal) {
215
243
  if (this.closed || this.uncertain)
216
244
  throw new Error("Daemon client is unavailable; reconnect after draining work.");
217
- const request = requestDaemon(this.paths, this.identity, "attach", this.facts, this.controller.signal);
245
+ const request = requestDaemon(this.paths, this.identity, "attach", this.facts, signal ? AbortSignal.any([signal, this.controller.signal]) : this.controller.signal);
218
246
  // Poll during attach: stopping a previous controller may need release answers
219
247
  // from this reattached participant before the attach response can complete.
220
248
  this.polling ??= this.poll();
249
+ let admitted = false;
221
250
  try {
222
251
  const result = await request;
252
+ admitted = true;
223
253
  this.consume(result);
224
254
  this.attached = true;
225
255
  return this;
@@ -227,7 +257,27 @@ export class DaemonConnection {
227
257
  catch (error) {
228
258
  return withCleanup(async () => {
229
259
  throw error;
230
- }, () => this.dispose());
260
+ }, async () => {
261
+ try {
262
+ await this.dispose();
263
+ }
264
+ catch (cleanupError) {
265
+ if (!admitted &&
266
+ !this.attached &&
267
+ this.closed &&
268
+ !this.callbacks.size &&
269
+ !this.callbackTasks.size &&
270
+ !this.completedCallbacks.size &&
271
+ error instanceof DaemonError &&
272
+ error.remote.name === "DaemonStoppingError") {
273
+ // The fenced first attach owned no grants, and local tasks have drained.
274
+ // Keep its retry marker even if the owner closes the cleanup transport.
275
+ error.cause = cleanupError;
276
+ return;
277
+ }
278
+ throw cleanupError;
279
+ }
280
+ });
231
281
  }
232
282
  }
233
283
  update(facts) {
@@ -7,5 +7,8 @@ export declare function createEngineService(root: string): {
7
7
  factsChanged: () => Promise<void>;
8
8
  idle: () => void;
9
9
  close: () => Promise<void>;
10
+ lifetime: () => Promise<import("./idle-exit.js").IdleExitPolicy>;
11
+ quiesce: () => Promise<void>;
12
+ failure: () => void;
10
13
  };
11
14
  };
@@ -268,7 +268,14 @@ export function createEngineService(root) {
268
268
  return {
269
269
  execute,
270
270
  bind: monitor.bind,
271
- hooks: { factsChanged: monitor.factsChanged, idle: monitor.schedule, close: monitor.close },
271
+ hooks: {
272
+ factsChanged: monitor.factsChanged,
273
+ idle: monitor.schedule,
274
+ close: monitor.close,
275
+ lifetime: monitor.lifetime,
276
+ quiesce: monitor.pause,
277
+ failure: monitor.blockAutomatic,
278
+ },
272
279
  };
273
280
  }
274
281
  async function withJobTimings(ctx, execution, label, action) {
@@ -0,0 +1,17 @@
1
+ export declare const IDLE_EXIT_GRACE_MS = 30000;
2
+ export type IdleExitPolicy = "exit" | "keep" | "pause";
3
+ interface IdleExitHooks {
4
+ live(): boolean;
5
+ policy(): Promise<IdleExitPolicy>;
6
+ quiesce(): Promise<void>;
7
+ close(current: () => boolean): Promise<boolean>;
8
+ resume(): void;
9
+ failed(): void;
10
+ }
11
+ /** The server heartbeat owns timing; this controller owns only one guarded deadline and evaluation. */
12
+ export declare function createIdleExit(hooks: IdleExitHooks): {
13
+ changed: () => void;
14
+ tick(): Promise<void>;
15
+ dispose(): Promise<void>;
16
+ };
17
+ export {};
@@ -0,0 +1,77 @@
1
+ export const IDLE_EXIT_GRACE_MS = 30_000;
2
+ /** The server heartbeat owns timing; this controller owns only one guarded deadline and evaluation. */
3
+ export function createIdleExit(hooks) {
4
+ let generation = 0;
5
+ let stopped = false;
6
+ let failed = false;
7
+ let emptySince;
8
+ let running;
9
+ const changed = () => {
10
+ generation++;
11
+ if (hooks.live())
12
+ emptySince = undefined;
13
+ };
14
+ async function evaluate() {
15
+ if (stopped || failed)
16
+ return;
17
+ if (hooks.live()) {
18
+ emptySince = undefined;
19
+ return;
20
+ }
21
+ const epoch = generation;
22
+ const current = () => !stopped && !failed && generation === epoch && !hooks.live();
23
+ let quiesced = false;
24
+ try {
25
+ const policy = await hooks.policy();
26
+ if (!current())
27
+ return;
28
+ if (policy !== "exit") {
29
+ emptySince = undefined;
30
+ return;
31
+ }
32
+ emptySince ??= Date.now();
33
+ if (Date.now() - emptySince < IDLE_EXIT_GRACE_MS)
34
+ return;
35
+ quiesced = true;
36
+ await hooks.quiesce();
37
+ if (!current())
38
+ return;
39
+ const latest = await hooks.policy();
40
+ if (!current())
41
+ return;
42
+ if (latest !== "exit") {
43
+ emptySince = undefined;
44
+ return;
45
+ }
46
+ if (await hooks.close(current))
47
+ stopped = true;
48
+ else if (hooks.live())
49
+ emptySince = undefined;
50
+ }
51
+ catch {
52
+ // A failed drain must not be cleared by an implicit restart or another heartbeat.
53
+ failed = true;
54
+ hooks.failed();
55
+ }
56
+ finally {
57
+ if (quiesced && !stopped && !failed)
58
+ hooks.resume();
59
+ }
60
+ }
61
+ return {
62
+ changed,
63
+ tick() {
64
+ if (!running) {
65
+ running = evaluate().finally(() => {
66
+ running = undefined;
67
+ });
68
+ }
69
+ return running;
70
+ },
71
+ async dispose() {
72
+ stopped = true;
73
+ generation++;
74
+ await running;
75
+ },
76
+ };
77
+ }
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export type { ConnectionOptions } from "./client.js";
2
- export { DaemonConnection, DaemonError, ensureDaemon, findDaemon, requestDaemon, stopDaemon } from "./client.js";
2
+ export { DaemonConnection, DaemonError, ensureDaemon, findDaemon, requestDaemon, stopDaemon, waitForDaemonExit, } from "./client.js";
3
3
  export type { DocumentView } from "./document.js";
4
4
  export { documentFingerprint } from "./document.js";
5
5
  export type { EngineContext, EngineHost, EngineSession, ReviewRequest } from "./engine/host.js";
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- export { DaemonConnection, DaemonError, ensureDaemon, findDaemon, requestDaemon, stopDaemon } from "./client.js";
1
+ export { DaemonConnection, DaemonError, ensureDaemon, findDaemon, requestDaemon, stopDaemon, waitForDaemonExit, } from "./client.js";
2
2
  export { documentFingerprint } from "./document.js";
3
3
  export { modelSignature } from "./model-signature.js";
4
4
  export { MAX_SETTINGS_BYTES, PROTOCOL_VERSION } from "./protocol.js";
package/dist/monitor.d.ts CHANGED
@@ -1,9 +1,12 @@
1
+ import type { IdleExitPolicy } from "./idle-exit.js";
1
2
  import type { Execution } from "./protocol.js";
2
3
  import type { startServer } from "./server.js";
3
4
  import type { installServiceHost } from "./service-host.js";
4
5
  export declare function createMonitor(root: string, host: ReturnType<typeof installServiceHost>): {
5
6
  bind(value: Awaited<ReturnType<typeof startServer>>): void;
6
7
  schedule: () => void;
8
+ lifetime: () => Promise<IdleExitPolicy>;
9
+ blockAutomatic: () => void;
7
10
  explicitSync(setup: string, execution: Execution): void;
8
11
  pause(): Promise<void>;
9
12
  factsChanged(): Promise<void>;
package/dist/monitor.js CHANGED
@@ -27,6 +27,11 @@ export function createMonitor(root, host) {
27
27
  transition = transition.then(start).catch(() => { });
28
28
  });
29
29
  }
30
+ function blockAutomatic() {
31
+ authorizationFailed = true;
32
+ retries.clear();
33
+ task?.controller.abort(new DOMException("Daemon safety barrier", "AbortError"));
34
+ }
30
35
  async function stop() {
31
36
  const current = task;
32
37
  if (!current)
@@ -36,6 +41,29 @@ export function createMonitor(root, host) {
36
41
  await current.continuous.stop();
37
42
  await current.promise;
38
43
  }
44
+ function unattendedGrant(config) {
45
+ if (!config.continuous || !config.agentMode)
46
+ return undefined;
47
+ const saved = readConsent(root)?.setups[config.setupName];
48
+ return saved?.afterExit && saved.fingerprint === consentFingerprint(root, config) ? saved : undefined;
49
+ }
50
+ async function lifetime() {
51
+ if (closed || authorizationFailed)
52
+ return "pause";
53
+ try {
54
+ const consent = readConsent(root);
55
+ if (!consent || !Object.values(consent.setups).some((saved) => saved.afterExit))
56
+ return "exit";
57
+ const config = await loadConfigForCheck();
58
+ if (closed || authorizationFailed)
59
+ return "pause";
60
+ return unattendedGrant(config) ? "keep" : "exit";
61
+ }
62
+ catch {
63
+ // Invalid evidence is not an implicit revocation or permission to discard a safety barrier.
64
+ return "pause";
65
+ }
66
+ }
39
67
  async function start() {
40
68
  const service = server;
41
69
  if (!service)
@@ -56,13 +84,12 @@ export function createMonitor(root, host) {
56
84
  const { pendingTransactionEntries } = await import("./engine/snapshot/snapshot-transaction-directory.js");
57
85
  if ((await pendingTransactionEntries()).some((entry) => entry.isDirectory()) || !available())
58
86
  return;
59
- const fingerprint = consentFingerprint(root, config);
60
87
  const peers = service.participants();
61
88
  if (peers.some((peer) => !peer.idle || peer.ready !== true))
62
89
  return;
63
- const authorized = consent.setups[config.setupName];
90
+ const authorized = unattendedGrant(config);
64
91
  const selected = peers.toSorted((a, b) => a.id.localeCompare(b.id))[0];
65
- if (!selected && (!authorized?.afterExit || authorized.fingerprint !== fingerprint))
92
+ if (!selected && !authorized)
66
93
  return;
67
94
  if (!continuous) {
68
95
  const { createContinuousSync } = await import("./engine/sync/continuous-sync.js");
@@ -117,9 +144,8 @@ export function createMonitor(root, host) {
117
144
  JSON.stringify(peer.model) === JSON.stringify(binding) &&
118
145
  peer.sessionDir === sessionDir &&
119
146
  peer.cwd === cwd);
120
- const saved = readConsent(root)?.setups[currentConfig.setupName];
121
- return Boolean(saved?.afterExit &&
122
- saved.fingerprint === consentFingerprint(root, currentConfig) &&
147
+ const saved = unattendedGrant(currentConfig);
148
+ return Boolean(saved &&
123
149
  JSON.stringify(saved.model) === JSON.stringify(binding) &&
124
150
  saved.sessionDir === sessionDir &&
125
151
  (saved.cwd ?? root) === cwd);
@@ -201,6 +227,8 @@ export function createMonitor(root, host) {
201
227
  schedule();
202
228
  },
203
229
  schedule,
230
+ lifetime,
231
+ blockAutomatic,
204
232
  explicitSync(setup, execution) {
205
233
  const peer = execution.facts();
206
234
  if (!closed && peer)
@@ -222,8 +250,7 @@ export function createMonitor(root, host) {
222
250
  }
223
251
  }
224
252
  catch (error) {
225
- authorizationFailed = true;
226
- retries.clear();
253
+ blockAutomatic();
227
254
  // Recovery barriers must not prevent passive clients from registering protection.
228
255
  if (error instanceof ConsentPublicationError)
229
256
  failure = error;
@@ -1,5 +1,10 @@
1
1
  import type { Api, Model } from "@earendil-works/pi-ai";
2
2
  export declare const PROTOCOL_VERSION = 1;
3
+ /** Authenticated idle shutdown after work is drained; callers may wait for this owner to exit. */
4
+ export declare class DaemonStoppingError extends Error {
5
+ name: string;
6
+ constructor();
7
+ }
3
8
  export declare const MAX_MESSAGE_BYTES: number;
4
9
  export declare const REVIEW_PAGE_CHARS: number;
5
10
  export declare const MAX_REVIEW_BYTES: number;
package/dist/protocol.js CHANGED
@@ -1,6 +1,13 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import path from "node:path";
3
3
  export const PROTOCOL_VERSION = 1;
4
+ /** Authenticated idle shutdown after work is drained; callers may wait for this owner to exit. */
5
+ export class DaemonStoppingError extends Error {
6
+ name = "DaemonStoppingError";
7
+ constructor() {
8
+ super("Daemon is closing after its idle grace period; wait for owner exit before reconnecting.");
9
+ }
10
+ }
4
11
  export const MAX_MESSAGE_BYTES = 4 * 1024 * 1024;
5
12
  export const REVIEW_PAGE_CHARS = 64 * 1024;
6
13
  export const MAX_REVIEW_BYTES = 16 * 1024 * 1024;
package/dist/server.d.ts CHANGED
@@ -1,8 +1,13 @@
1
+ import { type IdleExitPolicy } from "./idle-exit.js";
1
2
  import { type ClientFacts, type Execute, type Execution, type Identity } from "./protocol.js";
2
3
  export interface ServerHooks {
3
4
  factsChanged?(): Promise<void>;
4
5
  idle?(): void;
5
6
  close?(): Promise<void>;
7
+ lifetime?(): Promise<IdleExitPolicy>;
8
+ quiesce?(): Promise<void>;
9
+ stopped?(): void;
10
+ failure?(): void;
6
11
  }
7
12
  export declare function startServer(root: string, execute: Execute, hooks?: ServerHooks): Promise<{
8
13
  identity: Identity;
@@ -13,6 +18,7 @@ export declare function startServer(root: string, execute: Execute, hooks?: Serv
13
18
  participants: () => ClientFacts[];
14
19
  liveClients: () => ClientFacts[];
15
20
  expireClients: () => Promise<void>;
21
+ checkLifetime: () => Promise<void>;
16
22
  isIdle: () => boolean;
17
23
  readonly closed: boolean;
18
24
  }>;
package/dist/server.js CHANGED
@@ -5,9 +5,10 @@ import path from "node:path";
5
5
  import lockfile from "proper-lockfile";
6
6
  import { endpointOwner } from "./endpoint.js";
7
7
  import { canonicalRootGuard, daemonPaths, privateDirectory, processExists, publishIdentity, readIdentity, readJsonBody, runtimePaths, } from "./identity.js";
8
+ import { createIdleExit } from "./idle-exit.js";
8
9
  import { withCleanup } from "./lifecycle.js";
9
10
  import { ParticipantAdmission } from "./participant-admission.js";
10
- import { MAX_MESSAGE_BYTES, MAX_REVIEW_BYTES, operationPrefix, PROTOCOL_VERSION, REVIEW_PAGE_CHARS, record, remoteError, validateFacts, validateHandoff, validId, } from "./protocol.js";
11
+ import { DaemonStoppingError, MAX_MESSAGE_BYTES, MAX_REVIEW_BYTES, operationPrefix, PROTOCOL_VERSION, REVIEW_PAGE_CHARS, record, remoteError, validateFacts, validateHandoff, validId, } from "./protocol.js";
11
12
  export async function startServer(root, execute, hooks = {}) {
12
13
  const base = await runtimePaths(root);
13
14
  const identity = {
@@ -49,13 +50,22 @@ export async function startServer(root, execute, hooks = {}) {
49
50
  const peersFile = path.join(paths.directory, "clients.json");
50
51
  let sequence = 0;
51
52
  let closed = false;
53
+ let automaticClosing = false;
54
+ let peerWriteFailed = false;
55
+ let idleExit;
56
+ let expiring;
57
+ const peerOperations = new Set();
52
58
  let queue = Promise.resolve();
53
59
  let closing;
54
60
  let peerWrites = Promise.resolve();
55
61
  let heartbeat;
56
62
  function savePeers() {
63
+ idleExit?.changed();
57
64
  const operation = peerWrites.then(writePeers);
58
- peerWrites = operation.catch(() => { });
65
+ peerWrites = operation.catch(() => {
66
+ peerWriteFailed = true;
67
+ hooks.failure?.();
68
+ });
59
69
  return operation;
60
70
  }
61
71
  async function writePeers() {
@@ -153,6 +163,8 @@ export async function startServer(root, execute, hooks = {}) {
153
163
  }
154
164
  };
155
165
  const assertOwner = () => {
166
+ if (automaticClosing && !compromised)
167
+ throw new DaemonStoppingError();
156
168
  if (closed || compromised)
157
169
  throw new Error("Daemon ownership is no longer valid.");
158
170
  assertRoot();
@@ -375,6 +387,8 @@ export async function startServer(root, execute, hooks = {}) {
375
387
  return result;
376
388
  }
377
389
  async function handle(method, params, signal) {
390
+ if (automaticClosing && method !== "stop")
391
+ throw new DaemonStoppingError();
378
392
  const cleanup = ["answer", "poll", "cancel", "detach", "pause", "handoff", "stop"].includes(method);
379
393
  if (!published && !cleanup)
380
394
  throw new Error("Daemon readiness is not published.");
@@ -590,7 +604,12 @@ export async function startServer(root, execute, hooks = {}) {
590
604
  admissionController = new AbortController();
591
605
  response.once("close", disconnect);
592
606
  }
593
- respond(response, 200, { result: await handle(body.method, body.params, admissionController?.signal) });
607
+ const operation = handle(body.method, body.params, admissionController?.signal);
608
+ if (["attach", "update", "detach", "pause", "handoff"].includes(body.method)) {
609
+ peerOperations.add(operation);
610
+ void operation.finally(() => peerOperations.delete(operation)).catch(() => { });
611
+ }
612
+ respond(response, 200, { result: await operation });
594
613
  }
595
614
  catch (error) {
596
615
  if (!response.destroyed)
@@ -617,7 +636,15 @@ export async function startServer(root, execute, hooks = {}) {
617
636
  throw error;
618
637
  }, () => withCleanup(() => endpoint.close(), release));
619
638
  }
620
- async function expireClients() {
639
+ function expireClients() {
640
+ expiring ??= expire().finally(() => {
641
+ expiring = undefined;
642
+ });
643
+ return expiring;
644
+ }
645
+ async function expire() {
646
+ if (closed)
647
+ return;
621
648
  let changed = false;
622
649
  for (const [id, peer] of participants) {
623
650
  const exited = !processExists(peer.facts.pid);
@@ -646,8 +673,56 @@ export async function startServer(root, execute, hooks = {}) {
646
673
  await hooks.factsChanged?.();
647
674
  }
648
675
  }
676
+ const lifetime = async () => closed || compromised || peerWriteFailed ? "pause" : ((await hooks.lifetime?.()) ?? "pause");
677
+ if (hooks.lifetime) {
678
+ idleExit = createIdleExit({
679
+ live: () => liveClientFacts().length > 0,
680
+ policy: lifetime,
681
+ quiesce: async () => {
682
+ for (const job of [...jobs.values(), ...backgroundJobs])
683
+ if (!job.committed)
684
+ job.controller.abort(new DOMException("Daemon idle shutdown", "AbortError"));
685
+ await hooks.quiesce?.();
686
+ await Promise.allSettled([...jobs.values()].map((job) => job.promise));
687
+ await Promise.allSettled([...peerOperations]);
688
+ await expiring;
689
+ await peerWrites;
690
+ },
691
+ close: (current) => admission.run(async () => {
692
+ if (!current() || closed || peerWriteFailed || peerOperations.size)
693
+ return false;
694
+ await peerWrites;
695
+ const owned = await known();
696
+ const policy = await lifetime();
697
+ if (!owned ||
698
+ policy !== "exit" ||
699
+ !current() ||
700
+ closed ||
701
+ compromised ||
702
+ peerWriteFailed ||
703
+ peerOperations.size ||
704
+ backgroundJobs.size ||
705
+ pending.size ||
706
+ [...jobs.values()].some((job) => job.view.phase === "queued" || job.view.phase === "running"))
707
+ return false;
708
+ assertRoot();
709
+ // Fence new admissions synchronously, then close outside the gate and monitor transition.
710
+ automaticClosing = true;
711
+ closed = true;
712
+ setImmediate(() => {
713
+ void close().catch(() => { });
714
+ });
715
+ return true;
716
+ }),
717
+ resume: () => hooks.idle?.(),
718
+ failed: () => hooks.failure?.(),
719
+ });
720
+ void idleExit.tick();
721
+ }
649
722
  heartbeat = setInterval(() => {
650
- void expireClients().catch(() => { });
723
+ void expireClients()
724
+ .then(() => idleExit?.tick())
725
+ .catch(() => { });
651
726
  }, 1_000);
652
727
  heartbeat.unref();
653
728
  async function close() {
@@ -662,6 +737,7 @@ export async function startServer(root, execute, hooks = {}) {
662
737
  for (const job of [...jobs.values(), ...backgroundJobs])
663
738
  if (!job.committed)
664
739
  job.controller.abort(new DOMException("Daemon stopping", "AbortError"));
740
+ await idleExit?.dispose();
665
741
  let closeError;
666
742
  try {
667
743
  await hooks.close?.();
@@ -671,15 +747,21 @@ export async function startServer(root, execute, hooks = {}) {
671
747
  }
672
748
  await Promise.allSettled([...jobs.values()].map((job) => job.promise));
673
749
  await admission.run(async () => { });
750
+ await Promise.allSettled([...peerOperations]);
751
+ await expiring;
752
+ await peerWrites;
674
753
  for (const waiting of [...pending.values()])
675
754
  waiting.reject(new Error("Daemon stopping."));
755
+ // A failed engine drain must retain the live owner, not permit an implicit restart.
756
+ if (closeError)
757
+ throw closeError;
676
758
  await endpoint.close();
677
759
  if (await known())
678
760
  await fs.rm(paths.identity, { force: true });
679
761
  await release();
680
- if (closeError)
681
- throw closeError;
762
+ hooks.stopped?.();
682
763
  })().catch((error) => {
764
+ hooks.failure?.();
683
765
  closing = undefined;
684
766
  throw error;
685
767
  });
@@ -716,6 +798,8 @@ export async function startServer(root, execute, hooks = {}) {
716
798
  participants: participantFacts,
717
799
  liveClients: liveClientFacts,
718
800
  expireClients,
801
+ // The heartbeat and deterministic lifecycle tests use the same evaluation boundary.
802
+ checkLifetime: () => idleExit?.tick() ?? Promise.resolve(),
719
803
  isIdle: () => !closed && [...jobs.values()].every((job) => job.view.phase !== "queued" && job.view.phase !== "running"),
720
804
  get closed() {
721
805
  return closed;
@@ -79,7 +79,12 @@ Terminal formatting utilities are not interactive components. No daemon-owned me
79
79
  | Missing independent credentials | Public SDK failure; no parent-runtime key extraction | Synthetic resolver tests |
80
80
  | No resolver request / cancellation after credential runtime creation | Metadata uses memory credentials without auth refresh / settle already-started SDK credential writes before releasing owner | Resolver lifecycle tests |
81
81
  | Model output / stale candidate / refusal | Candidate only / revalidate all evidence / retain budget and refusal policy | Existing agent suites |
82
- | Last Pi exit without reviewed daemon-era permission | Service may stay alive; no unattended transfer or inference | Zero-client tests |
82
+ | No registered live PID and no valid active-setup after-exit grant / explicit CLI start without clients | Fixed 30-second grace, then quiesce and drain before safe exit; no final sync or inference | Lifecycle timer and process tests |
83
+ | Registered live PID, including passive, disconnected, publishing, or retired clients / uncertain PID probe | Retain lifetime and session protection; detach or heartbeat loss is not proof of exit | Live-PID and lifecycle tests |
84
+ | Client arrives during grace or quiescing, before final closing boundary | Cancel automatic exit; preserve one owner through admission | Admission and reattachment race tests |
85
+ | Valid active-setup grant / temporarily unavailable provider or backend | Retain lifetime under existing consent, fingerprint, and binding rules; no new work permission or availability probe | Consent and monitor tests |
86
+ | Uncertain consent publication, failed revocation, or cleanup failure | Stay paused; retain evidence and repair/revoke before explicit restart, without restoring an older grant | Consent failure and shutdown tests |
87
+ | Recognized closing owner / next eligible interactive client | Bounded cancellable wait; prove old-owner exit before singleton replacement; passive clients never launch | Closing-owner startup tests |
83
88
  | Print/JSON, no existing service / existing service | No launch / passive protection and automatic-work pause; never an implicit unattended grant | Bootstrap and actual-session-facts tests |
84
89
  | Orderly exit / ambiguous disconnection / replacement handoff | Retain live-PID file protection without active participation / pause and retain protection / require matching published successor | Server, handoff, and native post-exit model tests |
85
90
  | Config/model/consent changes during unattended review | Reject before publication, preserving new data | Consent tests |
@@ -90,6 +95,30 @@ Terminal formatting utilities are not interactive components. No daemon-owned me
90
95
 
91
96
  The source-linked matrix is the audit contract, not a list of already completed checks. The implementation plan records actual results separately.
92
97
 
98
+ ## Automatic service lifetime
99
+
100
+ The daemon owns lifetime for one canonical agent directory and its registered client PIDs, not every Pi process on the machine. Live disconnected, passive, publishing, and orderly retired clients count. `/reload`, `/new`, fork, and resume do not close the shared owner while their Pi process remains alive. An empty participant list, detach, transport failure, or heartbeat timeout is not proof of process exit.
101
+
102
+ When no registered live PID remains and no valid explicit after-exit grant covers the active setup, start a fixed 30-second grace period. The same policy applies to a service explicitly started without clients. A client arriving before the final closing boundary cancels automatic exit. Grants for other setups, revoked grants, and stale fingerprints do not preserve lifetime. Temporary provider or backend unavailability does not itself revoke a valid grant. Lifetime checks reuse existing consent authority without calling a model, contacting a provider or storage, executing credential commands, or changing authorization. No setting, environment variable, or keep-alive flag controls this policy.
103
+
104
+ After grace, stop new automatic work and cancel cancellable work. Drain foreground and monitor work, committed writes, admission, queue-release acknowledgements, peer persistence, and owned callbacks before endpoint and owner-lock release. Do not add a closing sync or model request. Preserve journals, backups, request accounting, and existing transfer permissions. Recheck liveness, consent, generation, and ownership after asynchronous reads or drains; the final admission boundary must let an earlier queued attach win and make a later attach observe closing. Cleanup failure is not successful exit.
105
+
106
+ After quiescence, the authenticated final fence returns `RemoteError.name = "DaemonStoppingError"` to rejected admissions and handshakes on the existing version-1 protocol. `ensureDaemon()` recognizes only this error and waits at most 30 seconds for the recorded PID to exit before singleton startup. The lightweight public `waitForDaemonExit(identity, signal)` helper provides the same cancellable process-exit check for an attach race; it never kills the owner or treats lost contact as exit. Pi Sync retries only an unpublished connection, at most once, and does not replay submitted operations. A rejected first attach preserves this stopping error after local disposal when no callbacks or prior attachment can own grants; a failed cleanup transport remains available as the error cause. Other combined attach and cleanup failures remain aggregate errors and do not authorize a retry. `DaemonConnection.attach(signal)` cancels queued admission without stopping the shared owner; the signal does not own the established connection's lifetime. The next eligible interactive client or explicit command may start after proven owner exit. An incompatible identity, uncertain ownership, or unreachable live owner still fails closed. Print/JSON never launch a service. Manual stop and restart retain explicit behavior. Authorization uncertainty and failed revocation remain paused, not cleared by an implicit restart that could restore an older persisted grant.
107
+
108
+ A later command can reconnect after a cancelled or failed unpublished attach. First, Pi Sync confirms the old connection's detach and drain, then releases its local queue grants. It uses a fresh client ID and generation for the next connection. Daemon retirement records stay intact, so late requests cannot revive the old attempt. Failed cleanup blocks a new identity and operation; it does not release uncertain grants. The established connection keeps its identity. A cancelled or submitted operation is never replayed by this recovery.
109
+
110
+ ## Repository lifetime smoke
111
+
112
+ After the repository build, run the standalone real-clock smoke from the repository root. It loads the built package directory through real Pi RPC, tests no-client CLI exit and last-Pi exit, restarts through the next eligible Pi, and retains an explicitly reviewed grant beyond the grace period. It uses only owned loopback provider/storage fixtures and preserves recovery bytes. It takes about two minutes; it is not a Vitest case.
113
+
114
+ ```sh
115
+ npm exec -- tsc -p tsconfig.test.json
116
+ cp -R packages/pi-sync/test/fixtures node_modules/.cache/pi-extensions-test/packages/pi-sync/test/
117
+ node node_modules/.cache/pi-extensions-test/packages/pi-sync/test/idle-exit-cli-smoke.js
118
+ ```
119
+
120
+ Do not rebuild while a smoke-owned daemon is running. Linux containers need an init process to reap detached children. This smoke does not verify native Windows behavior, terminal logout, physical power loss, or real-data cutover.
121
+
93
122
  ## Cross-process apply protocol
94
123
 
95
124
  Acquire target queues in deterministic client-ID and canonical-target order. Each reservation has a job-bound ID and the peer's session generation. The client holds Pi's public queues until the daemon acknowledges completion with a `queue-release` callback. Release uses the reservation ID even if the grant response was lost. A cancelled UI callback does not release an acquired grant. If IPC disappears, hold the grant until explicit release or proof that its daemon process exited. A timeout is not such proof.
@@ -116,7 +145,7 @@ Each POSIX instance binds inside an exclusively created 0700 directory; this par
116
145
 
117
146
  The model signature hashes the exact existing JSON serialization. Equal hashes preserve the engine's existing candidate keys and Continuous configuration identity; a definition with different serialization is unavailable, not a reason to reset budgets. Static metadata uses an in-memory credential store and no refresh. Only an actual resolver transport creates the public SDK credential runtime. Its final public `transformHeaders` hook revalidates capability and evidence after auth awaits, without returning header values to Pi.
118
147
 
119
- Unattended permission stores a setup/policy digest and an independent model/location binding, not a former Pi context. Normal closed clients remain in the durable protected-session ledger while their PID is alive but do not block zero-client scheduling; ambiguous losses and replacement gaps do. `Execution.liveClients()` supplies file protection and the missing-settings guard, while `Execution.participants()` supplies queue reservations and work eligibility. An unrelated attach or daemon restart does not remove retired protection. Only confirmed PID exit or a matching published replacement releases the corresponding record. A consent publication failure latches automatic work off for that service instance; repair persistence and revoke the retained grant before an explicit restart.
148
+ Unattended permission stores a setup/policy digest and an independent model/location binding, not a former Pi context. Normal closed clients remain in the durable protected-session ledger while their PID is alive but do not block zero-client scheduling; ambiguous losses and replacement gaps do. `Execution.liveClients()` supplies file protection and the missing-settings guard, while `Execution.participants()` supplies queue reservations and work eligibility. An unrelated attach or daemon restart does not remove retired protection. Only confirmed PID exit or a matching published replacement releases the corresponding record. A consent publication failure latches automatic work off for that service instance and prevents automatic exit from silently clearing the barrier. Failed revocation or uncertain consent must not restore an older persisted grant through implicit restart; retain the paused owner and evidence, repair persistence, and revoke the retained grant before an explicit restart.
120
149
 
121
150
  The resolver uses independently available agent-root `auth.json`/`models.json` configuration and the environment captured at service start. Credential commands execute non-interactively from the canonical agent root, not from a former Pi working directory. Handover must disclose this provider/account boundary; changing the service environment requires a restart. Parent runtime accounts, registered providers, and conversations are not copied.
122
151
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@narumitw/pi-sync-daemon",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "A local synchronization daemon with a versioned client API.",
5
5
  "type": "module",
6
6
  "license": "MIT",