The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
feat: harness grid logout, and a word about the credential a sign-out leaves
Kelvin6e1171bea4de
diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 315eece53..b7e55d5d1 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -42,6 +42,8 @@ import { readOrMintComputerId } from './lib/computerIdentity.js'import { renderLoginSuccessHtml } from './lib/loginPage.js'import { AuthSessionError, AuthSessionManager, clearAuthSession, readAuthSession, writeAuthSession, type AuthSession } from './lib/authSession.js'import { handOffToGrid } from './lib/gridHandoff.js'+import { passThroughToGridLogout } from './lib/gridLogout.js'+import { warnIfGridSignInRemains } from './lib/gridCredentials.js'import { ENGINE_CLI_COMMANDS, ENGINES } from './lib/engineBin.js'import { buildEngineCommandArgv, buildEngineLaunchArgv, commandAvailableInInteractiveShell, interactiveEngineShell } from './lib/engineLaunch.js'import { clearDeleted, isRecentlyDeleted, markDeleted } from './lib/deletedSessions.js'@@ -241,6 +243,9 @@ Grid (the fleet of AI engines the \`grid\` CLI serves — needs \`grid\` on PATHno second browser, no second approvalharness grid login --force sign the harness in as a different account first, then the gridharness grid login --json emit the same machine-readable NDJSON \`harness login --json\` emits+ harness grid logout [flags] sign out of your grid — the whole of \`grid logout\`, which stops what+ this box is serving BEFORE deleting anything. Flags go straight to it:+ --force signs out over a serve child it could not confirm stoppedBrowser end-to-end encryption:harness browser-link print a reusable 7-day setup link for browsers@@ -621,6 +626,27 @@ function gridSaid(handoff: { stdout: string; stderr: string }): Record<string, ureturn { ...(out ? { grid: parsed } : {}), ...(err ? { detail: err } : {}) }}+/**+ * `harness grid logout` — the grid sign-out, run as itself, so the pair a person was taught is+ * symmetric.+ *+ * A passthrough and nothing else. The serve-child teardown that runs before any credential is+ * deleted, the refusal that keeps them when a child cannot be confirmed stopped, `--force`, the+ * exit code and every word on either stream are `grid logout`'s. This function's whole job is to+ * adopt the child's exit code and to say the one thing the child cannot: that there was no child.+ *+ * ⚠️ **No cascade into the harness session, and none out of it.** Nothing here reads this+ * computer's SSO session, so no grid condition can decide whether the harness stays signed in — and+ * `harness logout` correspondingly never deletes grid credentials (see `logout` below).+ */+async function gridLogoutCommand(args: string[]): Promise<void> {+ const outcome = await passThroughToGridLogout(args)+ // On the FIELD: both outcomes are truthy objects, and testing the object would read a missing+ // `grid` as a clean sign-out.+ if (outcome.ran === false) console.error(`\n ✗ ${outcome.message}\n`)+ process.exitCode = outcome.exitCode+}+/*** Pulls `code`/`state`/`error` out of whatever the user pasted — the full callback URL, just its query* string (with or without a leading `?`), or a bare `code=...&state=...` pair with no URL shape at all.@@ -790,7 +816,16 @@ async function updateCommand(): Promise<void> {process.exit(0)}-/** Stop the local adapter and discard this computer's SSO session. */+/**+ * Stop the local adapter and discard this computer's SSO session — local, and unable to fail.+ *+ * ⚠️ **This never touches the grid credential store, and must not learn to.** Two reasons, and both+ * matter: `grid logout` can refuse and exit non-zero over a serve child it cannot confirm stopped,+ * so cascading would let a grid condition block a harness sign-out for a reason that has nothing to+ * do with the harness; and the store may predate the harness entirely, having been written by a+ * browser sign-in this CLI knows nothing about. All that is owed is the sentence below, so that a+ * long-lived credential is not left behind in silence.+ */async function logout(): Promise<void> {const pid = readPid()if (pid && isAlive(pid)) { try { process.kill(pid, 'SIGTERM') } catch { /* ignore */ } }@@ -798,6 +833,9 @@ async function logout(): Promise<void> {clearAuthSession()rmSync(MACHINE_NAME_FILE, { force: true })console.log('Signed out. Run `harness login`, then `harness start`, to reconnect this computer.')+ // Existence is the whole of the test — nothing is read out of the store, and nothing is written+ // into it. On stderr, so a script reading this command's output is unaffected by it.+ warnIfGridSignInRemains()process.exit(0)}@@ -3795,6 +3833,9 @@ async function resetCommand(): Promise<void> {if (r.pid) console.log(` Stopped adapter process ${r.pid}.`)clearAuthSession()console.log('\n Start again with: harness login, then harness start\n')+ // The SECOND door onto the sign-out `logout` performs, and it clears MORE, so somebody running it+ // is if anything likelier to believe nothing is left. Same call, so the two cannot drift.+ warnIfGridSignInRemains()process.exit(0)}@@ -4371,6 +4412,14 @@ const flags = rest.filter((a) => a.startsWith('-'))const args = rest.filter((a) => !a.startsWith('-'))const foreground = flags.includes('--foreground') || flags.includes('-f')+/** `argv` with the first occurrence of `token` removed, order otherwise untouched — how a subcommand+ * word is dropped from an argv that is otherwise passed straight to a child. Flags typed BEFORE the+ * word survive, which a slice from its index would discard. */+function withoutFirst(argv: string[], token: string): string[] {+ const at = argv.indexOf(token)+ return at < 0 ? argv : [...argv.slice(0, at), ...argv.slice(at + 1)]+}+if (!cmd || cmd === '--help' || cmd === '-h' || cmd === 'help') usage()if (cmd === 'version' || cmd === '--version' || cmd === '-v') { console.log(VERSION); process.exit(0) }@@ -4417,6 +4466,11 @@ switch (cmd) {breakcase 'grid':if (args[0] === 'login') gridLoginCommand(flags.includes('--force'), flags.includes('--json')).catch(onError)+ // Everything but the verb, in the order it was typed — a passthrough that allow-listed flags+ // would be a second place that has to know what `grid logout` accepts. Only the FIRST `logout`+ // token goes: filtering by value instead would eat an option's *value* the day `grid logout`+ // takes one, forwarding the flag with nothing behind it.+ else if (args[0] === 'logout') gridLogoutCommand(withoutFirst(rest, 'logout')).catch(onError)else { console.error(`Unknown command: grid ${args[0] ?? ''}`); usage(1) }breakcase 'machines':diff --git a/cli/src/gridCommand.spec.ts b/cli/src/gridCommand.spec.tsindex ace4c76de..f4811a828 100644--- a/cli/src/gridCommand.spec.ts+++ b/cli/src/gridCommand.spec.ts@@ -1,13 +1,18 @@/**- * `harness grid login` — the real CLI as a subprocess, against a fake backend and a fake `grid`.+ * The `grid` seam — the real CLI as a subprocess, against a fake backend and a fake `grid`.** The fake `grid` is first on PATH and records the argv and the standard input it was handed. It- * **refuses** argv without `--harness`: asserting that the harness asked for the hand-off is the one- * thing a fake binary can honestly check, since it cannot exchange a token the way the real CLI does.+ * **refuses** a `login` argv without `--harness`: asserting that the harness asked for the hand-off+ * is the one thing a fake binary can honestly check, since it cannot exchange a token the way the+ * real CLI does.+ *+ * Three commands meet here, and the last two are about what does NOT happen: `harness grid login`+ * hands a token over, `harness grid logout` passes straight through to `grid logout` without+ * reproducing any of it, and `harness logout` mentions the grid credential store without touching it.*/import { spawn } from 'child_process'import { createServer, type Server } from 'http'-import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs'+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs'import { tmpdir } from 'os'import { delimiter, join } from 'path'import { fileURLToPath } from 'url'@@ -33,12 +38,13 @@ const FAKE_GRID = `#!/usr/bin/env node'use strict'const { writeFileSync } = require('fs')const args = process.argv.slice(2)-let stdin = ''-process.stdin.setEncoding('utf8')-process.stdin.on('data', (chunk) => { stdin += chunk })-process.stdin.on('end', () => {++function answer(stdin) {writeFileSync(process.env.FAKE_GRID_RECORD, JSON.stringify({ args, stdin, env: process.env }))- if (!args.includes('--harness')) {+ // The guard is scoped to the verb it belongs to. Only the LOGIN hand-off must ask for+ // \`--harness\`; \`grid logout\` has no such flag, and refusing it here would make the passthrough+ // untestable against the same fake.+ if (args[0] === 'login' && !args.includes('--harness')) {process.stderr.write('fake grid: refusing argv that does not ask for the hand-off\\n')process.exitCode = 64return@@ -47,7 +53,19 @@ process.stdin.on('end', () => {// Where the real \`grid\` puts every refusal — see the test that reads it back off the result line.if (process.env.FAKE_GRID_STDERR) process.stderr.write(process.env.FAKE_GRID_STDERR)process.exitCode = Number(process.env.FAKE_GRID_EXIT || '0')-})+}++// Standard input is read on the hand-off and NOWHERE else. The logout passthrough inherits stdin+// from the harness, whose own caller may never close it — so a fake that waited for end-of-file on+// every argv would hang the pair instead of measuring it.+if (args[0] === 'login') {+ let stdin = ''+ process.stdin.setEncoding('utf8')+ process.stdin.on('data', (chunk) => { stdin += chunk })+ process.stdin.on('end', () => answer(stdin))+} else {+ answer('')+}`function tempRoot(): string {@@ -121,7 +139,12 @@ function envFor(root: string, backendUrl?: string, extra: NodeJS.ProcessEnv = {}type Run = { status: number | null; stdout: string; stderr: string }/** Async spawn — REQUIRED whenever the child talks to a fake backend hosted in THIS process, which- * spawnSync would block the event loop of until the child exits, deadlocking both. */+ * spawnSync would block the event loop of until the child exits, deadlocking both.+ *+ * ⚠️ Resolves on **`close`**, never `exit`. `exit` fires while the child's stdio may still hold+ * unemitted data, so a terminating NDJSON line written just before the process ends can be missing+ * from `stdout` — and the cases below compare it for EQUALITY. A regression that DROPPED that line+ * would produce the same shorter stdout, so the flake would make the real failure look like noise. */function run(root: string, args: string[], backendUrl?: string, extra: NodeJS.ProcessEnv = {}, grid: GridOnPath = 'runnable'): Promise<Run> {return new Promise((resolve) => {const child = spawn(process.execPath, [TSX, CLI_SOURCE, ...args], {@@ -132,7 +155,7 @@ function run(root: string, args: string[], backendUrl?: string, extra: NodeJS.Prlet stderr = ''child.stdout.on('data', (c: Buffer) => { stdout += c.toString() })child.stderr.on('data', (c: Buffer) => { stderr += c.toString() })- child.once('exit', (status) => resolve({ status, stdout, stderr }))+ child.once('close', (status) => resolve({ status, stdout, stderr }))})}@@ -298,7 +321,8 @@ describe('harness grid login — a signed-out computer', () => {// Simulate the browser completing SSO against this CLI's own loopback callback server.await fetch(`${capturedRedirectUri}?code=code_123&state=state_456`)- const status = await new Promise<number | null>((resolve) => child.once('exit', resolve))+ // `close`, not `exit`: on `exit` the child's stdout may still hold the terminating result line.+ const status = await new Promise<number | null>((resolve) => child.once('close', resolve))if (stdout.trim()) lines.push(JSON.parse(stdout.trim()))expect(status).toBe(0)// Two lines total: the sign-in's authorize_url, and ONE terminating result — not one per half.@@ -528,3 +552,247 @@ describe('the harness grid namespace', () => {expect(result.stderr).toContain('Unknown command: grid nonsense')}, 20_000)})++// ── signing out ────────────────────────────────────────────────────────────────────────────────+//+// Two verbs, and the tests below are mostly about the wall between them: `harness grid logout` runs+// the grid sign-out and nothing of the harness's, and `harness logout` mentions the grid credential+// store without reading a byte of it or deleting it.++/** The grid credential store, as `grid` itself lays it out: `<GRID_HOME>/credentials.toml`. */+function seedGridCredentials(dir: string): string {+ mkdirSync(dir, { recursive: true })+ const file = join(dir, 'credentials.toml')+ writeFileSync(file, 'session_token = "grid_seeded"\n')+ return file+}++/** `harness logout`, with GRID_HOME under this test's control rather than the developer's shell.+ *+ * A stray `GRID_HOME` in the ambient environment would point the check at a directory this test+ * never wrote, and the SILENT case would then pass for entirely the wrong reason. Passing+ * `undefined` drops the variable from the child's environment altogether, which is the state the+ * `~/.grid` default is for. */+function runLogout(root: string, gridHome?: string): Promise<Run> {+ return run(root, ['logout'], 'http://127.0.0.1:1', { GRID_HOME: gridHome })+}++describe('harness grid logout', () => {+ it('runs the grid sign-out and answers with the child\'s own exit code', async () => {+ const root = tempRoot()+ seedSession(root)++ // Port 1 for the backend: nothing on this path may reach it. The grid sign-out is the grid's+ // business, and a harness session this command never reads is one it can never be blocked by.+ const result = await run(root, ['grid', 'logout'], 'http://127.0.0.1:1',+ { FAKE_GRID_STDOUT: 'Signed out. Removed credentials for 2 grids.\n' })++ expect(result.status).toBe(0)+ expect(result.stdout).toContain('Removed credentials for 2 grids.')+ expect(readRecord(root).args).toEqual(['logout'])+ }, 20_000)++ it('carries a refusal out as a non-zero exit, in the child\'s own words', async () => {+ const root = tempRoot()+ seedSession(root)+ // The shape `grid logout` refuses in: it will not delete credentials it may still need to+ // deregister a serve child with, and it says so on stderr.+ const refusal = 'dt-edge: still serving on pid 4242. Stop it, or sign out with --force.\n'++ const result = await run(root, ['grid', 'logout'], 'http://127.0.0.1:1',+ { FAKE_GRID_EXIT: '1', FAKE_GRID_STDERR: refusal })++ expect(result.status).toBe(1)+ expect(result.stderr).toContain('still serving on pid 4242')+ }, 20_000)++ it('lets --force reach the child, so the override a person already knows still works', async () => {+ const root = tempRoot()+ seedSession(root)++ const result = await run(root, ['grid', 'logout', '--force'], 'http://127.0.0.1:1')++ expect(result.status).toBe(0)+ expect(readRecord(root).args).toEqual(['logout', '--force'])+ }, 20_000)++ it('passes --json through and hands back the child\'s answer unwrapped', async () => {+ const root = tempRoot()+ seedSession(root)++ const result = await run(root, ['grid', 'logout', '--json'], 'http://127.0.0.1:1',+ { FAKE_GRID_STDOUT: '{"signed_out":true,"grids":2}\n' })++ expect(result.status).toBe(0)+ expect(readRecord(root).args).toEqual(['logout', '--json'])+ // ⚠️ EXACTLY the child's document, with no harness envelope around it and no result line after+ // it. `harness grid login --json` has two halves to reconcile and therefore emits its own+ // terminating line; this command has ONE, so anything it added would be a second dialect of an+ // answer `grid logout` already gives.+ expect(result.stdout.trim()).toBe('{"signed_out":true,"grids":2}')+ }, 20_000)++ it('never signs the harness out, not even when the grid sign-out refuses', async () => {+ const root = tempRoot()+ seedSession(root)+ const session = join(root, 'auth', 'session.json')+ const before = readFileSync(session, 'utf8')++ const result = await run(root, ['grid', 'logout'], 'http://127.0.0.1:1', { FAKE_GRID_EXIT: '1' })++ expect(result.status).toBe(1)+ // No cascade in this direction either: a grid condition decides the exit code and nothing else.+ expect(existsSync(session)).toBe(true)+ expect(readFileSync(session, 'utf8')).toBe(before)+ }, 20_000)++ it('says there is no grid CLI rather than crashing on the spawn', async () => {+ const root = tempRoot()+ seedSession(root)++ const result = await run(root, ['grid', 'logout'], 'http://127.0.0.1:1', {}, 'absent')++ expect(result.status).toBe(1)+ // Named as the missing thing it is. `toContain('grid')` would be satisfied by the dispatcher's+ // own "Unknown command: grid logout", which is what this said before the command existed.+ expect(result.stderr).toContain('PATH')+ expect(result.stderr).not.toContain('Unknown command')+ expect(result.stderr).not.toContain('Failed to start adapter')+ }, 20_000)++ it('drops only the verb it consumed, never a later token that spells it', async () => {+ const root = tempRoot()+ seedSession(root)++ // `grid logout` takes no option value TODAY, so this is the passthrough's stated contract rather+ // than a flag that exists: "a flag `grid logout` grows tomorrow works here the day it ships".+ // Filtering the argv by VALUE would forward `--reason` with its value eaten.+ const result = await run(root, ['grid', 'logout', '--reason', 'logout'], 'http://127.0.0.1:1')++ expect(result.status).toBe(0)+ expect(readRecord(root).args).toEqual(['logout', '--reason', 'logout'])+ }, 20_000)++ it('reports a grid it cannot RUN as missing too', async () => {+ const root = tempRoot()+ seedSession(root)++ const result = await run(root, ['grid', 'logout'], 'http://127.0.0.1:1', {}, 'not-executable')++ // This module keeps its OWN copy of the PATH pre-check, so the sibling case in the hand-off+ // suite proves nothing about it. The case above would survive that pre-check being deleted here+ // — an empty PATH answers ENOENT, which the spawn's own fallback maps to the same sentence. A+ // present-but-unrunnable file answers EACCES, which it does not.+ expect(result.status).toBe(1)+ expect(result.stderr).toContain('PATH')+ }, 20_000)+})++describe('harness logout — the grid credential it will not touch', () => {+ it('warns, naming `harness grid logout`, when a grid sign-in is still on this machine', async () => {+ const root = tempRoot()+ seedSession(root)+ seedGridCredentials(join(root, '.grid'))++ const result = await runLogout(root)++ // Local, and unable to fail: the warning is a sentence, never a condition.+ expect(result.status).toBe(0)+ expect(result.stdout).toContain('Signed out.')+ expect(result.stderr).toContain('harness grid logout')+ }, 20_000)++ it('stays silent when there are no grid credentials', async () => {+ const root = tempRoot()+ seedSession(root)++ const result = await runLogout(root)++ expect(result.status).toBe(0)+ expect(result.stdout).toContain('Signed out.')+ expect(result.stderr).not.toContain('grid logout')+ }, 20_000)++ it('never removes the grid credential file', async () => {+ const root = tempRoot()+ seedSession(root)+ const credentials = seedGridCredentials(join(root, '.grid'))+ const before = readFileSync(credentials, 'utf8')++ await runLogout(root)++ // The store may predate the harness entirely — a browser sign-in it knows nothing about — so+ // the warning is the whole of what this command is entitled to do about it.+ expect(existsSync(credentials)).toBe(true)+ expect(readFileSync(credentials, 'utf8')).toBe(before)+ }, 20_000)++ it('looks where GRID_HOME points, the way `grid` itself does', async () => {+ const root = tempRoot()+ seedSession(root)+ const elsewhere = join(root, 'grid-home')+ seedGridCredentials(elsewhere)++ const result = await runLogout(root, elsewhere)++ expect(result.stderr).toContain('harness grid logout')+ }, 20_000)++ it('expands a leading ~ in GRID_HOME, because `grid` does', async () => {+ const root = tempRoot()+ seedSession(root)+ seedGridCredentials(join(root, 'grid-state'))++ // A shell expands `~` at assignment; a systemd unit, a Docker ENV or a .env file does not. There+ // `grid`'s own `expanduser()` still resolves it, so a literal value taken verbatim here would+ // look for a directory named `~` and go silent about a credential that is definitely present.+ const result = await runLogout(root, '~/grid-state')++ expect(result.stderr).toContain('harness grid logout')+ }, 20_000)++ it('does not warn about a store GRID_HOME points away from', async () => {+ const root = tempRoot()+ seedSession(root)+ // Credentials at the DEFAULT location, and a GRID_HOME aimed at an empty directory. Without the+ // override being read, the check would find the default store and warn — so this is the negative+ // control that makes the case above mean "it read GRID_HOME" rather than "it found something".+ seedGridCredentials(join(root, '.grid'))+ const empty = join(root, 'grid-home-empty')+ mkdirSync(empty, { recursive: true })++ const result = await runLogout(root, empty)++ expect(result.status).toBe(0)+ expect(result.stderr).not.toContain('grid logout')+ }, 20_000)+})++describe('harness reset — the second door onto the same sign-out', () => {+ it('warns about a grid sign-in too, and leaves it alone', async () => {+ const root = tempRoot()+ seedSession(root)+ const credentials = seedGridCredentials(join(root, '.grid'))+ const before = readFileSync(credentials, 'utf8')++ // `reset` clears the SSO session exactly as `logout` does, and more besides — so somebody who+ // runs it is if anything likelier to believe nothing is left behind. A warning written at one+ // door and not the other is a warning the other silently does without.+ const result = await run(root, ['reset'], 'http://127.0.0.1:1', { GRID_HOME: undefined })++ expect(result.status).toBe(0)+ expect(result.stderr).toContain('harness grid logout')+ expect(existsSync(credentials)).toBe(true)+ expect(readFileSync(credentials, 'utf8')).toBe(before)+ }, 20_000)++ it('stays silent when there is no grid sign-in', async () => {+ const root = tempRoot()+ seedSession(root)++ const result = await run(root, ['reset'], 'http://127.0.0.1:1', { GRID_HOME: undefined })++ expect(result.status).toBe(0)+ expect(result.stderr).not.toContain('grid logout')+ }, 20_000)+})diff --git a/cli/src/lib/gridCredentials.ts b/cli/src/lib/gridCredentials.tsnew file mode 100644index 000000000..94817a2f0--- /dev/null+++ b/cli/src/lib/gridCredentials.ts@@ -0,0 +1,91 @@+/**+ * Where the `grid` CLI keeps this machine's grid sign-in — located, and nothing more.+ *+ * `harness logout` detaches the harness and only the harness, so the one thing it owes a person is+ * a sentence about the credential it is leaving behind. That sentence needs no more than the+ * existence of the file: nothing here opens it, parses it, writes to it, or removes it.+ *+ * **No marker is written into the store.** A key recording *how* the sign-in happened was considered+ * and dropped — its only remaining purpose was redirecting an expiry message, and a year-long+ * session removed the need (PRD `harness-grid-login`, Implementation Decision 8).+ *+ * ⚠️ **The layout below is hand-duplicated from autonomous-grid's `shared/paths.py`** — there is no+ * import path between the two repositories. It drifts SILENTLY: move the store there and this check+ * finds nothing, which is spelled exactly like a machine that was never signed in, so `harness+ * logout` would stop warning and no test in either repository would notice. autonomous-grid's+ * `tests/test_harness_login_lockstep.py` pins these three literals against its own for that reason.+ */+import { existsSync, writeSync } from 'node:fs'+import { homedir } from 'node:os'+import { join } from 'node:path'++/** The environment variable that relocates the whole of `grid`'s state. */+export const GRID_HOME_ENV = 'GRID_HOME'+/** What `grid` falls back to, under the user's home directory. */+export const GRID_HOME_DEFAULT = '.grid'+/** The store itself. Present ⇒ signed in; absent ⇒ signed out. */+export const GRID_CREDENTIALS_FILE = 'credentials.toml'++/**+ * The credential store's path, honouring `GRID_HOME` the way `grid` does.+ *+ * ⚠️ **Set-but-empty is not the same as unset**, and the fallback keys on the key being ABSENT for+ * that reason. `grid` reads `os.getenv("GRID_HOME", "~/.grid")`, which hands an empty value straight+ * through to a relative path — a pathological configuration, but one where guessing `~/.grid`+ * instead would put this check somewhere `grid` is demonstrably not looking.+ *+ * The value is otherwise taken verbatim. `grid` runs `expanduser()` over it as well, which matters+ * only for a literal leading `~` — and a shell has already expanded that at the point of assignment,+ * so the two agree on every path either of them can actually be given.+ */+export function gridCredentialsPath(env: NodeJS.ProcessEnv = process.env): string {+ const configured = env[GRID_HOME_ENV]+ const home = configured === undefined ? join(homedir(), GRID_HOME_DEFAULT) : expandLeadingTilde(configured)+ return join(home, GRID_CREDENTIALS_FILE)+}++/** `~` and `~/…` resolved against this user's home, because `grid` runs `expanduser()` over the same+ * value and the two must not disagree about where the file is.+ *+ * ⚠️ A shell expands `~` at the point of assignment, so this only matters where nothing does:+ * a systemd unit, a Docker `ENV`, a `.env` file, a CI variable. There the two would otherwise land+ * in different places — `grid` writes to `$HOME/…` and this looks for a directory literally named+ * `~` — and the miss reads exactly like a machine that was never signed in.+ *+ * `~otheruser` is NOT resolved (`expanduser` does; there is no equivalent in Node without reading+ * the password database) and neither is a Windows `~\`. Both are documented gaps rather than+ * silent ones: nothing in this stack has been seen to use either. */+function expandLeadingTilde(value: string): string {+ if (value === '~') return homedir()+ return value.startsWith('~/') ? join(homedir(), value.slice(2)) : value+}++/** Is there a grid sign-in on this machine?+ *+ * `existsSync` answers `false` for a path it cannot even stat rather than raising, and that is the+ * property this needs rather than a happy accident: the caller is a sign-out that is local and must+ * not be able to fail — least of all over a cosmetic warning. */+export function gridCredentialsExist(env: NodeJS.ProcessEnv = process.env): boolean {+ return existsSync(gridCredentialsPath(env))+}++/**+ * Say — once, on standard error — that a grid sign-in is still on this machine, if one is.+ *+ * Both harness sign-outs call this, and that is the point rather than tidiness. `harness logout` and+ * `harness reset` are two doors onto the same act (`clearAuthSession`), and a warning written at one+ * of them is a warning the other silently does without. One function, so they cannot drift.+ *+ * ⚠️ **`writeSync`, not `console.error`.** Both callers finish with `process.exit(0)`, and stderr to+ * a **pipe is asynchronous on macOS** — which `process.exit` does not flush. The one line this owes a+ * person could therefore be dropped exactly when it is being captured by a script or a CI job, and a+ * dropped line is spelled identically to "there were no grid credentials". The `catch` is not a+ * swallowed error: it is the case where stderr itself is gone, and a sign-out must not fail over its+ * own caveat.+ */+export function warnIfGridSignInRemains(env: NodeJS.ProcessEnv = process.env): void {+ if (!gridCredentialsExist(env)) return+ try {+ writeSync(2, 'Your grid sign-in is still on this machine — run `harness grid logout` to end that too.\n')+ } catch { /* no stderr to say it on; the sign-out itself still stands */ }+}diff --git a/cli/src/lib/gridLogout.ts b/cli/src/lib/gridLogout.tsnew file mode 100644index 000000000..bfae698ba--- /dev/null+++ b/cli/src/lib/gridLogout.ts@@ -0,0 +1,72 @@+/**+ * Run `grid logout` as itself, and get out of the way.+ *+ * The grid sign-out is not a credential delete: it tears every serve child on this box down FIRST,+ * while the token that makes their deregistration authoritative still exists, and it refuses — keeping+ * the credentials — when a child cannot be confirmed stopped. `--force` walks away from that refusal.+ * All of it already exists, it has been got wrong once, and a second dialect of it here would be the+ * kind that drifts. So this module reproduces none of it: it spawns the child, inherits all three+ * streams, and hands back the child's exit code.+ *+ * ⚠️ **Nothing is wrapped, under `--json` or otherwise.** `harness grid login` has two halves to+ * reconcile and emits its own terminating result line; this command has ONE, so its standard output+ * is `grid logout`'s document verbatim and its standard error is `grid logout`'s sentence verbatim.+ * An envelope added here would be a second answer to a question the child has already answered.+ *+ * The one thing this module is entitled to say is that there was no child to run at all.+ */+import { spawn } from 'node:child_process'+import { binaryOnPath } from './binaryOnPath.js'+import { GRID_BINARY } from './gridHandoff.js'++/** The verb, on the same binary the hand-off spawns. Deliberately NOT a cross-repo pin: rename it in+ * autonomous-grid and argparse refuses it loudly, in the child's own words, on the child's own+ * stderr — there is no silent direction to guard. */+const GRID_LOGOUT_VERB = 'logout'++const MISSING_MESSAGE =+ `No \`${GRID_BINARY}\` on PATH, so there is no grid sign-in here for this to end. If your grid CLI `+ + 'is installed somewhere else, run `grid logout` there.'++/**+ * A child ran and its exit code is the answer, or none did and this carries the sentence.+ *+ * ⚠️ `ran` is read on the FIELD. Both shapes are truthy objects, so a caller testing the outcome+ * itself would take a missing `grid` for a clean sign-out.+ */+export type GridLogoutOutcome =+ | { ran: true; exitCode: number }+ | { ran: false; exitCode: number; message: string }++const missing = (): GridLogoutOutcome => ({ ran: false, exitCode: 1, message: MISSING_MESSAGE })++/**+ * Spawn `grid logout`, forwarding `args` untouched, and resolve with what it did.+ *+ * `args` is whatever followed `harness grid logout`, passed through rather than allow-listed: a flag+ * `grid logout` grows tomorrow works here the day it ships, and this file never becomes a second+ * place that has to know what the sign-out accepts.+ */+export async function passThroughToGridLogout(args: string[]): Promise<GridLogoutOutcome> {+ // Asking PATH rather than spawning to find out, exactly as the hand-off does: an absent `grid` is+ // a sentence, not a spawn error every caller would have to recognise. It also catches the case a+ // spawn cannot — a `grid` that is present but not executable answers EACCES, never ENOENT.+ if (!binaryOnPath(GRID_BINARY)) return missing()+ return await new Promise<GridLogoutOutcome>((resolve) => {+ // All three streams inherited: the child talks to the terminal directly, which is what makes+ // this a passthrough rather than a re-narration of one.+ const child = spawn(GRID_BINARY, [GRID_LOGOUT_VERB, ...args], { stdio: 'inherit' })+ let settled = false+ const settle = (outcome: GridLogoutOutcome): void => { if (!settled) { settled = true; resolve(outcome) } }++ // Between the PATH check and the spawn the binary can still be gone.+ child.once('error', (err: NodeJS.ErrnoException) => settle(err.code === 'ENOENT'+ ? missing()+ : { ran: false, exitCode: 1, message: `Could not run \`${GRID_BINARY}\`: ${err.message}` }))++ // A child killed by a signal has no status. It reports as an ordinary non-zero exit, because+ // that is what a shell would see and because the signal reached this process too — the person+ // who sent it needs no sentence from here.+ child.once('close', (status) => settle({ ran: true, exitCode: status ?? 1 }))+ })+}