Skip to content

fix(host-kit): pin ps lstart reads to the C locale so daemon stop finds a live daemon - #4682

Merged
thymikee merged 24 commits into
callstack:mainfrom
pcbeingused333:fix/ps-lstart-locale
Nov 21, 2026
Merged

thymikee merged 24 commits into
callstack:mainfrom
pcbeingused333:fix/ps-lstart-locale

Conversation

@pcbeingused333

@pcbeingused333 pcbeingused333 commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #4656. On macOS and BSD, a daemon and a client with different locales read different ps lstart strings for one process, so a stop could discard the registration of a live daemon.

Start-time reads now pin LC_ALL=C TZ=UTC and store a posix:<epochMs> token. A raw value from an older release, or a malformed token, is unverified: nothing is signaled or discarded. Linux /proc and Windows keep their identity sources.

Accepted trade-off: on macOS and BSD, do not run an older and a newer build on one host. The help and commands.md state the limits.

Before / after

Daemon started under LC_ALL=fr_FR.UTF-8 TZ=Pacific/Kiritimati, stopped from LC_ALL=C TZ=UTC:

base (#4656): stop reads a different start time and can discard the registration of the live daemon
head: stop verifies the identity and the daemon shuts down gracefully

With a raw legacy start time in daemon.json:

head: stop refuses with details.terminationReason identity-unverified, sends no signal, keeps daemon.json and the lock

Validation

  • 14bcb79cb0, macOS, disposable state dir: both rows above.
  • 21985d3fc8: pnpm check:quick and focused unit runs passed; the malformed-token regressions fail without the fix.
  • Mixed-version run (0.21.41 against this branch, iOS simulator, isolated dirs): separate state dirs fail closed both ways; the orphan case is closed by fix(daemon): close a detached daemon that finds its registration deleted or replaced #4837.
  • a8c4bbf453: out-of-range posix: tokens are malformed; regressions fail without the fix. 1ce8933f82 keeps host-process.ts under 1000 lines (shared sysctl options); host-kit and closure-budget tests pass. Hosted CI owns the full gate.

Disclosure

This change was prepared with the help of an AI coding assistant (Claude Code) and submitted by the account holder.


Autofix with [code]smith
Open in [code]smith · Need help on this PR? Tag @codesmith-bot with what you need.

View guided diff

@thymikee

Copy link
Copy Markdown
Member

The locale pin in 70f0b17 is too wide: it also changes how command text is read, and that breaks managed-process ownership for non-ASCII paths.

The pin applies to every host-kit ps read, including the pid=,command= batch read and readProcessField('command='/'state=') (host-process.ts:200). Only lstart needs it. BSD/macOS ps escapes non-ASCII argv bytes under LC_ALL=C: a process started with /Users/mich/é/ü prints that path by default and /Users/mich/M-CM-)/M-CM-< under the pin. listHostProcesses stays unpinned, so one scan now compares UTF-8 command text with escaped text. In agent-browser-process-record.ts:161-162, first.command === last.command && command === first.command compares the pinned read with the unpinned list. A managed Chrome or agent-browser process with a non-ASCII argv path (a non-ASCII home dir or --user-data-dir) fails that filter, so it is never recorded or cleaned up. The command matchers in judgeProcessIdentity (host-process.ts:789-796) and the app-log and recording matchers see the escaped text too. They then either refuse to signal or report the process as reassigned. Before this PR both reads used the same locale and agreed. The rule the code must satisfy: no command text read by host-kit changes encoding between callers, and every ps read whose output contains lstart is pinned. The set of sites is the lstart-bearing reads, meaning HOST_PROCESS_IDENTITY_PS_ARGS (sync and async) and readProcessField when the field is lstart=. Please add a regression that asserts the pid=,command= call carries no LC_ALL pin.

Not blocking, and fine to take or leave: the new test checks the env argument on mocked runCmd calls and expects every call to be pinned, which locks in the problem above, and no test drives judgeProcessIdentity or stopDaemonProcess with a legacy-locale record against a C-locale read (for example mar. 17 nov. 19:42:27 2026 against Tue Nov 17 19:42:27 2026, expecting unverified). simulator-boot.ts already defines C_LOCALE_ENV and a C-form lstart regex, so this PR adds a third spelling; exporting one from host-kit and importing it there would fix that. env: { LC_ALL: 'C' } replaces the whole environment. PATH and HOME do not matter, because ps is resolved by absolute path, but dropping TZ changes how lstart renders, and a record written under a custom TZ would still count as differing. psStartTimesLocaleMismatch only matches C form against non-C form, so two different localized renderings still compare as differing, and the comment should state that legacy-only scope.

Could the fix be smaller? Pin only the lstart reads, keep command and state reads on default options, keep the 'unknown' rule for legacy records, and put the C-form check beside processStartTimesDiffer so simulator-boot.ts can reuse it. Nothing else needs to change first. As an optional follow-up, isAgentDeviceDaemonProcess in daemon-process.ts could use the same comparison, so a legacy-locale daemon can still be stopped after the upgrade.

The Coverage check is failing, but its log ends mid-run in the react-native companion worker tests with no assertion or error line, so it does not point at this PR. Please re-run it. No conflicts. Before merge, narrow the pin to the lstart reads and add the unpinned-command regression. The issue's own reproduction (a French-locale daemon with LC_TIME=C daemon stop) has not been run on macOS yet, so a live run of that route showing daemon stop finding the daemon would close it.

A separate security cross-check of this head, run because process identity decides which process gets signalled, adds two more items before merge:

  • The pin drops the child environment and changes the identity clock (ps-start-time.ts:11). An explicit exec env replaces the inherited one, so ps loses TZ (and LANG) and renders lstart in the host zone. With the same explicit TZ on both sides of an upgrade, the new CLI reads a different start time for the same live PID, and stopDaemonProcess returns already-exited, which retires a live daemon's registration. Apply LC_ALL=C as a final override on top of the effective child environment instead of replacing it.
  • The legacy-locale guard misses real macOS formats (ps-start-time.ts:25). Under nb_NO.UTF-8, macOS ps prints the clock with dots, and other locales omit HH:mm:ss entirely. A record written that way does not match the C-form check, so the two renderings count as different lifetimes and a live daemon is again treated as exited. A mismatch should prove exit only when both values are in the same verified format. Otherwise treat the legacy record as unverified, never as gone. Please add a test with a real localized format that has no colon-separated clock, exercised at the daemon stop boundary.

Signal authorization still requires an exact identity match, so neither item lets the CLI signal the wrong process. Both make it give up on a live daemon, which is the orphaning bug #4656 reports, now coming from another direction.

thymikee added a commit to pcbeingused333/agent-device that referenced this pull request Nov 18, 2026
…tamps unverified

Addresses the blocking review on callstack#4682:

- The LC_ALL=C pin now applies only to ps reads whose output carries
  lstart (HOST_PROCESS_IDENTITY_PS_ARGS sync/async and
  readProcessField('lstart=')). The pid=,command= batch read and
  readProcessField('command='/'state=') keep the caller's locale, so
  command text reads with one encoding from every host-kit caller,
  matching the unpinned listHostProcesses scan. BSD/macOS ps escapes
  non-ASCII argv bytes under LC_ALL=C (/tmp/é-ü -> /tmp/M-CM-)-M-CM-<),
  which broke managed-process ownership for non-ASCII paths.
- The pin is a final override on top of the effective child environment
  (new effectiveChildEnv in exec.ts), so TZ and the rest of the child
  env survive: replacing the whole env dropped TZ and rendered lstart
  in the host zone under the pin (verified live: TZ=Pacific/Kiritimati
  record Thu Nov 19 09:29:21 2026 vs no-TZ read Wed Nov 18 20:29:21).
- processStartTimesDiffer proves a different lifetime only when both
  sides share one verified format (linux: token, C-form lstart, Windows
  invariant stamp). A legacy localized record — with or without a
  colon-separated clock, e.g. mer. 18 nov. 20:29:43 2026 or
  18 nov. 2026 — is unverified: never declared exited at daemon stop,
  never a signal authorization.

Regressions: pin scope + UTF-8 command reads + TZ retention in
host-process-liveness.test.ts, legacy verdicts in host-process.test.ts
and owner-identity*.test.ts, and at the daemon stop boundary in
daemon-process-takeover.test.ts (legacy record -> retained
identity-unverified with the daemon alive; non-ASCII argv reads as
UTF-8). Token-based reuse tests now use verified-format tokens.

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
@thymikee

thymikee commented Nov 18, 2026 •

Copy link
Copy Markdown
Member

Progress at 7ef7ebb. The locale override is now limited to start-time reads, keeps the effective child environment, and leaves Unicode command reads unpinned. On macOS, a real daemon started under French LC_TIME stopped gracefully from a C-locale client. The worker also verified graceful shutdown at a matching explicit TZ, and verified that legacy localized records return identity-unverified with the process and registration retained.

The cross-time-zone case remains open. The current C-form timestamp has no time-zone provenance. Coverage on this exact head also reports eager-closure growth from ps-start-time.ts; this needs a source fix before merge. The cross-zone run and exact-head checks are still pending.

@thymikee

Copy link
Copy Markdown
Member

This review covers f88ff09. The newer head 7ef7ebb changes how the locale pin reaches the spawn environment and will get its own delta review; the time-zone and evidence items below do not depend on it. At f88ff09, the earlier command pin and environment replacement findings are fixed, but birth identity and live validation still need work. The real dotted-clock fixture and full macOS run remain outstanding.

Could the process owner give birth tokens locale- and time-zone-independent, identifiable provenance? Starting a daemon in Pacific/Kiritimati and stopping it with TZ=UTC produces different C-shaped strings for the same PID, so the comparison can report a live daemon as exited. Conversely, a recycled PID held by a matching daemon can have the same local clock value and pass signal authorization. Both comparisons must treat old unqualified renderings as unknown unless the original lifetime is independently established; keep argv probes separate.

Please remove the redundant non-ASCII assertion and cover this through the environment-sensitive process reader and real-child stop test. It compares the same constructed string on both sides and passes even when the command read still has the reported regression.

The takeover test uses a stub executable and synthetic timestamps, so it does not establish graceful stop or live resource ownership. At the fixed head on macOS, start a real detached daemon under fr_FR.UTF-8 in a fresh state directory, capture its PID and token, and run daemon stop --state-dir

--json under LC_TIME=C; show stopped:true, mode:graceful, and PID exit. Repeat across different TZ values. With a separate pre-fix registration from an actual non-C locale, show typed identity-unverified refusal, a live PID, and retained metadata and lock. Run Apple simulator record start and stop through the daemon and show the recorder stops and releases its resource. If the snapshot change remains, show successive requests across provider locales retain the same live snapshot generation.

Not blocking: these can be taken or left: use a valid 21-digit CIM sample for stale Windows fixtures and remove unreachable platform branches; resolve scoped environment overrides once at spawn; bind an installed UTF-8 locale for the real-child Unicode test; use a recorded nb_NO.UTF-8 dotted-clock value; and keep the existing table case instead of the duplicate one-second reuse assertion.

Could the already loaded process capability own POSIX birth-token construction and its sync and async probe policy, with exec resolving scoped overrides once at spawn and the cancellable snapshot provider reusing that policy? A versioned token could identify comparable clocks while historical raw values remain unknown, preserving Linux /proc and Windows CIM tokens; choosing provenance and the legacy refusal rule at the process boundary comes first, while preserving Apple provider cancellation and routing, removing the extra eager import, and consolidating fixtures. No ADR amendment is needed for that ownership.

Android Smoke Tests passed, but Linux normally uses /proc and does not exercise macOS lstart. Repo Guards reports R86 on the added process.env capture, and Coverage reports ten eager-closure assertions with one extra module each. There are no known conflicts. Before merge, fix birth-token ownership and scope, clear R86 and the eager-closure checks at their source, and provide the exact-head macOS receipts.

@thymikee

Copy link
Copy Markdown
Member

At 7ef7ebb, the locale pin no longer applies to argv reads, but the process birth identity and SDK startup issues remain from the earlier review.

Could the host-kit observation owner emit one locale- and timezone-independent birth identity with provenance? A daemon registered under Pacific/Kiritimati and stopped under UTC gets different C-shaped lstart strings for the same PID, and the classifier treats the shared shape as a shared clock. The exit wait can report exit before signaling, so detached stop can report not-running and retire a live daemon's lock and metadata. Claim, lock, and managed-process observations also treat the difference as reuse. Old raw POSIX values need to remain unknown unless the lifetime is independently established. Identity classifier

Could every live signal authorization gate require a positive match between comparable birth identities, with command matching independent? A recycled PID can have the same raw local-second string under a different timezone, bypass the mismatch check, and pass the daemon entry-path check. That can authorize a signal to a different process lifetime. Legacy raw POSIX values need to remain unknown for equality too. Signal gate

Could scoped and unscoped launch and observation routes use the same clock, with the captured host bound at declared entrypoints for probes that need its environment? An unscoped lstart probe receives only LC_ALL=C, while Node ensureDaemon passes the captured TZ to the child. With a nondefault TZ, the parent can reject its live child during readiness. The scoped real-child test does not cover this route. Please verify a fresh Node ensureDaemon call with a nondefault TZ. Probe environment

Could the Unicode test remove the self-comparison and retain the environment-sensitive reader regression and real-child stop test? It supplies the same constructed argv to both sides without invoking ps, so it stays green with the earlier overbroad pin. Test

Could the valid and stale process birth fixtures be shared in test-kit? The same values appear in three test files, so each identity format change requires three updates. Fixture

Could you attach exact-head macOS receipts for the CLI and recording routes? The takeover test uses a stub process and synthetic timestamps, and the progress comment reports partial real macOS validation without the underlying transcript. At the fixed SHA, start a detached daemon in a fresh state directory under fr_FR.UTF-8, record its PID and birth identity, and run daemon stop --state-dir

--json under LC_TIME=C; show stopped:true, mode:graceful, and that PID exiting. Repeat with different explicit TZ values, and show a fresh Node ensureDaemon call under a nondefault TZ recognizing its child. For a genuine pre-fix non-C registration, show details.terminationReason=identity-unverified, the live PID, and retained metadata and lock. Through an Apple simulator daemon session, run record start and record stop and show the recorder exiting and its owned resource released. Include the SHA, commands, and outputs. Takeover test

Not blocking: the stale CIM fixtures could use valid distinct 21-digit samples, the Unicode child test could bind an installed UTF-8 locale, the stop regression could use a recorded nb_NO.UTF-8 dotted-clock value, and the redundant one-second reuse test could be removed; please take or leave these suggestions.

Could comparable POSIX identities live in the already loaded host-kit process capability alongside the Linux and Windows producers, with sync and async paths sharing one probe policy and the existing exec resolver owning spawn overrides? Could argv reads stay separate, qualified observations yield positive and negative lifetime judgments, and the extra eager import be collapsed? First, the canonical POSIX clock, provenance discriminator, and unknown legacy behavior for both matches and differences need definitions; saved-state structural equality should remain intact. Apple snapshot provider routing can stay separate, and no ADR amendment is needed.

The Coverage failure most likely comes from the added eager module, since its inbound static imports remain; please confirm from the job log. No conflicts are known. Before merge, please fix birth identity and the unscoped SDK route, repair the regressions and eager closure growth at their source, and provide passing exact-head checks and the macOS receipts above.

@thymikee

Copy link
Copy Markdown
Member

Round 2 at head ea5c816b274e7fb88e0b4fabb441df5c164f86b2 (single fast-forward 7ef7ebb7d4..ea5c816b27, no force-push).

Eager-closure / Coverage failure — fixed at the seam, no baseline changes. The ps-start-time module is deleted and its logic now lives in the already-loaded host-process.ts (984 lines, under the 1000 cap). pnpm exec vitest run --project unit-core scripts/__tests__/eager-closure-budgets.test.ts passes (909/909); the full receipt below shows vitest-related passed and zero eager-closure failures — the Coverage job's "adds 1 module" finding is gone.

Cross-TZ identity — closed with provenanced birth tokens. New POSIX reads canonicalize the pinned C-form lstart (parsed in the reader's zone) to posix:<epochMs>, a zone-independent token with explicit comparable provenance. processStartTimesDiffer proves a different lifetime only between two tokens of the same provenanced format (linux:, posix:, 21-digit Windows CIM); historical raw renderings — localized and raw C-form alike — are unqualified, so they yield identity-unverified: never already-exited, never a signal. isAgentDeviceDaemonProcess requires a provenanced expected token plus exact match plus command match. Linux /proc and Windows CIM routes, unpinned argv reads (UTF-8 command text preserved; only lstart=-bearing reads pin LC_ALL=C via envOverrides), and cancellation are unchanged. No shutdown-transport or signal-scope expansion.

Live macOS verification at exact head ea5c816b27 (disposable daemons, per-process env only, no host-global settings, owner-proven cleanup, no leftover daemons):

  • Cross-locale: daemon started under LC_ALL=fr_FR.UTF-8 recorded processStartTime: "posix:1795036084000"; LC_ALL=C LC_TIME=C agent-device daemon stop --json → stopped: true, mode: "graceful", pid 69017 gone, state dir cleaned.
  • Cross-TZ: daemon started under TZ=Pacific/Kiritimati recorded posix:1795036104000 while raw lstart rendered Thu Nov 19 11:08:24 2026 there vs Wed Nov 18 21:08:24 2026 under TZ=UTC; stop under TZ=UTC LC_ALL=C → stopped: true, mode: "graceful", pid 70294 gone.
  • Legacy record: raw C-form Wed Nov 18 22:08:42 2026 written into a live daemon's daemon.json (pid 71455); LC_ALL=C daemon stop --json → success: false, terminationReason: "identity-unverified", removedInfo: false, daemon.json + daemon.lock retained, pid still alive. Owner cleanup (SIGTERM) confirmed the pid gone and the state dir removed.

Checks receipt: pnpm check:affected --run --head ea5c816b274e7fb88e0b4fabb441df5c164f86b2 → receipt .tmp/validation/run-s0JGzn/receipt.json, exactCommit=true: format, lint, typecheck, layering, fallow, build, vitest-related all passed; unit failed only on 6 load-induced flakes while a concurrent validation ran on this host (release-publish ×4, snapshot-helper-exit-result ×1, macos-helper-package-contents ×1) — all 3 files pass in isolation (40/40), and none are touched by this PR; the pre-existing baseline failures (eager-closure-budgets ×65, daemon-process-takeover) are gone. pnpm format clean, pnpm build green, frozen lockfile install used throughout.

No device proof was run — no device is assigned to this task via T3. Not merged, not watched; readiness labels untouched.

@thymikee

Copy link
Copy Markdown
Member

Round 3 at head 0b301eefcaac49c597faab47667f9c2303fe2de1 (single fast-forward ea5c816b27..0b301eefca).

UTC clock at the lstart-only ownership seam. The lstart-bearing ps probes now override TZ=UTC alongside LC_ALL=C, applied as the final envOverrides word in resolveSpawnEnv — so a captured host/request TZ can no longer change the zone the ps child renders in, and the rest of the effective child env (and unpinned argv reads) is untouched. The known UTC output is parsed with Date.UTC, so the posix:<epochMs> token no longer depends on the JS reader's local zone and DST folds are out of scope. Scoped and unscoped routes share this one probe policy; Linux /proc and Windows CIM producers, cancellation, and the eager-closure shape (no new module) are unchanged. Legacy raw POSIX values remain unqualified → identity-unverified for both equality and difference; the signal gate still requires a provenanced token plus exact match plus command match. New regression test: a C-form read canonicalizes identically with the reader process under TZ=Pacific/Kiritimati vs baseline.

SDK ensureDaemon under nondefault TZ, differing parent TZ (fresh Node ensureDaemon from @agent-device/daemon-client, per-process env only, disposable state dirs, owner-proven cleanup):

  • TZ=Pacific/Kiritimati node --experimental-strip-types .tmp/ensure-r3.ts → {"readerTZ":"Pacific/Kiritimati","started":true,"pid":49006,"token":"posix:1795037630000"} — the parent recognized its own live child during readiness under a nondefault captured TZ.
  • TZ=UTC … same state dir → started:false, pid:49006, token:"posix:1795037630000"; TZ=America/New_York LC_ALL=fr_FR.UTF-8 … → started:false, same pid/token. Differing parent TZ attaches without replacing the daemon.
  • That SDK-started daemon was then stopped via TZ=Europe/Paris LC_ALL=C daemon stop --json → stopped:true, mode:"graceful", pid 49006 exited; state dir removed; no leftover daemons.

Exact-head CLI + legacy receipts at 0b301eefca (retained from this round's runs):

  • Cross-locale: daemon under LC_ALL=fr_FR.UTF-8 recorded posix:1795037566000 (pid 45677); raw lstart rendered mer. 18 nov. 22:32:46 2026 (fr_FR) / Wed Nov 18 21:32:46 2026 (C,UTC) / Thu Nov 19 11:32:46 2026 (Kiritimati) — one instant; LC_ALL=C LC_TIME=C daemon stop --json → stopped:true, mode:"graceful", pid exited.
  • Cross-TZ: daemon under TZ=Pacific/Kiritimati recorded posix:1795037598000 (pid 47318); stop under TZ=UTC LC_ALL=C → stopped:true, mode:"graceful", pid exited.
  • Legacy no-signal: raw C-form Wed Nov 18 21:33:21 2026 written into a live daemon's daemon.json (pid 47518, real token posix:1795037601000); LC_ALL=C daemon stop --json → success:false, terminationReason:"identity-unverified", removedInfo:false, daemon.json+daemon.lock retained, pid alive; owner SIGTERM cleanup confirmed pid gone, dir removed.

Checks at exact head: pnpm check:affected --run --head 0b301eefcaac49c597faab47667f9c2303fe2de1 → receipt .tmp/validation/run-smaLfc/receipt.json, exactCommit=true: format, lint, typecheck, layering, fallow, build, vitest-related passed; unit = 20592 passed / 2 failed, both in files this PR does not touch (scripts/__tests__/release-publish.test.ts, test/repo-guards/macos-helper-package-contents.test.ts) — release-publish also fails on the pristine 70f0b17 baseline, and both files pass in isolation at this head (8/8), so they are environmental, not regressions; eager-closure-budgets is green (909/909 direct, and inside the passing vitest-related/unit scope). Host-global state untouched: all runs used per-process env on disposable daemons only.

Still pending (reported separately, not done): the Apple-simulator recording route receipt (record start/record stop through a simulator daemon session, recorder exit + owned-resource release). No device is assigned to this task via T3, so no simulator was touched. Not merged, not watched; labels untouched.

@thymikee

Copy link
Copy Markdown
Member

Exact-head recording verification — PASS

  • Candidate: 0b301eefcaac49c597faab47667f9c2303fe2de1 (PR head), checked out and built in a clean worktree (pnpm install --frozen-lockfile, pnpm build, pnpm build:xcuitest:ios); CLI reports 0.21.40-dev, daemon codeOrigin: checkout. Working tree clean afterward — no source changes.
  • Device: iPhone 17 Pro Max simulator, iOS 27.0, UDID DBEA214F-555F-4DDA-B62B-E34285CE63DB, host local. device_open succeeded with no DEVICE_IN_USE or foreign claim; the Device panel open-list contained only this verification thread. Device left booted, as found.
  • Runner: the T3 device-bound CLI is pinned to published 0.21.36 and cannot execute the candidate, so per the device instructions the repo-owned recording test runner test/integration/recording-contact-sheet.test.ts (node --test, AGENT_DEVICE_RECORDING_E2E=1, AGENT_DEVICE_IOS_UDID=<udid>) was used; it executes this checkout's own src/bin.ts at the candidate SHA against the assigned simulator. Result: pass 1, fail 0 (~28 s).
  • Exercised on the assigned simulator: open com.apple.Preferences --relaunch → record start <out>.mp4 → click / scroll down / back → record stop (success, exit 0) → record contact-sheet. Export contact-sheet.mp4 written (3,540,793 bytes) with PNG contact sheet and gesture-telemetry sidecar (artifacts under gitignored test/artifacts/ios/record-contact-sheet/...).
  • Recorder exit / owned-resource release: session manifest screen-recording.resource.json shows lifecycle: "completed", phase: "completed", stopObservation.recorder: "confirmed", nativePathDisposition: "retired". The recorder (simctl io <udid> recordVideo, pid 66761) was recorded with birth token posix:1795039280000 — the new pinned-UTC lstart canonical form from this PR — and that pid is gone after record stop; no recordVideo process remains and no owned-processes.json is left in the session state dir. The test daemon itself registered processStartTime: "posix:1795039265000" through the same probe.
  • Cleanup: the test session ran close (session events end with close); the test daemon (pid 65558) was reaped at runner teardown and is no longer alive; the foreground app was restored to com.callstack.agentdevicelab through the device-bound CLI and that panel session was closed without --shutdown (the simulator was already booted and stays booted).

Limit: a manual record start/stop through the T3 device-bound CLI was not used as evidence, because that CLI runs published 0.21.36, not this head; all candidate proof above comes from the repo-owned runner executing the candidate source.

@thymikee

Copy link
Copy Markdown
Member

I reviewed 0b301ee against the earlier review (#4682 (comment)). The new design is closer, but the safety rule still has gaps and it changes the saved identity format for registrations that already exist. CI is still running with no failures reported yet. No conflicts. Before merge, the shared proof and format-change problems below need fixes, the tests need to exercise the real read path, and the exact-head macOS transcripts need to be attached.

When the host returns the same unparseable raw lstart as the saved record, host-process.ts:413 keeps the raw text and the shared stop judge returns ours on string equality. Recorder termination and owned-process reaping use the same check, and the daemon-only guard at daemon-process.ts:39 does not cover them. An unqualified clock rendering can then authorize a signal with no positive proof of the recorded lifetime. Please have host-kit expose one match/different/unknown comparison, and let only its match result open every PID-based signal gate that uses a birth marker. Keep raw equality only for structural fences, and keep direct child handles as independent evidence.

The stop test stub at host-process-stop-confirm.test.ts:236 emits an already encoded posix token in the ps row (:303-316). At 7ef7ebb the classifier already treated that token and a raw C value as incomparable, so the test can pass without this change. The mixed cases in host-process.test.ts:199 and owner-identity-liveness.test.ts:64 bypass the reader the same way, and so does the daemon case at daemon-metadata-loss.test.ts:98. These routes can look protected while the reader still emits raw lstart or the signal gate still accepts raw equality. Please make the ps stub emit C-form lstart and keep the saved fixture independent. Cover a differing raw C value that 7ef7ebb treats as reassignment, and separately an identical unqualified read and record that sends no signal.

The latest live results are from ea5c816, but this head changes the child clock and parser (host-process.ts:239). Please attach commands, outputs and the SHA for a real detached CLI daemon in a fresh state directory across French/C locales and differing TZ values, showing the token, a graceful stop and the PID exit. Add a fresh unscoped Node ensureDaemon with nondefault TZ that recognizes its child. For a genuine pre-fix non-C registration, show identity-unverified with a live PID and retained lock and metadata. For an Apple simulator daemon session, show record start/stop, recorder PID exit and release of the recording resource.

Under the same locale and settings, a healthy pre-fix macOS Metro companion has a raw saved startTime. The new probe returns posix, so reuse fails at client-companion-tunnel.ts:246, and the ensure path at :489 tries a stop that keeps the live process as unverified at :318. After upgrade, a working tunnel becomes unusable, and a repeated ensure and an explicit stop both fail while the worker stays registered. Please give the companion lifecycle a safe upgrade path, such as owner-side shutdown before the identity change or re-verification through an independent worker-owned fence. Keep the record and fail closed when no owner can be established.

A live retained runner from before this change has a raw runnerStartTime. Once its daemon exits and the lease can be adopted, runner-lease.ts:810 compares it with a new posix read, and runner-adoption.ts:289 reports runner_pid_recycled before the token-authenticated probe runs. Cleanup at runner-lease.ts:713-734 also refuses the PID as unverified, then releases the lease after its other cleanup attempt. A healthy iOS runner that the old build could hand off is now called recycled, so the next daemon cannot adopt it and may rebuild while the old process still runs. Please separate unknown birth evidence from proven PID reuse. Use independent endpoint-to-process proof for handoff, or drain the retained runner with its owner before changing the marker format, and keep unresolved cleanup state.

A live simulator recorder with an old raw start time and matching argv gets unverified from the judge. Both host fields are readable, so platform-runtime-screen-recording-process-host.ts:139 treats that as not ours, and packages/platform-apple/src/recording/recovery.ts:165-169 reports ownership-fence-lost with no proven mismatch. Recovering a recording made before the format change can be refused while the same simctl process is still alive, and the process also loses the direct child-handle route. Please pass unknown birth evidence separately from a proven ownership mismatch into the simulator stop and recovery result. Keep markers and artifacts on uncertainty, use an independently owned handle when one exists, and otherwise require owner-side settlement.

The rewritten startToken body and LATER_LIFETIME in agent-browser-lifecycle.test.ts:16 match tests/agent-browser-process-record.test.ts:31-35. The staleStartTimeLike helpers at daemon-process-takeover.test.ts:69 and cli-device-status.test.ts:22 also encode the same per-format choices. The format change already needed the same fixture edit in several places, and test doubles can drift on which lifetime evidence is valid. Please use one deterministic lifetime fixture and one stale-of helper at the owning shared test seam, with real C-form rows at mocked ps boundaries and canonical tokens where observations are consumed.

Existing help tells users to end an older daemon with daemon stop (cli-help.ts:419, website/docs/docs/commands.md:92). For a live older macOS detached registration with raw lstart, the upgraded CLI now returns identity-unverified even with the same locale and TZ, as the new rule requires. Operators can repeat the suggested command and keep hitting the refusal while the old daemon holds resources. Please update the help and docs to describe the refusal and the supported owner-side or pre-upgrade stop procedure.

The head writes a posix token into both existing registration identity fields (daemon-registration-owner.ts:118, and :88). A pre-fix hardened client from the merge base still reads that same lock structure. Its comparator at base host-process.ts:243-250 treats posix versus its own raw lstart as two unequal values, its manual stop has no version check before exit polling, and its lock reclaimer uses the same PID reuse proof. ADR 0030 covers the legacy-versus-hardened lock boundary, and this change keeps the hardened schema while changing the published value. Running the previous CLI against a newly started macOS daemon in the same state directory can report not-running and retire the live registration and lock, even with identical locale and TZ. That is the reported orphaning in the opposite mixed-version direction. Please keep the old-readable identity where old hardened clients make reclaim decisions and store the canonical comparison evidence separately, or add a cutover that released clients actually refuse before they read the lifetime. Add an old-client/new-daemon case.

Not blocking: daemon-registration-status.test.ts:123 uses a 20-digit placeholder for a live PID on the Windows branch, but the host comparison needs 21 digits, so it is incomparable and :127 would not see stopped; a distinct valid 21-digit CIM value from the shared stale-of fixture would fix it. The PR body still describes a separate ps-start-time module and a C-form-versus-localized comparison, while the head removes the module, pins locale and UTC, and treats every raw POSIX rendering as unqualified. These can be taken or left.

Simplicity question: could both the positive and negative live comparisons sit behind one host-kit three-way result, with the existing stop judge staying the consumer for host-kit targets? Daemon, browser, runner and companion lifetime checks would consume that result and keep their own command and resource ownership logic. That would drop the public provenance boolean and the separate daemon guard. The rollout would be defined at the registration and lock owner before a new encoding is published to old readers. The comparison contract and the saved-format cutover would come first, with unparseable observations as unknown and structural identity checks on saved records left intact. The size is fine; my concern is the new provenance seam and its inconsistent consumers.

The 28 changed files include no help or user doc changes, which is why the help finding above is raised against existing text. The live results and local check report are tied to ea5c816, and no exact-head logs were supplied. The Apple snapshot read is unchanged here, so this change does not show snapshot stability across provider locales. The POSIX lstart source still has one-second precision, so PID reuse at that granularity is not measured.

@thymikee

Copy link
Copy Markdown
Member

Round 4 at head 25594b972e04f8ae3c5a399acdcaf646924350f0 (fast-forward on 0b301eefca), answering the review at #4682 (comment) item by item.

1. One three-way comparison, raw equality never opens a signal gate. compareBirthTokens(left, right) in packages/host-kit/src/internal/host-process.ts returns match (same provenanced format, equal values — the only result that authorizes a PID-based signal), different (same provenanced format, different values — proven pid reuse), or unknown (everything else, including two equal raw renderings). judgeProcessIdentity now returns ours only on a provenanced match; daemon-process.ts, stopDaemonProcess, runner adoption/lease verification, and the companion reuse check all consume this one result. Direct child handles remain independent evidence (the recorder's own spawned pid can still be ended via child.kill when the host cannot answer).

2. Real read path in tests. The ps stubs at the producer seam now emit real C-form lstart rows (host-process-stop-confirm.test.ts and the marker mocks), with records holding canonical posix: tokens; mixed cases in host-process.test.ts cover a differing C value (proven reuse), an identical unqualified read+record (unknown, no signal), and a legacy raw record against a canonical read (unverified). One shared lifetime fixture (packages/test-kit/src/process-lifetime.fixtures.ts: LIFETIME_TOKEN, STALE_LIFETIME_TOKEN, LEGACY_RAW_START_TIME, staleBirthTokenLike) backs the daemon, CLI, browser and runner tests; host-process-mock.ts pins to it.

3. Exact-head macOS lifecycle evidence (head 25594b972e, disposable state dirs, per-process env only, owner-proven cleanup, no host-global changes):

  • Cross-locale CLI: daemon started under LC_ALL=fr_FR.UTF-8 published processStartTime: "jeu. 19 nov. 13:57:43 2026" (legacy raw) beside processStartTimeToken: "posix:1795093063000"; the same pid renders jeu. 19 nov. … / Thu Nov 19 12:57:43 2026 / Fri Nov 20 02:57:43 2026 under fr_FR / C+UTC / Kiritimati; LC_ALL=C LC_TIME=C daemon stop --json → {"success":true,"stopped":true,"mode":"graceful"}, pid exited.
  • Cross-TZ CLI: daemon under TZ=Pacific/Kiritimati, stop under TZ=UTC LC_ALL=C → stopped:true, graceful, pid exited.
  • SDK ensureDaemon (unscoped node, --experimental-strip-types): under TZ=Pacific/Kiritimati → started:true, pid 71063; attaching from TZ=UTC and TZ=America/New_York → started:false, same pid and same posix:1795093123000 token.
  • Legacy pre-fix record (raw processStartTime only, token field removed, live pid): daemon stop → COMMAND_FAILED, terminationReason: "identity-unverified", removedInfo:false, lock and metadata retained, pid still alive; owner-side SIGTERM cleanup then exited it.
  • No leftover daemon processes after any run (verified with ps).

4. Companion upgrade path. shouldReuseCompanion now uses compareBirthTokens: different refuses reuse, match/unknown fall through to the existing command + bridgeScope + tokenHash fence, so a healthy pre-fix raw record keeps the tunnel reusable instead of being declared recycled, and an unproven record still fails closed keeping the registration.

5. Runner handoff. compareLeaseRunnerPidIdentity separates unknown from proven reuse: adoption refuses only on different (recycled) and on unknown (runner_pid_unverified) — never reports runner_pid_recycled for a raw record; cleanup signals the pid only on match and otherwise proceeds with the command-pattern sweep and keeps unresolved state in diagnostics (ios_runner_lease_unverified_pid_skipped).

6. Recorder/recovery. readOwnershipEvidence reports unprovable separately from not-ours (proven different birth, or a provenanced birth match beside a contradicted command claim); packages/platform-apple/src/recording/recovery.ts maps unprovable to cleanup-pending / manual-recovery-required and keeps markers and artifacts instead of reporting a fence loss.

7. Help/docs. cli-help.ts (daemon-stop paragraph) and website/docs/docs/commands.md now describe the identity-unverified refusal and the supported owner-side / pre-upgrade stop procedure.

8. Persisted-format compatibility (old hardened client vs new daemon). The registration and lock owners now dual-write: the legacy raw processStartTime/startTime field keeps exactly the rendering a released build wrote (old readers compare it as before), and the canonical token rides beside it as processStartTimeToken/birthToken, which only this build's comparisons consume. In-memory reads (parseDaemonInfo, readRegisteredDaemonIdentity, lock inspection) fold the token for comparison, so new-vs-new works on provenanced tokens. Mixed-version tests: new-build record keeps raw field + token (old client sees its expected format; new reader matches via token; stale token → superseded), and an old raw-only record is unproven/never superseded to a new reader. The daemon quiesce fence accepts its canonical token or its own legacy raw rendering, so a released client can still ask a new daemon to leave.

Checks at exact head 25594b972e (pnpm check:affected --run --head 25594b972e…, receipt .tmp/validation/run-9I07nK/receipt.json, exactCommit=true): format, lint, typecheck, layering, fallow, build passed. The vitest-related and unit phases hit only Test timed out failures while this shared host ran at load average 300–850 from concurrent worktrees; every one of those files is untouched by this diff and passes when run directly at this head (e.g. scripts/__tests__/release-publish.test.ts 5/5 isolated, test/integration/provider-scenarios/android-find.test.ts and test/output-economy/owner-files-no-leak.test.ts pass alone; full unit-core + apple-runner + fuzz-worker sweep: 19093 + 990 passed with only the load-sensitive release-publish timing out in the parallel run). The eager-closure gate (scripts/__tests__/eager-closure-budgets.test.ts) passes against origin/main as part of the sweep. Recording-route evidence at 0b301eefca (comment 6992988078) remains valid; no simulator was touched in this round (no device assigned).

@thymikee

Copy link
Copy Markdown
Member

The Integration Tests failure was caused by the dual-written daemon registration: three tests and their cleanup helper passed the legacy raw processStartTime to the signal gate instead of processStartTimeToken, so the gate correctly returned identity-unverified. Commit 40edb706bd uses the published token and keeps missing or unqualified identity fail-closed.

The three failing files reproduced the same 3 failures at 25594b972e; all 5 tests passed at merge base 972b5a5a23 and after the fix. The cleanup-helper suite passed 9/9, and the full local Node integration lane passed. Recent main Integration Tests jobs also passed: run 44534103223 and run 44533954652. CI on the new head is pending.

@thymikee

Copy link
Copy Markdown
Member

Thanks for the update. At 40edb70, the Integration Tests failure from the earlier review is fixed, and the CLI, SDK and legacy-record asks from the earlier review (#4682 (comment)) are met. Four problems remain, and one new one shows up in recovery.

The new unprovable value in ManagedProcessOwnership is not handled by every consumer. inspectApplePerfCaptureDescriptor checks owned-alive and ownership-lost, then falls through to { status: 'missing' } at https://github.com/callstack/agent-device/blob/40edb70/src/platform-runtime-perf-capture-host.ts#L237. The host audio probe reattach (packages/capture-kit/src/audio-probe-recovery.ts:35-45) does the same. After a daemon restart, a live xctrace capture or audio probe whose identity cannot be proven is then recorded as completed/already-missing, and nothing is left for cleanup or device admission. At base the same state was retained as ownership-fence-lost. The rule: every consumer treats unprovable as live but unresolved, never as missing. Making each consumer an exhaustive switch over the union (perf, audio, app-log, screen recording) lets the compiler list the sites. Please map it to transport-not-reattachable on reattach and to manual-recovery-required on cleanup. Please also add one test that drives inspectManagedProcess to unprovable through the perf and audio reattach and asserts the record is retained.

readProcessStartTimeRaw handles only Windows specially (https://github.com/callstack/agent-device/blob/40edb70/packages/host-kit/src/internal/host-process.ts#L314). On Linux it runs ps -o lstart=, while the merge-base reader returned the /proc token linux:<boot>:<ticks>. The registration, lock owner and guard write this value into the legacy processStartTime/startTime fields. A released Linux client compares its own linux: read with that field by exact equality, so daemon stop and the force-retire path return identity-unverified against a daemon started by this build. The legacy field also becomes a locale- and TZ-dependent string on Linux, which is the bug this PR fixes on macOS. The rule: the legacy field equals what the merge-base readProcessStartTime returned on that host (the /proc token on Linux, CIM on Windows, unpinned ps only on other POSIX hosts). One host-kit function that produces both values from a single read would keep them in step.

The old-client/new-daemon test at https://github.com/callstack/agent-device/blob/40edb70/packages/daemon-contracts/src/daemon-registration.test.ts#L94 writes daemon.json with the test-kit publishDaemonRegistration, which re-implements the dual write. The assertions at lines 111-112 therefore check the fixture's own encoding. No test drives the production writers (tryAcquireDaemonRegistration, publishClaim, createReclaimMutex) or the quiesce fence's rawStartTime acceptance. Reverting the production publisher to write the token into processStartTime would keep every test green. Please assert the daemon.json and lock owner.json that the production acquire paths produce with a mocked reader: legacy field equals the released reader's value, token field equals the canonical token. Add a quiesce-fence case where a request carrying the record's legacy value is admitted. Please also drop the dual write from the helper or have it call the production encoder.

The help paragraph at https://github.com/callstack/agent-device/blob/40edb70/src/commands/schema/cli-help.ts#L421 and website/docs/docs/commands.md:93 say that any older registration stores a raw lstart and that stop refuses it. Older Linux builds registered /proc tokens and older Windows builds registered CIM tokens. compareBirthTokens matches both, and stop handles them normally. An agent on those hosts that follows this text will treat a stoppable daemon as stuck and fall back to manual SIGTERM or deleting the state dir. Please scope both sentences to macOS/BSD registrations written before this release, and say that Linux and Windows registrations from older builds still stop normally.

Not blocking, take or leave: the delta shortens about twenty unrelated comments in host-process.ts (the NixOS ps fallback, the Windows CIM row rule, the EPERM and zombie stop notes) to stay under the 1000-line cap, and moving the birth-token codec into its own host-kit module would make that unnecessary (import it lazily or count it in the closure budget); and staleBirthTokenLike in packages/test-kit/src/process-lifetime.fixtures.ts:22 returns 20 digits for a Windows token, while psStartTimeFormat needs 21, so it compares unknown instead of different.

Could the birthToken/rawStartTime pair on OwnerIdentity become one host-kit persisted-identity codec? readPersistedOwner(record) would return { pid, startTime } with startTime always the comparable value. writePersistedOwner(identity) would emit { startTime: releasedReaderValue, birthToken: canonical } from one host read. Registration, lock owner, guard holder and the quiesce fence would all call that pair. That removes birthTokenOf, the startTime meaning split and the rawStartTime threading, and it fixes the Linux field by construction. It needs only a note on the dual-field schema and on when the legacy field can be dropped, under ADR 0030's legacy/hardened lock boundary.

CI is green: 12 checks, none failing, at 40edb70. No conflicts. The Linux refusal above follows from daemon-process.ts at 972b5a5 and was not reproduced against a running daemon. The Apple simulator recording evidence is from 0b301ee, before this delta changed judgeProcessIdentity and the recorder ownership mapping. Before merge, please fix the unprovable handling, then the Linux legacy field with production-writer tests, then the help text. After that, run record start and stop through a daemon session on an iOS simulator at the final head. The output should show the recorder PID exiting, screen-recording.resource.json with lifecycle completed and stopObservation.recorder confirmed, and no owned-processes.json left. Please also attach the output of the new publisher test showing the Linux legacy field equals the linux: token.

@thymikee

Copy link
Copy Markdown
Member

Review update at 86fba4d2c9ac0c293f3f675549b8ebd5b122dfdd:

  1. Perf, audio, app-log and Apple recording recovery now switch over ownership explicitly. unprovable maps to transport-not-reattachable on reattach and manual-recovery-required on cleanup. Tests drive the real process inspector with a live, unqualified identity through perf and audio durable recovery and verify the records remain open.
  2. Host-kit now owns the persisted-owner encoder and decoder; in-memory owners carry the comparable start time. Registration, lock/guard and quiesce use the codec. The Linux and Windows legacy values use the canonical /proc and CIM values; POSIX uses the released unpinned rendering. ADR 0030 records the dual fields and removal boundary.
  3. The production publisher tests cover daemon registration, lock and guard records, and a quiesce request carrying the legacy value. The test helper uses the production encoder; the Windows stale fixture has 21 digits. Relevant output:
    ✓ lock and guard publish the Linux linux:boot:123 legacy field
    ✓ lock and guard publish the POSIX legacy field
    ✓ lock and guard publish the Windows legacy field
    ✓ registration publisher writes the Linux linux:boot:123 legacy field
    ✓ registration publisher writes the Windows legacy field
    ✓ a quiesce fence carrying the published legacy value is admitted
    Test Files 3 passed; Tests 14 passed
    
  4. Help and docs scope the older raw-registration refusal to macOS/BSD and state that older Linux/Windows registrations stop normally.
  5. Live iOS evidence is blocked. T3 device_open returned its bundled agent-device 0.21.36 client. Against an isolated daemon built from this head, the returned command refused open with Remote daemon RPC protocol is incompatible: the client supports protocol 2 and this daemon uses protocol 3. It advised upgrading client or host. T3 exposes no task-scoped client selection; changing its installed runtime would affect host-global tooling, and downgrading the daemon would not test this head. No recording was started. The isolated daemon was stopped gracefully and the device panel closed. A compatible T3 client is needed to complete this evidence.

The focused recovery, writer, lock and registration tests, typecheck, and eager-closure tests passed. The initial affected gate found an R11 test import violation; the tests were moved into their owning packages and the full layering check passed. Hosted checks on this head are still running.

@thymikee

Copy link
Copy Markdown
Member

Live iOS recording at c0d2a160aeb22450d092b74268f1a9687999122c

Built from this head (pnpm install --frozen-lockfile && pnpm build) and driven with its own CLI (node dist/src/internal/bin.js), so client and daemon match this head. The run used an isolated temp --state-dir (shown as <state>) and per-process env only. Device: iPhone 17e simulator, iOS 27.0 (F25C7515-D67E-4838-BEAC-0AD08DB056EC), app com.apple.Preferences. The sequence was open → record start → about 3 s → record stop → close → daemon stop.

== record start
{"success":true}
== owned-processes.json during recording
{"version":1,"processes":[{"pid":36753,"startTime":"posix:1795113044000",
  "command":".../simctl io F25C7515-... recordVideo <state>/rec.native.mp4","purpose":"simctl-screen-recording"}]}
== recorder pid: 36753 (simctl, running)
== record stop
{"success":true, "recorder":"confirmed", "nativePathDisposition":"retired", "durationMs":3859}
== recorder pid after stop: 36753 exited
== screen-recording.resource.json
lifecycle: completed
metadata.phase: completed
metadata.stopObservation.recorder: confirmed
metadata.completion.stopObservation.recorder: confirmed
metadata.stopFinalization.nativePathDisposition: retired
== owned-processes.json after stop: none
== exported rec.mp4: 41096 bytes
== close: {"success":true}
== daemon stop: {"success":true,"stopped":true,"mode":"graceful"}

The owned-process record carries the canonical posix: birth token, the recorder exits on stop, the durable record completes with the recorder confirmed, and nothing is left owing cleanup. The daemon itself stops gracefully under the new identity comparison.

@thymikee

Copy link
Copy Markdown
Member

Thanks for the update. The code at c0d2a16 fixes the defect from the earlier review: the legacy field is now the ps rendering only where released clients need it. The new tests do not guard that fix, so they need changes before merge. CI is green with 13 checks and none failing, and there are no conflicts.

The Linux row in process-lock-persisted.test.ts sets the readProcessStartTimeRaw mock to the token itself (linux:boot:123), and daemon-registration-persisted.test.ts mocks readCurrentOwnerIdentity, which sits above needsLegacyPsRead and the cached persisted pair. Both tests would also pass on the earlier code, where the legacy field stored the raw read. Deleting needsLegacyPsRead (owner-identity.ts:79-82) and always taking the ps rendering also leaves every test green. If that regresses, a released Linux client cannot stop or force-retire a daemon started by this build, and no test notices. The rule: in each persisted-identity test, the legacy reader returns a value that differs from the token, so the expected field shows which path ran. Set the legacy mock to a ps rendering such as Tue Nov 17 19:42:27 2026 in the Linux and Windows rows of the lock test, and keep expecting the token. In the registration test, mock readProcessStartTime/readProcessStartTimeRaw in host-process the same way (or reuse the lock test's module mock) instead of readCurrentOwnerIdentity, and add the POSIX row.

The quiesce-fence test in daemon-idle-reap-lifecycle.test.ts builds its identity from the real readCurrentOwnerIdentity(). The unit suite runs in the coverage job on Ubuntu, where the token is linux:..., so writePersistedOwner(identity).startTime === identity.startTime and the fence matches the first clause at daemon-idle-reap.ts:253. Removing the legacy acceptance clause at line 254 keeps the test green in CI, and it only goes red on a macOS machine. If that clause regresses, a released macOS client's lifecycle request gets instance-mismatch instead of a drain. The rule: the test must not depend on the host. Mock host-process readProcessStartTime to a posix: token and readProcessStartTimeRaw to a distinct raw rendering, as the lock test does. Then assert that a fence carrying the raw value is admitted and that a different raw value is refused.

Not blocking, take or leave: writePersistedOwner is not a pure codec, since it returns the released rendering only when the module-level currentPersistedOwner matches, and it writes startTime: null for any other posix: identity; every production writer passes this process's cached identity so that branch does not fire today, but having readCurrentOwnerIdentity/rememberOwnerIdentity expose the persisted pair from the one host read, and passing it to the writers, would let the encoder take its legacy value as input instead of from a module cache.

Once the persisted-identity tests catch their regressions (the legacy mocks differ from the token in the Linux/Windows lock and registration rows, and the quiesce-fence test is host-independent), this is ready to merge.

@pcbeingused333

Copy link
Copy Markdown
Contributor Author

Thanks, @thymikee. Pushed 437e441 with the test changes:

  • process-lock-persisted.test.ts: the raw ps mock is now a fixed rendering that differs from the token in every row, so the Linux and Windows rows only pass if the lock and guard keep the token, and the POSIX row only passes if they take the ps rendering.
  • daemon-registration-persisted.test.ts: mocks readProcessStartTime/readProcessStartTimeRaw with distinct values, re-imports per row, and adds the POSIX row.
  • daemon-idle-reap-lifecycle.test.ts: pins the token to a posix: value and the raw rendering to a distinct string, so the quiesce-fence test no longer depends on the host; it now asserts the published field is the raw rendering, and a new case checks that a fence with a different raw start time is refused.

@thymikee

Copy link
Copy Markdown
Member

The code in 437e441 is ready: the ps lstart locale fix and its regression coverage look right, and the findings from the earlier review (#4682 (comment)) are fixed. Repo Guards & Compatibility fails at this commit in scripts/layering/package-boundaries.test.ts:451 ("the real tree parses, declares, and passes R11"), and the cause is the new vi.mock paths in daemon-registration-persisted.test.ts:6-7 and daemon-idle-reap-lifecycle.test.ts:20-21, which reach into host-kit/src/internal/host-process.ts by relative path. That check was green at c0d2a16, so this change caused the failure. Before merge, a consumer-package test should reach host-kit only through its package specifier: mock @agent-device/host-kit/process in those two tests (or move the registration row into host-kit), and keep both regressions red when the field mapping or the legacy clause at daemon-idle-reap.ts:254 is removed. Not blocking, and you can take or leave these: the legacy alias (const legacy = expected;) in process-lock-persisted.test.ts:23 could go by using expected in the two assertions.

@thymikee thymikee added the ready-for-human Valid work that needs human implementation, judgment, or maintainer merge label Nov 20, 2026
@thymikee

Copy link
Copy Markdown
Member

Still ready at aafbcf1. The two tests now mock @agent-device/host-kit/process instead of reaching into host-kit/src/internal, so the R11 package-boundary check passes, and the regressions still pin the persisted start-time mapping and the legacy clause in daemon-idle-reap. The legacy alias is gone too. All checks pass, and the label stays.

@thymikee thymikee removed the ready-for-human Valid work that needs human implementation, judgment, or maintainer merge label Nov 20, 2026
@thymikee

Copy link
Copy Markdown
Member

Thanks for this fix and for the thorough live evidence, @pcbeingused333. I pushed one commit on top of your branch (14bcb79cb0, plus a merge of main) that keeps your fix and removes the compatibility layer around it.

What stays: ps -o lstart is read with LC_ALL=C TZ=UTC and stored as a posix:<epochMs> token, and a raw start time from an older release is unverified, so nothing is signaled and no live daemon's registration is discarded.

What changed:

  • A persisted owner has one startTime field again, which now holds the token. The second birthToken / processStartTimeToken field, the raw lstart readers that existed to write it, and the helpers each record writer adopted are gone.
  • Runner leases, capture recovery, process locks, daemon registration, the companion tunnel and the platform runtime hosts are back to their state on main. Production changes are now host-process.ts, exec.ts and the CLI help line.
  • A ps start time that this build cannot parse is now unknown evidence instead of a raw token, so a raw string can never match a live read.

Why: the project adds compatibility paths only when a maintainer asks for them, and we decided not to support an older build and a newer build sharing one state directory. The PR description states that trade-off. The cross-locale, cross-zone and legacy-record cases are still covered by tests, and I re-ran the cross-locale stop and the legacy-record refusal on macOS at the new head.

@thymikee

Copy link
Copy Markdown
Member

Thanks for the fix, and for the careful first version. At c9049e8 the simplified change reads correctly: the Linux-only Coverage failure from 14bcb79 is fixed, and the 13 checks on this commit show no failures. Two things remain before this is marked ready: an independent pass over every consumer of the start-time token, which is running now, and the maintainer's sign-off on the mixed-version trade-off in note 1.

The live cross-locale and legacy-record runs at 14bcb79 still apply, because the production code is identical here.

Not blocking, and you can take or leave these: (1) the accepted trade-off in cli-help.ts:423 is scoped to one state directory, but runner leases and device claims are host-global, so an older build on the same host may read a newer daemon's posix: start time as a reused process; one sentence saying not to run older and newer builds on one host would cover it, and the same sentence could say that records from an older release on macOS/BSD (daemon, companion tunnel, runner leases) stay unverified until their owner stops the process, since an old companion tunnel now fails on every retry; (2) help and docs (commands.md:96) still say "canonical birth token", a name from the field that 14bcb79 removed, so "start-time token" would match the code; (3) in host-process.ts:389 an unparseable lstart drops the whole row, including the state column, so keeping the row with a null start time would preserve zombie proof if it ever matters.

pcbeingused333 and others added 6 commits November 20, 2026 14:33
ps -o lstart prints weekday and month names in the caller's locale, so a
daemon and a client under different LC_TIME compared one start time as
different lifetimes and daemon stop orphaned a live daemon on macOS.
Run the ps identity reads with LC_ALL=C and treat a C-form start time
against a localized one as unknown instead of reassigned.

Fixes callstack#4656
…tamps unverified

Addresses the blocking review on callstack#4682:

- The LC_ALL=C pin now applies only to ps reads whose output carries
  lstart (HOST_PROCESS_IDENTITY_PS_ARGS sync/async and
  readProcessField('lstart=')). The pid=,command= batch read and
  readProcessField('command='/'state=') keep the caller's locale, so
  command text reads with one encoding from every host-kit caller,
  matching the unpinned listHostProcesses scan. BSD/macOS ps escapes
  non-ASCII argv bytes under LC_ALL=C (/tmp/é-ü -> /tmp/M-CM-)-M-CM-<),
  which broke managed-process ownership for non-ASCII paths.
- The pin is a final override on top of the effective child environment
  (new effectiveChildEnv in exec.ts), so TZ and the rest of the child
  env survive: replacing the whole env dropped TZ and rendered lstart
  in the host zone under the pin (verified live: TZ=Pacific/Kiritimati
  record Thu Nov 19 09:29:21 2026 vs no-TZ read Wed Nov 18 20:29:21).
- processStartTimesDiffer proves a different lifetime only when both
  sides share one verified format (linux: token, C-form lstart, Windows
  invariant stamp). A legacy localized record — with or without a
  colon-separated clock, e.g. mer. 18 nov. 20:29:43 2026 or
  18 nov. 2026 — is unverified: never declared exited at daemon stop,
  never a signal authorization.

Regressions: pin scope + UTF-8 command reads + TZ retention in
host-process-liveness.test.ts, legacy verdicts in host-process.test.ts
and owner-identity*.test.ts, and at the daemon stop boundary in
daemon-process-takeover.test.ts (legacy record -> retained
identity-unverified with the daemon alive; non-ASCII argv reads as
UTF-8). Token-based reuse tests now use verified-format tokens.

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
…heck the lstart helpers

Move the start-time format classification and processStartTimesDiffer into
ps-start-time.ts (re-exported through the process barrel) so host-process.ts
stays under 1000 lines, and use non-null match groups in the takeover test's
locale helpers. Also replaces hex escapes with Unicode escapes in the
liveness test.

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
…wn-env word

The layering guard (R86 process-globals) forbids reading process.env outside
declared process entries, so the pin cannot be materialized from
process.env in exec.ts. ExecOptions gains envOverrides, which
resolveSpawnEnv applies as the final word over the bound host scope's
environment plus the request env: LC_ALL=C is pinned while TZ and the
rest of the effective child environment survive. Outside a scope an
explicit env still takes the overrides on top, and with neither the
child inherits natively.

The TZ regression moves to exec.test.ts, which spawns a real child:
withCommandHost(host TZ=Pacific/Kiritimati) + envOverrides LC_ALL=C
observes 'Pacific/Kiritimati|C', and the override also wins over a
request-env LC_ALL.

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
…ost-process module

Move the ps-start-time logic into the already-loaded host-process.ts so the
eager-closure budget is unchanged, and give newly produced POSIX birth tokens
explicit comparable provenance: a pinned C-form lstart is parsed in the
reader's zone and recorded as posix:<epochMs>, so identity survives a
cross-TZ stop. Historical raw renderings stay unqualified: they yield
unverified identity and never prove exit or authorize a signal. Linux /proc
and Windows CIM routes, unpinned argv reads, and cancellation are unchanged.

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
… output as UTC

The probe now overrides TZ=UTC alongside LC_ALL=C (as the final envOverrides
word, so a captured host or request TZ cannot change the zone ps renders in),
and the known UTC output is parsed with Date.UTC. The posix:<epochMs> birth
token no longer depends on the JS reader's local zone or on DST folds, so a
daemon registered under one TZ is recognized under any other. Linux /proc,
Windows CIM, unpinned argv reads, cancellation, and the eager-closure shape
are unchanged; legacy raw renderings stay unqualified and unverified.

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
The token classifier accepted any string that starts with `posix:`. A stored
`posix:corrupt` beside a valid live token then counted as a different
lifetime: `waitForDaemonExit` declared a live daemon exited, and a held lock
or reclaim guard marked its live holder as reused.

A stored value is now a POSIX token only in the form a read writes: `posix:`
followed by a whole-second epoch in safe-integer milliseconds. Any other value
is unverified like a raw `ps` string from an older release: never a match,
never a mismatch. The reader returns only tokens that pass the same rule.

Also say "start-time token" in the CLI help and the commands page.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@thymikee
thymikee force-pushed the fix/ps-lstart-locale branch from 21985d3 to b69ae8b Compare November 20, 2026 13:36
@thymikee

Copy link
Copy Markdown
Member

At b69ae8b the malformed-token gap is closed: a stored value counts as a start-time token only as posix: followed by a whole-second epoch, and anything else is unverified, like a raw string from an older release. Tests pin that at daemon stop, record retirement, lock acquisition, reclaim guards and owner liveness, and an independent pass confirmed they fail when the rule is reverted to a prefix check. The only change since 21985d3 is a merge of main. All that remains is the maintainer's sign-off on the mixed-version trade-off stated in the PR body.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@thymikee

Copy link
Copy Markdown
Member

Follow-up on the three optional notes from the review at c9049e8, in 786f878:

  1. Same host: the help line and commands.md now say not to run an older and a newer build on one host, because runner leases and device claims are host-global, and that records an older macOS or BSD build wrote (daemon, companion tunnel, runner leases) stay unverified until their owner stops the process.
  2. "start-time token" wording: already in place at 21985d3.
  3. Keep the row when lstart does not parse: not done. It makes startTime nullable in HostProcessIdentityObservation, which every caller of the observation reads, to keep zombie proof for a ps rendering that this build cannot parse. With LC_ALL=C TZ=UTC that rendering is not expected. A dropped row is unknown evidence, so nothing is signaled.

The remaining item is the maintainer's sign-off on the mixed-version trade-off.

@thymikee

Copy link
Copy Markdown
Member

The code and docs are ready at 786f878. The mixed-version trade-off is now stated in the shipped help and the user docs, and the docs-only change matches the code. CI is green and there are no conflicts.

The one remaining item is the maintainer sign-off on that trade-off (an older and a newer build must not share one host on macOS or BSD), which this change states but does not give: #4682 (comment)

Not blocking, take or leave:

  • The "three artifacts" list in cli-help.ts:423 is closed, but other records that store a process start time have the same raw-versus-token mismatch (owned-process records, process-lock owner records, Metro companion state, the agent-browser process record). "Other records that store a process start time" would be more accurate in both files.
  • The new "do not run an older and a newer build on one host" line in website/docs/docs/commands.md:96 applies only on macOS or BSD, since Linux and Windows start times are unchanged. It could start with "On macOS or BSD,".
  • The help line reads "and records an older macOS or BSD build wrote" while commands.md says "records that an older macOS or BSD build wrote"; keeping "that" in cli-help.ts would align them.

The same-host scope note, the "start-time token" wording note and the note about keeping the row when lstart does not parse are settled at this head.

Not verified here: an older build was not run against a newer state directory, so the mixed-host failure is reasoned from the code, not reproduced. The live macOS runs from the PR body were not repeated; this change does not touch that path.

…tart-time record

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@thymikee

Copy link
Copy Markdown
Member

The three wording notes are applied in af8197c, with the same sentence in the help line and commands.md:

  • The warning starts with "On macOS or BSD,".
  • The record list is open: "the daemon registration, the companion tunnel, runner leases, and other records that store a process start time".
  • Both files say "records that an older build wrote".

The remaining item is the maintainer's sign-off on the trade-off.

@thymikee

Copy link
Copy Markdown
Member

Thanks for the update. At af8197c the mixed-build warning is scoped to macOS and BSD and names the records that store a start time, as the last review suggested. CI is green and there are no conflicts. Review has nothing blocking left; the remaining item is the maintainer sign-off on the mixed-build trade-off.

Two notes for a follow-up, not for this PR:

  • The help in cli-help.ts and commands.md say older Linux registrations stop normally. That does not hold in one fallback case: when agent-device cannot read the daemon's /proc birth identity (for example an unreadable boot_id) and falls back to ps, an older build stored raw lstart and this build reads posix:<epochMs>, so the mixed-build limits apply there too. Limiting the compatibility sentence to Linux /proc tokens and Windows CIM tokens would be exact.
  • host-kit could own one C-locale lstart field parser, shared by host-process.ts and simulator-boot.ts.

Not verified here: the change touches only help text and a docs page, so no tests were run and the code outside the change was not re-reviewed.

…d Windows tokens

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@thymikee

Copy link
Copy Markdown
Member

Both follow-up notes are handled:

  • Linux ps fallback: fixed in 6938e4d. The help line and commands.md now say that only registrations with a Linux /proc or Windows start-time token still stop normally. A Linux registration read through the ps fallback (for example with an unreadable boot_id) has the same limits as macOS and BSD.
  • Shared lstart parser: tracked in host-kit: own one C-locale lstart parser for host-process and simulator-boot #4875, to do after this PR merges. It touches simulator boot observation in platform-apple, which is outside this change.

The remaining item is the maintainer's sign-off on the trade-off.

@thymikee

Copy link
Copy Markdown
Member

Thanks for the update.

One defect remains at 6938e4d. The POSIX token classifier at https://github.com/callstack/agent-device/blob/6938e4d/packages/host-kit/src/internal/host-process.ts#L268 accepts any nonnegative whole-second safe integer, including posix:8640000000001000. That value is outside the four-digit year range the producer can emit and outside JavaScript's Date range. An in-memory run of stopDaemonProcess at this commit against a live macOS PID with that recorded token returned exited/already-exited, because waitForDaemonExit treats the malformed token as comparable to the real token and reads the difference as exit proof. A corrupted start-time token in daemon.json can therefore make daemon stop report a live daemon as already exited, and retirement can then remove registration metadata when the startup lock is free. The rule the code must satisfy: a POSIX token is valid only inside the UTC range the producer can emit, through 9999-12-31T23:59:59Z. Please bound the classifier to that range and add an out-of-range whole-second safe integer to the malformed-token stop regression.

Could host-kit own one C-form lstart field decoder for process identity and Simulator boot observation, with each caller keeping its current UTC or local-time interpretation?

The earlier evidence request is now satisfied. CI is green, and the body rules check now passes at this commit. The change since the earlier review touches only a help string and a docs line, and the other 15 checks passed. No conflicts are known. Not verified here: a fresh test run, since the delta is text only. After the fix, the remaining step before merge is maintainer sign-off on the mixed-build trade-off, which this review does not re-raise.

A posix: token is valid only through 9999-12-31T23:59:59Z, the last instant the four-digit-year lstart rendering can emit. A larger whole-second safe integer is malformed, so a corrupted daemon.json token no longer reads as exit proof in stopDaemonProcess.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@pcbeingused333

Copy link
Copy Markdown
Contributor Author

Bounded the POSIX token classifier to the UTC range the producer can emit, through 9999-12-31T23:59:59Z (253402300799000 ms), in startTimeTokenSource (host-process.ts). A whole-second safe integer past that, such as posix:8640000000001000, is now malformed, so waitForDaemonExit no longer reads it as exit proof and stopDaemonProcess retains the daemon. The malformed-token stop regression in daemon-exit-wait.test.ts now includes posix:8640000000001000 and posix:253402300800000 (the first instant past the bound). Both fail without the change and pass with it; the host-kit unit tests pass.

The shared C-form lstart decoder stays in #4875, as agreed.

Disclosure: this change was prepared with an AI coding assistant (Claude), and the diff and test results were not reviewed by a human before posting.

@thymikee

Copy link
Copy Markdown
Member

Thanks for the update. The earlier findings from the first review (#4682 (comment)) are fixed at a8c4bbf, and one new problem remains.

host-process.ts is now 1003 lines, over the 1000-line oxlint max-lines limit, so the required Lint, Typecheck & Package check fails. The three lines added in this update (POSIX_TOKEN_MAX_EPOCH_MS and its comment) crossed the limit. Please split the file at its owner instead of adding a waiver or disable comment. The host CPU architecture block (around lines 935-1003: pendingHostCpuArch, settledHostCpuArch, readHostCpuArch, readHostCpuArchSync, settleHostCpuArch, resolveHostCpuArch, hostCpuArchName, isAppleSiliconMac, isAppleSiliconMacSync, plus the APPLE_SILICON_SYSCTL and SYSCTL_TIMEOUT_MS constants) shares no state with process identity. It can move to packages/host-kit/src/internal/host-cpu-arch.ts, which needs only runCmd and runCmdSync from exec. Update the importers, move any Fallow baseline entry with the symbols, and keep the CPU-arch tests beside the new module. That frees about 65 lines.

The failing check is in a file this PR edits, so it is likely related to this change. The other 14 checks pass, including typecheck and format. No conflicts are known.

Not verified here: the host-kit and daemon-exit-wait tests were not run locally, and no live macOS run was done. The ps lstart read is covered only by mocked reads in tests. Once the file is split and Lint, Typecheck & Package is green, this is ready for another look.

…-process

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@thymikee

Copy link
Copy Markdown
Member

The max-lines failure is fixed in b11ff89. As suggested, the host CPU architecture block moved to packages/host-kit/src/internal/host-cpu-arch.ts. That module imports only runCmd and runCmdSync from exec. Its tests moved with it to host-cpu-arch.test.ts, and process.ts re-exports both readers from the new module, so no importer changes. host-process.ts is now 930 lines. No Fallow baseline entry named these symbols. Locally, the host-kit lint, typecheck, and the CPU-arch and host-process tests pass. CI owns the rest.

A host-kit module beside host-process grows every entry's eager closure,
so the CPU-arch reader stays in host-process and its two sysctl calls share
one options object.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@thymikee

Copy link
Copy Markdown
Member

The suggested split failed the eager-closure gate in Coverage. At b11ff89, host-cpu-arch.ts was a new module that every entry evaluates through host-kit/process. Since this PR also adds statements compared with main, the gate does not count that as a pure split (src/cli.ts 275 → 276 modules, +7 statements, and 25 more entries). The modules the closure already loads can't hold it either: owner-identity.ts imports host-process.ts, and exec.ts does not own CPU architecture.

1ce8933 reverts the split and keeps the reader in host-process.ts. Its two sysctl calls now share one SYSCTL_OPTIONS object, which brings the file to 997 lines, with no waiver or new module. Locally, the host-kit lint, typecheck, the CPU-arch and host-process tests, and eager-closure-budgets.test.ts pass. CI owns the rest.

@thymikee

Copy link
Copy Markdown
Member

Thanks for the update.

The findings from the earlier review are now fixed at 1ce8933, and the code shows no new problems. Checks are green: the cancelled body-rules run is superseded by a passing run at this head. No conflicts. The change still waits on maintainer sign-off for the mixed-build trade-off, so it is not ready to merge yet.

Could the follow-up in #4875 put the shared C-locale lstart field decoder in host-kit, keep the UTC token in host process identity, and keep the local-time conversion in Simulator boot observation? The production posix: checks would stay inside host-kit, and the generic envOverrides option would be applied at the exec spawn sites.

Not verified here: the tests and the eager-closure and coverage gate were not re-run locally; the result relies on the CI checks.

@thymikee

Copy link
Copy Markdown
Member

On the #4875 follow-up: we don't plan to build it. A shared decoder removes about 15 duplicated lines and changes no behavior. Against that:

  • host-process.ts is at 997 of 1000 lines. A new host-kit module grows every entry's eager closure, as this PR showed, so the exported decoder would have to live in that file and would likely push it over the limit again.
  • Simulator boot observation in platform-apple would depend on host-kit's process-identity module for a 12-line field parser.
  • Simulator boot observation is device-facing, so the change would need an iOS simulator run.
  • The local-time read there is correct: ps renders and the code parses in the same process's time zone, so the two parsers differ only in style.

The envOverrides option is already applied at the exec spawn sites (hostPsOptions passes it to runCmd and runCmdSync). #4875 stays open and is closed after this PR merges, unless a maintainer wants it.

@thymikee

Copy link
Copy Markdown
Member

The reasons in #4682 (comment) settle the design question from the review at 1ce8933: the shared decoder would grow the eager closure or push host-process.ts over its limit, and it would add a device-facing change for about 15 lines. Nothing from review blocks this head. The remaining item is the maintainer sign-off on the mixed-build trade-off.

@thymikee

Copy link
Copy Markdown
Member

Maintainer sign-off: the mixed-build trade-off is accepted as stated in the help text and commands.md. On macOS and BSD, an older and a newer build must not share one host. No further compatibility work is planned for this PR.

@thymikee

Copy link
Copy Markdown
Member

With the maintainer sign-off on the mixed-build trade-off (#4682 (comment)) and the design question settled, nothing from review blocks 1ce8933. CI is green and there are no conflicts.

@thymikee thymikee added the ready-for-human Valid work that needs human implementation, judgment, or maintainer merge label Nov 21, 2026
@thymikee
thymikee merged commit 4075dd1 into callstack:main Nov 21, 2026
15 of 16 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-for-human Valid work that needs human implementation, judgment, or maintainer merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

macOS: daemon stop orphans a live daemon when the daemon and the client run under different LC_TIME locales (ps -o lstart is not locale-pinned)

2 participants