Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 70 additions & 2 deletions packages/desktop/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,14 +69,14 @@ Expect zero events for `/usr/bin/codesign`, `/Applications/Harness.app`, and `Ha

`Harness.app` carries the Tracker: the compiled Harness CLI at `Contents/Helpers/harness` (the same executable `harness tracker serve` runs, signed with the app's Developer ID and hardened runtime, with the entitlements in `scripts/mac-tracker-entitlements.plist` that Bun's JIT needs) and the `tracker` shim at `Contents/Resources/tracker-shim.sh`. `bun run package:mac --verify` refuses an app without them, with the wrong signature, or whose executable does not report a version.

Installing or replacing the app is the only step. Each packaged launch starts `startBundledTracker` in the background, which:
Installing or replacing the app is the only step. Each packaged launch starts `startBundledTracker` in the background. A launch verifies the installed Tracker revision against the Git history sealed into the signed app, then:

1. Copies the executable and shim to an immutable release at `~/.local/state/tracker/harness-releases/<id>/` (content-named, `SHA256SUMS`, `BUILD_COMMIT`), so the running service survives the app being replaced, and keeps the last three releases it staged.
2. Points `~/.local/libexec/harness/harness` and `~/.local/bin/tracker` at that release with atomic link swaps. A regular file at either path is never replaced; the install stops and reports it.
3. Repoints only the executable (`ProgramArguments[0]`) of the existing `local.harness.tracker` LaunchAgent, then reloads it. The `--config` path, role, environment, logs, SQLite journal, secrets and fence files are not touched. If there is no agent but `~/.config/harness/tracker.json` exists, it writes one for that file's role; with no configuration it installs the command line only.
4. Waits for `harness tracker ensure` to report ready. If the new release does not become ready in 30 seconds, it restores the previous executable, links and agent and reports `rolled-back`.

A launch with its own `--user-data-dir` (tests, or a candidate run beside the installed app) skips all of this. A second launch with the same app changes and restarts nothing. Another app instance or an installer already running holds a lock, so two installs never interleave. A LaunchAgent whose command is not `tracker serve` is refused. Rollback of a bad app is the previous release directory plus `launchctl bootout`/`bootstrap` of the previous agent file; the previous app bundle remains the rollback source for the executable.
A launch with its own `--user-data-dir` (tests, or a candidate run beside the installed app) skips all of this. A second launch with the same app changes and restarts nothing. Packaged startup and the [native release installer](#native-release-activation) share the Mac activation lock. A LaunchAgent whose command is not `tracker serve` is refused. Rollback of a bad app is the previous release directory plus `launchctl bootout`/`bootstrap` of the previous agent file; the previous app bundle remains the rollback source for the executable.

## Projects and shared collaboration

Expand Down Expand Up @@ -211,3 +211,71 @@ The first plugin supports Cloudflare Workers with explicit named environments an
```

Add stage, preprod and prod entries for configured targets. Worker mappings must match an explicit `env.<name>.name` in Wrangler and use distinct Worker identities. Pages mappings instead name a `branch` and the Pages project `name`; output comes from `pages_build_output_dir`. The adapter checks the live Pages production branch before upload. Provider credentials are read only in the host, passed only to the adapter subprocess and removed from agent/check subprocess environments. Set the dedicated variables in the desktop host's managed launch environment; do not put tokens in this JSON. A repository needs its normal `check` and `build` scripts and locally installed Wrangler. Receipts live in the Git common directory's `harness-deployments/receipts.json` and are shared across worktrees. Remote phones and hosted read-only projects cannot execute deployment operations.

## Native release activation

Build, sign, verify, and stage artifacts before acquiring an activation lock. Run the
approved activation plan through `bun scripts/native-install.ts` from the repository
root on the computer named for each target. Start from the same plan on both Macs.
A plan pins one Git revision, an owner, and the release approval reference. Each
target has a stable ID, an absolute canonical artifact path, the expected code
signature CDHash, and instructions or an artifact location for rollback.

```text
bun scripts/native-install.ts activate /path/to/release.json primary
bun scripts/native-install.ts activate /path/to/release.json mb2 /path/to/primary.json
bun scripts/native-install.ts activate /path/to/release.json iphone
bun scripts/native-install.ts status /path/to/release.json
```

The plan has `id`, `revision`, `owner`, `approval`, `targets`, and optionally
`primaryFirst` set to the primary Mac target ID. Each target has `id`, `kind`,
`computer` (the local Tracker node), `artifact`, `signature`, and `rollback`.
Use a separate ID for each release and each target. Set `primaryFirst` when the
release order requires it. The other targets require that release's exact
primary receipt. On MB2 pass the primary receipt from the completed primary
activation, using the approved host-work path for remote operations.

- **`mac`** uses a signed `Harness.app` and an `activate` argument array beginning
with the absolute path to the approved bundle replacement script. The script
keeps the previous app, quits Harness normally, swaps the bundle, and returns.
Launch Harness after the command reports installed. App startup takes the same
Mac lock and handles the bundled Tracker separately. Mac readback checks the
installed app's actual code signature and revision and verifies that the
Tracker stayed at the pre-install revision during the bundle swap.
- **`tracker`** uses the staged release directory and an `activate` argument
array for the approved standalone activation script. Preserve the
restart-before-repoint sequence and its health and rollback checks inside the
script. Set `checksums` to the SHA-256 of `SHA256SUMS`; that file must cover
`harness`, `tracker-shim.sh`, and `SOURCE_COMMIT`. For a separately approved
deliberate Tracker rollback, create its own plan and set the target's
`rollbackFrom` to the exact live revision that the approval names.
- **`iphone`** runs on `daniel-primary-mbp` with the paired physical device's
CoreDevice UUID in `device`. Use the signed `.app`, a unique fourteen-digit
build number in `build`. Build the renderer from the clean pinned checkout, then
run `bun scripts/native-install.ts stamp-ios packages/desktop/build` before
running `cap sync ios` from the desktop package. Sync copies the revision stamp
into the web assets that Xcode seals inside the signed app. The installed
build number is read directly from the requested physical iPhone via
`devicectl`.

Both Mac activation paths share the same lock on that Mac. The primary Mac
holds the distinct lock for the paired iPhone. The release command waits up to
five minutes for an ongoing activation. The kernel releases a lock when
its last holder exits. The lease expiry in the receipt is for diagnosis. A retry
takes the same lock, reads the target again, and reconciles any interrupted
attempt against that observation. Keep the old release artifacts until the
release is verified and its rollback window has closed.

Receipts are under `~/.local/state/tracker/native-install/<release-id>/<target-id>.json`.
They record the owner, approval, artifact, expected and previous revisions,
Tracker compatibility floor, lease, rollback, and actual readback. To combine
status across the Macs, copy the receipts into one private directory with the
same release/target layout and pass its root to `status`. A target with no receipt
is pending. A failed or interrupted readback is unconfirmed. An installed receipt
reports what the target returned at its recorded observation time.

The Mac bundle installer rejects a candidate whose Git history excludes the
active Tracker revision. For rollback of the desktop app, keep a verified
compatible app artifact and follow the approved rollback instructions. Legacy
Mac bundles built before this guard can replace Tracker on launch.
1 change: 1 addition & 0 deletions packages/desktop/scripts/package-mac-app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ async function copyProject(output: string, sources: MacAppSources): Promise<void
productName: 'Harness',
version: '0.1.0',
revision: sources.revision,
trackerAncestors: sources.trackerAncestors,
main: 'dist/main.cjs'
})
);
Expand Down
2 changes: 2 additions & 0 deletions packages/desktop/scripts/package-mac-app.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,6 @@ export interface MacAppSources {
/** The built renderer. */
renderer: string;
revision: string;
/** Ancestors sealed into the signed package for offline Tracker compatibility checks. */
trackerAncestors?: readonly string[];
}
13 changes: 12 additions & 1 deletion packages/desktop/scripts/package-mac.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,8 @@ function verifyRelease(app: string): void {
throw new MacPackageError('Artifact must use the signed Harness Safe Storage namespace.');
if (!isRevision(manifest.revision))
throw new MacPackageError('Artifact must embed the full git commit it was built from.');
if (!Array.isArray(manifest.trackerAncestors) || !manifest.trackerAncestors.every(isRevision))
throw new MacPackageError('Artifact must embed signed Tracker revision ancestry.');
}

async function packageRelease(): Promise<void> {
Expand All @@ -100,7 +102,16 @@ async function packageRelease(): Promise<void> {
try {
const bundles = join(staging, 'bundles');
await buildDesktopMain(define, bundles);
await assembleMacApp(candidate, { bundles, renderer: resolve('build'), revision });
const ancestry = execFileSync('git', ['rev-list', revision], {
encoding: 'utf8',
maxBuffer: 16 * 1024 * 1024
});
await assembleMacApp(candidate, {
bundles,
renderer: resolve('build'),
revision,
trackerAncestors: ancestry.trim().split('\n').slice(1)
});
const { sign } = await import('@electron/osx-sign');
await sign({
app: candidate,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ export interface TrackerBundleHost {
run(file: string, args: string[], env?: Record<string, string>): Promise<TrackerBundleRun>;
/** The user id whose launchd domain owns the service. */
uid: number;
/** For a packaged launch, identify the executable launchd is actually using. */
activeExecutable?(): Promise<string | null>;
sleep(milliseconds: number): Promise<void>;
}

Expand All @@ -18,6 +20,8 @@ export interface TrackerBundleInput {
app: string;
/** The full git commit the app was built from. */
revision: string;
/** Git ancestors sealed into the signed app manifest. */
ancestors?: readonly string[];
home: string;
host: TrackerBundleHost;
/** How many one-second readiness checks to allow after a restart. */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ import type { TrackerBundleLayout } from './trackerBundleLayout.types';
import type { ReleaseLink } from './trackerSessionLinks.types';
import { stageTrackerRelease } from './stageTrackerRelease';
import { inspectLink, replaceSymlink } from './replaceSymlink';
import { recordRelease, withLock } from './trackerBundleRecord';
import { recordRelease } from './trackerBundleRecord';
import { withNativeActivationLock } from './nativeActivationLock';
import { trackerFloorRefusal } from './trackerRevisionFloor';
import { activateService, serviceConfig } from './activateTrackerService';
import { trackerSessionLinks } from './trackerSessionLinks';
import { isTrackerServe, readAgentProgram } from './trackerLaunchAgent';
Expand Down Expand Up @@ -39,8 +41,12 @@ export async function installBundledTracker(
if (!(await present(files.executable)) || !(await present(files.shim)))
return { status: 'not-bundled' };
const layout = trackerBundleLayout(input.home);
const outcome = await withLock(layout.lock, () => apply(input, layout, files));
return outcome ?? { status: 'refused', reason: 'Another Tracker install is running.' };
const outcome = await withNativeActivationLock(
layout.lock,
() => apply(input, layout, files),
10
);
return outcome ?? { status: 'refused', reason: 'Another native install is running on this Mac.' };
}

/** Points each link into the release and returns what it held, for a rollback. */
Expand All @@ -52,16 +58,32 @@ async function repointLinks(links: ReleaseLink[], release: string) {
return before;
}

async function bundleRefusal(
input: TrackerBundleInput,
layout: TrackerBundleLayout,
program: string[] | null
): Promise<string | null> {
if (program !== null && !isTrackerServe(program))
return 'The Tracker LaunchAgent is not a Tracker service.';
const foreign = await foreignEntry(layout);
if (foreign) return `${foreign} is not a link this app owns.`;
const active = await input.host.activeExecutable?.();
if (active && !(await present(active))) return 'The loaded Tracker executable is missing.';
return trackerFloorRefusal(
[...(program ? [program[0]] : []), ...(active ? [active] : []), layout.launcher],
input.revision,
input.ancestors
);
}

async function apply(
input: TrackerBundleInput,
layout: TrackerBundleLayout,
files: ReturnType<typeof bundledTrackerFiles>
): Promise<TrackerBundleOutcome> {
const program = await readAgentProgram(layout.agent, input.host);
if (program !== null && !isTrackerServe(program))
return { status: 'refused', reason: 'The Tracker LaunchAgent is not a Tracker service.' };
const foreign = await foreignEntry(layout);
if (foreign) return { status: 'refused', reason: `${foreign} is not a link this app owns.` };
const refusal = await bundleRefusal(input, layout, program);
if (refusal) return { status: 'refused', reason: refusal };
const staged = await stageTrackerRelease(files, layout.releases, input.revision);
const executable = join(staged.directory, 'harness');
// Every link moves before the service restarts, so it never starts beside an older one.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// @harness-uid u_tqudg6lphc
import { spawn } from 'node:child_process';
import { mkdir, open } from 'node:fs/promises';
import { dirname } from 'node:path';
import { TrackerBundleError } from './TrackerBundleError';

function claim(fd: number, wait: number): Promise<number | null> {
return new Promise((resolve, reject) => {
const process = spawn('/usr/bin/lockf', ['-s', '-t', String(wait), '3'], {
stdio: ['ignore', 'ignore', 'ignore', fd]
});
process.once('error', reject);
process.once('exit', resolve);
});
}

/** The descriptor owns the lock. Keep its inode even when the installer exits or crashes. */
export async function withNativeActivationLock<T>(
file: string,
work: (descriptor: number) => Promise<T>,
wait = 0
): Promise<T | null> {
await mkdir(dirname(file), { recursive: true, mode: 0o700 });
const handle = await open(file, 'a', 0o600);
try {
const status = await claim(handle.fd, wait);
if (status === 75) return null;
if (status !== 0) throw new TrackerBundleError('Could not lock native device activation.');
return await work(handle.fd);
} finally {
await handle.close();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,17 @@ async function readIfPresent(file: string): Promise<string | null> {
}
}

async function existingRelease(
directory: string,
revision: string,
sums: string
): Promise<boolean> {
return (
(await readIfPresent(join(directory, 'SHA256SUMS'))) === sums &&
(await readIfPresent(join(directory, 'SOURCE_COMMIT')))?.trim() === revision
);
}

/**
* Copies the bundled executable and shim to an immutable, content-named release directory
* outside the app, so a running service survives the app being replaced. An existing release
Expand All @@ -31,10 +42,16 @@ export async function stageTrackerRelease(
revision: string
): Promise<StagedRelease> {
const [executable, shim] = await Promise.all([sha256(files.executable), sha256(files.shim)]);
const id = createHash('sha256').update(`${executable}:${shim}`).digest('hex').slice(0, 10);
const directory = join(releases, id);
const sums = `${executable} harness\n${shim} tracker-shim.sh\n`;
if ((await readIfPresent(join(directory, 'SHA256SUMS'))) === sums) return { id, directory };
const legacy = createHash('sha256').update(`${executable}:${shim}`).digest('hex').slice(0, 10);
if (await existingRelease(join(releases, legacy), revision, sums))
return { id: legacy, directory: join(releases, legacy) };
const id = createHash('sha256')
.update(`${revision}:${executable}:${shim}`)
.digest('hex')
.slice(0, 10);
const directory = join(releases, id);
if (await existingRelease(directory, revision, sums)) return { id, directory };
await mkdir(releases, { recursive: true, mode: 0o700 });
const staging = await mkdtemp(join(releases, `.stage-${id}-`));
try {
Expand All @@ -47,7 +64,6 @@ export async function stageTrackerRelease(
await writeFile(join(staging, 'SHA256SUMS'), sums, { mode: 0o600 });
if ((await sha256(join(staging, 'harness'))) !== executable)
throw new TrackerBundleError('The staged Tracker executable does not match the bundle.');
await rm(directory, { recursive: true, force: true });
await rename(staging, directory);
} finally {
await rm(staging, { recursive: true, force: true });
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,13 @@ import { readFile } from 'node:fs/promises';
import { join, resolve } from 'node:path';
import type { TrackerBundleHost, TrackerBundleOutcome } from './TrackerBundleService.types';
import { installBundledTracker } from './installBundledTracker';
import { isTrackerRevision } from './trackerRevisionFloor';
import { trackerLabel } from './trackerBundleLayout';
import { TrackerBundleError } from './TrackerBundleError';

/** Runs programs for real, never through a shell, and reports their exit status. */
export function systemTrackerHost(): TrackerBundleHost {
return {
const host: TrackerBundleHost = {
uid: process.getuid?.() ?? 0,
sleep: (milliseconds) => new Promise((done) => setTimeout(done, milliseconds)),
run: (file, args, env) =>
Expand All @@ -23,6 +26,15 @@ export function systemTrackerHost(): TrackerBundleHost {
);
})
};
host.activeExecutable = async () => {
const result = await host.run('/bin/launchctl', ['print', `gui/${host.uid}/${trackerLabel}`]);
if (result.status === 113) return null;
const executable = /^\s*program = (.+)$/m.exec(result.stdout)?.[1]?.trim();
if (result.status !== 0 || !executable)
throw new TrackerBundleError('Could not read the loaded Tracker launch program.');
return executable;
};
return host;
}

/**
Expand All @@ -37,7 +49,13 @@ export async function startBundledTracker(
): Promise<TrackerBundleOutcome> {
const manifest = JSON.parse(await readFile(join(appPath, 'package.json'), 'utf8'));
const revision: unknown = manifest.revision;
if (typeof revision !== 'string' || !/^[0-9a-f]{40}$/.test(revision))
return { status: 'not-bundled' };
return installBundledTracker({ app: resolve(appPath, '../../..'), revision, home, host });
if (!isTrackerRevision(revision)) return { status: 'not-bundled' };
const ancestors: unknown = manifest.trackerAncestors;
return installBundledTracker({
app: resolve(appPath, '../../..'),
revision,
ancestors: Array.isArray(ancestors) ? ancestors.filter(isTrackerRevision) : [],
home,
host
});
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export function trackerBundleLayout(home: string) {
return {
releases: join(state, 'harness-releases'),
record: join(state, 'tracker-bundle.json'),
lock: join(state, 'tracker-bundle.lock'),
lock: join(state, 'native-install', 'mac.lock'),
launcher: join(home, '.local/libexec/harness/harness'),
entry: join(home, '.local/bin/tracker'),
agent: join(home, 'Library/LaunchAgents', `${trackerLabel}.plist`),
Expand Down
Loading
Loading