Skip to content

Commit 59bfaab

Browse files
committed
feat(lifecycle): detached handoff supervisor with OS-owned callback
An agent running inside T3 cannot upgrade T3: the lifecycle action kills the agent before it can report back. This adds a detached handoff that moves the action to an OS-owned supervisor whose lifetime is independent of T3. - handwritten envelope (owner-private, credentials refused) describing the originating thread, command, wait target, relaunch, readiness and callback; - macOS: transient per-handoff LaunchAgent; Windows: transient current-user Scheduled Task (InteractiveToken, LeastPrivilege, one-shot); - explicit state machine PREPARED..COMPLETE/FAILED, single-run claim, and terminal-result idempotency that refuses to re-run the destructive command; - independence proof (direct parent pid 1, no initiator ancestor) required before the initiator may stop T3; - callback contract: local result envelope + GitHub receipt; no state.sqlite writes, no fabricated orchestration events, no copied credentials. Zero-dependency ESM under scripts/lifecycle-handoff with unit tests and a real launchd fixture (fake parent exits, supervisor survives, runs a harmless command, relaunches a fake service, calls back once, unregisters itself). Non-overlapping with the Windows SCM lifecycle work on PR #10.
1 parent 419f757 commit 59bfaab

15 files changed

Lines changed: 1751 additions & 0 deletions
Lines changed: 147 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,147 @@
1+
# Detached lifecycle handoff
2+
3+
A lifecycle action that stops or replaces T3 (install, update, restart) cannot be
4+
performed by an agent running *inside* T3: the action kills the agent that is
5+
executing it, so the last step — reporting back — never runs. A **detached
6+
handoff** moves the action to an OS-owned helper whose lifetime is independent of
7+
T3, and gives that helper enough state to relaunch T3 and report the result into
8+
the thread that requested it.
9+
10+
Implementation lives in [`scripts/lifecycle-handoff/`](../../scripts/lifecycle-handoff/README.md).
11+
12+
## Execution model
13+
14+
```
15+
initiating agent (inside T3)
16+
├─ writes a user-private envelope PREPARED
17+
├─ registers a transient OS job DETACHED
18+
└─ proves the helper is OS-owned, then quits T3
19+
│
20+
OS-owned supervisor (launchd / Task Scheduler)
21+
├─ verifies its own ancestry
22+
├─ waits for the initiating pid to exit WAITING_FOR_EXIT
23+
├─ runs the lifecycle command APPLYING
24+
├─ relaunches T3 RELAUNCHING
25+
├─ waits for readiness WAITING_FOR_T3
26+
├─ runs an optional identity probe
27+
├─ delivers the callback + writes the result CALLBACK_PENDING
28+
├─ writes the terminal result envelope COMPLETE / FAILED
29+
└─ removes its own job registration
30+
```
31+
32+
The supervisor never force-kills a process. If the waited-for pid is still alive
33+
when its bound expires, the handoff fails with `FAILED` and durable evidence
34+
rather than killing active work.
35+
36+
## Supervisor mechanism
37+
38+
**macOS** — a transient, per-handoff LaunchAgent in `~/Library/LaunchAgents`
39+
(`RunAtLoad`, `KeepAlive=false`, `ProcessType=Background`, log to the handoff
40+
directory). `launchctl bootstrap gui/<uid> <plist>` starts it; its direct parent
41+
is launchd (pid 1), so T3/Electron job-object teardown cannot reach it. It removes
42+
its own plist and `launchctl bootout`s itself as its last step.
43+
44+
**Windows** — a transient current-user Scheduled Task created from an XML task
45+
definition (`InteractiveToken`, `LeastPrivilege`, one `TimeTrigger`,
46+
`StartWhenAvailable`). The Task Scheduler service owns the process, so it is not
47+
an Electron job-object child. `schtasks /Delete` removes it at the end. This path
48+
is implemented but **has not been executed on a Windows host** (see "Validation").
49+
50+
`nohup`, `Start-Process`, and terminal detachment are deliberately not used:
51+
neither reliably escapes the parent job object on the platforms that matter.
52+
53+
## Independence proof
54+
55+
Before the initiating agent may quit T3 it must show the helper cannot be killed
56+
with T3. `handoff.mjs prepare` polls `launchctl print gui/<uid>/<label>` for the
57+
job pid, then walks the process parent chain:
58+
59+
- `directParent === 1` (launchd) is required;
60+
- none of the helper's ancestors may be the initiator or its parent.
61+
62+
The proof is stored in the handoff state file. If it fails, `prepare` boots the
63+
job out and throws — T3 is never stopped on an unproven helper.
64+
65+
## Handoff envelope
66+
67+
Written to `paths.dir/<handoffId>.envelope.json`, mode `0600`, in a `0700`
68+
directory (default `~/.t3/userdata/lifecycle-handoff`). Required fields:
69+
70+
| Field | Meaning |
71+
| --- | --- |
72+
| `handoffId` | unique id; also the idempotency key |
73+
| `originating.threadId` / `projectId` / `machine` / `platform` | where to return |
74+
| `task.description` / `operation` | what is being done |
75+
| `command.argv` / `cwd` / `timeoutMs` | the lifecycle command |
76+
| `waitFor.pid` / `timeoutMs` | the process whose exit gates the command |
77+
| `relaunch.argv` | how to bring T3 back (empty = no relaunch) |
78+
| `readiness` | `none` \| `file` \| `pid` \| `tcp` \| `http` |
79+
| `identity.before` / `after` / `afterCommand` | expected and independently observed identity |
80+
| `callback` | `none` \| `github` \| `http` |
81+
| `paths` / `supervisor` | state, log, result, node and script paths |
82+
83+
Credentials are rejected at write time: any key matching
84+
`token|secret|password|credential|bearer|api-key|private-key|cookie`, and any value
85+
shaped like a GitHub/Slack/OpenAI/JWT/PEM credential, fails the write.
86+
87+
## Callback contract
88+
89+
The supervisor always writes a terminal result envelope to `paths.result`. The
90+
callback is a best-effort *notification* layered on top:
91+
92+
- `none` — result envelope only.
93+
- `github` — `gh issue comment <issue> --repo <repo> --body-file -` with a short
94+
message. This is the durable cross-machine receipt when no T3 callback exists.
95+
- `http` — `POST` JSON `{handoffId, state, message}`.
96+
97+
Message shape:
98+
99+
```
100+
DETACHED HANDOFF COMPLETE <id>.
101+
Operation: <op> (exit=0).
102+
Before: {"version":"0.0.43"}
103+
After: "0.0.44"
104+
Result: <result path>
105+
```
106+
107+
**Supported T3 callback: not available today.** T3 exposes no CLI or REST command
108+
that appends a message / starts a turn. The only supported mutation transport is
109+
the authenticated `/ws` `orchestration.dispatchCommand` (`thread.turn.start`),
110+
which needs an environment-session credential. The supervisor therefore does
111+
**not** touch `state.sqlite`, does not fabricate orchestration events, and does not
112+
copy auth tokens; it uses the result envelope + GitHub receipt fallback. When a
113+
supported callback endpoint exists, it slots in behind `callback.kind = "http"`
114+
without changing the lifecycle logic.
115+
116+
## Security model
117+
118+
- Envelope, state, log, and result files are owner-private (`0600`) in a `0700`
119+
directory; the plist/task XML is `0600`.
120+
- No secrets in the envelope, argv, or logs; credential-shaped values are refused.
121+
- No root/SYSTEM task; the Windows task is `LeastPrivilege`, InteractiveToken.
122+
- No database access and no orchestration-event fabrication.
123+
- `KeepAlive=false` and a single-run claim (`<handoffId>.lock`) mean a crash cannot
124+
become an endless restart loop.
125+
- The callback is attempted only after the result is durable, so a failed receipt
126+
still leaves local evidence.
127+
128+
## Recovery procedure
129+
130+
1. `node scripts/lifecycle-handoff/handoff.mjs status --dir <dir> --id <id>` — read
131+
`state` and `result`.
132+
2. Read `<dir>/<id>.log` and `<id>.state.json` — every transition is timestamped.
133+
3. `FAILED` results carry `failure.reason`; `command.stdoutTail/stderrTail`
134+
preserve the command's own evidence.
135+
4. A terminal result means the destructive command will **not** run again; re-running
136+
the same handoff id is a no-op. To retry deliberately, start a new handoff id.
137+
138+
## Validation
139+
140+
- Harmless fixture on macOS (real launchd): fake parent → prepare → parent exits →
141+
supervisor survives → harmless command runs → fake service returns → callback
142+
delivered exactly once → job unregistered → idempotent replay is a no-op.
143+
- Windows: implemented, not executed (no Windows host here).
144+
- A real-T3 restart smoke is intentionally **not** run from an active initiating
145+
session, because it would terminate that session. The mechanism to do so is
146+
proven by the fixture; run the real smoke only from an idle T3 with a bounded,
147+
non-mutating command.
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
# Detached lifecycle handoff
2+
3+
Move a T3-stopping lifecycle action (install / update / restart) to an OS-owned
4+
supervisor that survives T3 exiting, then report the outcome back. Design and
5+
security model: [`docs/internals/lifecycle-handoff.md`](../../docs/internals/lifecycle-handoff.md).
6+
7+
Zero dependencies; runs on the Node that is already present.
8+
9+
## How an agent invokes it
10+
11+
1. Write a request JSON (`command.argv` is the lifecycle command; `waitPid` is the
12+
pid that must exit first — normally the T3 server):
13+
14+
```json
15+
{
16+
"threadId": "<t3 thread id>",
17+
"projectId": "<project id>",
18+
"operation": "update",
19+
"description": "upgrade T3 to the next released build",
20+
"agentPid": 1234,
21+
"waitPid": 5678,
22+
"command": { "argv": ["/path/to/t3", "update"], "timeoutMs": 900000 },
23+
"relaunch": { "argv": ["open", "-a", "/Applications/T3 Code (Alpha).app"] },
24+
"readiness": { "kind": "http", "url": "http://127.0.0.1:3773/health" },
25+
"identity": { "before": { "version": "0.0.43" }, "afterCommand": { "argv": ["/path/to/t3", "--version"] } },
26+
"callback": { "kind": "github", "github": { "repo": "nullStack65/t3code", "issue": 10 } }
27+
}
28+
```
29+
30+
2. Prepare and verify independence. **Only quit T3 if this exits 0:**
31+
32+
```bash
33+
node scripts/lifecycle-handoff/handoff.mjs prepare --request request.json
34+
```
35+
36+
It prints the handoff id and the independence proof
37+
(`registration.proof.independent === true`, `directParent === 1`). If it fails, it
38+
has already unregistered the job — do not stop T3.
39+
40+
3. Read progress:
41+
42+
```bash
43+
node scripts/lifecycle-handoff/handoff.mjs status --dir <dir> --id <handoffId>
44+
```
45+
46+
## Layout
47+
48+
| File | Purpose |
49+
| --- | --- |
50+
| `handoff.mjs` | initiating-agent CLI (`prepare` / `status` / `verify`) |
51+
| `supervisor.mjs` | detached entry point started by launchd / Task Scheduler |
52+
| `lib/envelope.mjs` | envelope schema, secret refusal, state names |
53+
| `lib/process.mjs` | liveness and parent-chain independence proof |
54+
| `lib/platform.mjs` | LaunchAgent and Scheduled Task rendering + registration |
55+
| `lib/state.mjs` | atomic owner-only state writes, single-run claim |
56+
| `lib/run.mjs` | the state machine + readiness + callback |
57+
| `fixtures/` | harmless fake parent / command / service for the fixture test |
58+
59+
## Tests
60+
61+
```bash
62+
node --test test/envelope.test.mjs test/run.test.mjs # unit
63+
node --test test/fixture.integration.test.mjs # real launchd (macOS)
64+
```
65+
66+
The integration test runs a real LaunchAgent: a fake parent prepares a handoff,
67+
exits, and the detached supervisor is asserted to survive, run a harmless command,
68+
relaunch a fake service, call back exactly once, unregister itself, and refuse to
69+
re-run the destructive command on replay.
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
// Harmless stand-in for the real lifecycle command.
2+
import { writeFileSync } from "node:fs";
3+
writeFileSync(process.argv[2], `applied:${new Date().toISOString()}\n`);
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
// Fake initiating agent. It prepares a real detached handoff for a harmless
2+
// command, then exits — exactly the moment the real agent would quit T3.
3+
import { spawnSync } from "node:child_process";
4+
import { mkdirSync, writeFileSync } from "node:fs";
5+
import { dirname, join } from "node:path";
6+
import { fileURLToPath } from "node:url";
7+
8+
const [dir, port] = process.argv.slice(2);
9+
const here = dirname(fileURLToPath(import.meta.url));
10+
const handoffCli = join(here, "..", "handoff.mjs");
11+
mkdirSync(dir, { recursive: true });
12+
13+
const request = {
14+
threadId: "fixture-thread",
15+
projectId: "fixture-project",
16+
machine: "fixture-machine",
17+
operation: "fixture-restart",
18+
description: "harmless detached handoff fixture",
19+
agentPid: process.pid,
20+
waitPid: process.pid,
21+
waitTimeoutMs: 30_000,
22+
command: { argv: [process.execPath, join(here, "apply.mjs"), join(dir, "applied.marker")] },
23+
relaunch: { argv: [process.execPath, join(here, "fake-service.mjs"), join(dir, "service-ready.marker")] },
24+
readiness: { kind: "file", path: join(dir, "service-ready.marker"), timeoutMs: 30_000, pollMs: 200 },
25+
identity: {
26+
before: { version: "0.0.43" },
27+
after: { version: "0.0.44" },
28+
afterCommand: { argv: [process.execPath, "-e", "process.stdout.write('0.0.44')"] },
29+
},
30+
callback: { kind: "http", url: `http://127.0.0.1:${port}/callback` },
31+
};
32+
33+
const requestPath = join(dir, "request.json");
34+
writeFileSync(requestPath, JSON.stringify(request, null, 2));
35+
const outcome = spawnSync(process.execPath, [handoffCli, "prepare", "--request", requestPath, "--dir", dir], {
36+
encoding: "utf8",
37+
});
38+
process.stderr.write(outcome.stderr ?? "");
39+
if (outcome.status !== 0) {
40+
process.stderr.write(`prepare failed: ${outcome.stdout}\n`);
41+
process.exit(outcome.status ?? 1);
42+
}
43+
writeFileSync(join(dir, "parent-prepared.json"), outcome.stdout ?? "");
44+
// Exiting here releases the supervisor's wait, mirroring an agent quitting T3.
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
// Harmless stand-in for relaunching T3: the "service" comes back and writes a
2+
// readiness marker the supervisor can observe.
3+
import { writeFileSync } from "node:fs";
4+
writeFileSync(process.argv[2], `ready:${process.pid}\n`);

0 commit comments

Comments
 (0)