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
A computer signed in by QR hands its sign-in to grid (hold until the Grid PROD cut-over) (#979)
Kelvind93f3209022e
diff --git a/SECURITY.md b/SECURITY.mdindex aeeeba1ab..94411323b 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -37,7 +37,9 @@ stranger approving yours with their phone (a QR they photographed). The phone shwhere from, and whether it is on the phone's network — another network takes a two-second hold, not atap — and the computer asks its own person whose account approved it before any session exists.A computer signed in this way can add a phone of its own; that chain is intended. Its session is-Harness's own, so billing and grid still need a Google or Apple sign-in.+Harness's own, so billing still needs a Google or Apple sign-in. Grid does not: the Grid control plane+asks the Harness backend who holds the session (autonomous-grid ADR 0046), so approving a computer+also hands it the account's Grid: its grids and the models on them.## For implementersdiff --git a/cli/src/architecture.spec.ts b/cli/src/architecture.spec.tsindex a40edbcc4..d7e14bd60 100644--- a/cli/src/architecture.spec.ts+++ b/cli/src/architecture.spec.ts@@ -144,7 +144,7 @@ const SERVICE_MAY_IMPORT: Record<string, string> = {/** What is not the core's, by path: each goes to a service or its own process, in the plan's order. */const EDGE: RegExp[] = [/^gateway\//, /^lib\/e2ee\//, /^cable\//, /^device\//, /^lib\/autonomous-device\//, /^sharing\//, /^teams\//, /^orchestrator\//, /^services\//,- /^lib\/grid(Attach|Credentials|Derive|Ensure|Exec|FleetRpc|Handoff|Install|McpUrl|Models|ModelsPayload|Picture|Presence|Reader|Target|Wake)\.ts$/,+ /^lib\/grid(Attach|Credentials|Derive|Ensure|Envelope|Exec|FleetRpc|Handoff|Install|McpUrl|Models|ModelsPayload|Picture|Presence|Reader|Target|Wake)\.ts$/,/^lib\/localModels\.ts$/,// The change-agent handoff reads and redacts history and runs git: the edge host owns that work./^lib\/agentHandoff\.ts$/,diff --git a/cli/src/authCommand.spec.ts b/cli/src/authCommand.spec.tsindex a775dcb75..458e62b38 100644--- a/cli/src/authCommand.spec.ts+++ b/cli/src/authCommand.spec.ts@@ -31,7 +31,7 @@ function tempRoot(): string {return root}-function seedSession(root: string, opts: { expiresInMs?: number } = {}): void {+function seedSession(root: string, opts: { expiresInMs?: number; overrides?: Record<string, unknown> } = {}): void {const authDir = join(root, 'auth')mkdirSync(authDir, { recursive: true })writeFileSync(join(authDir, 'session.json'), JSON.stringify({@@ -43,6 +43,7 @@ function seedSession(root: string, opts: { expiresInMs?: number } = {}): void {computerId: 'a'.repeat(32),machineId: 'm_seeded',updatedAt: Date.now(),+ ...opts.overrides,}))}@@ -232,6 +233,19 @@ describe('harness auth status --json', () => {expect(result.stdout).toContain('Not signed in')})+ it('tells a computer signed in by QR that billing still needs a Google or Apple sign-in, and grid does not', () => {+ // A Harness-issued sign-in now goes to grid like any other (autonomous-grid ADR 0046), so naming+ // grid here would send the person to sign in again for nothing. Billing's Autonomous service+ // still cannot take one.+ const root = tempRoot()+ seedSession(root, { overrides: { accessToken: `hna_${'Q'.repeat(43)}`, method: 'qr' } })+ const result = runSync(root, ['auth', 'status'], 'http://127.0.0.1:1')+ expect(result.status).toBe(0)+ expect(result.stdout).toContain('by your phone')+ expect(result.stdout).toContain('Billing needs a Google or Apple sign-in: harness login --force')+ expect(result.stdout).not.toMatch(/grid/i)+ })+it('reports loggedIn:true from a saved, non-expiring session without a network round trip', () => {const root = tempRoot()seedSession(root)diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 893255bf1..ee48db047 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -325,9 +325,11 @@ async function authStatusCommand(json: boolean): Promise<void> {if (json) console.log(JSON.stringify(payload))else {console.log(`\n ${payload.loggedIn ? '✓ Signed in' : '✗ Not signed in'}${payload.machineId ? ` (machine ${payload.machineId})` : ''}${payload.loggedIn && payload.method === 'qr' ? ' — by your phone' : ''}\n`)- // A session a phone approved is Harness's own: the Autonomous services behind billing and grid- // do not take it. Say so where the person looks, not only when one of them refuses.- if (payload.loggedIn && payload.method === 'qr') console.log(' Billing and grid need a Google or Apple sign-in: harness login --force\n')+ // A session a phone approved is Harness's own, and billing's Autonomous service does not take it.+ // Say so where the person looks, not only when billing refuses. Grid is not named: it learns who+ // holds a Harness-issued sign-in from the Harness backend (autonomous-grid ADR 0046), and naming+ // it sent people to sign in again with Google or Apple for nothing.+ if (payload.loggedIn && payload.method === 'qr') console.log(' Billing needs a Google or Apple sign-in: harness login --force\n')}}@@ -806,13 +808,15 @@ async function gridLoginCommand(force: boolean, json: boolean): Promise<void> {}))}-/** What `grid` itself said, carried out on the result line beside this command's own classification.+/** What `grid` itself said, carried out on the result line beside `message` — which is already `grid`'s+ * own sentence when it refused with its `--json` envelope (`lib/gridHandoff.ts`), else the hand-off's.** `grid`'s answer on success is a JSON document on stdout, so it travels parsed, under `grid`. Its* refusals go to **stderr** — every one of them already names its own way forward — and those- * travel verbatim under `detail`, because a client reading NDJSON off stdout would otherwise have- * the exit code and no sentence to show anybody. Both are omitted when empty rather than sent as- * `null`: an absent key reads as "the child said nothing there", which is what it means. */+ * travel verbatim under `detail` (the envelope line included), because a client reading NDJSON off+ * stdout would otherwise have the exit code and no sentence to show anybody. Both are omitted when+ * empty rather than sent as `null`: an absent key reads as "the child said nothing there", which is+ * what it means. */function gridSaid(handoff: { stdout: string; stderr: string }): Record<string, unknown> {const out = handoff.stdout.trim()const err = handoff.stderr.trim()diff --git a/cli/src/gridCommand.spec.ts b/cli/src/gridCommand.spec.tsindex 2a6c2af37..59e8f3058 100644--- a/cli/src/gridCommand.spec.ts+++ b/cli/src/gridCommand.spec.ts@@ -50,6 +50,11 @@ function answer(stdin) {return}if (process.env.FAKE_GRID_STDOUT) process.stdout.write(process.env.FAKE_GRID_STDOUT)+ // The refusal envelope the real \`grid\` writes under \`--json\` only (\`cli/json_error.py\`), one+ // line, BEFORE the interpreter prints the same sentence in plain text on its way out.+ if (process.env.FAKE_GRID_ENVELOPE && args.includes('--json')) {+ process.stderr.write(JSON.stringify({ error: { code: null, message: process.env.FAKE_GRID_ENVELOPE, status: 409 } }) + '\\n')+ }// 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')@@ -343,6 +348,50 @@ describe('harness grid login — an already-signed-in computer', () => {}, 20_000)})+/**+ * A computer signed in by QR holds a Harness-issued sign-in (`method: 'qr'`, a token starting+ * `hna_`). The hand-off used to refuse it before `grid` was asked; the control plane now learns who+ * holds one from the Harness backend (autonomous-grid ADR 0046), so it goes to `grid` like any other+ * sign-in and whatever `grid` answers is the answer.+ */+describe('harness grid login — a computer signed in by QR', () => {+ const HARNESS_ISSUED = `hna_${'Q'.repeat(43)}`+ const seedQrSession = (root: string): void => seedSession(root, { accessToken: HARNESS_ISSUED, method: 'qr' })++ it('hands its Harness-issued sign-in to grid on standard input, as it does an Autonomous token', async () => {+ const root = tempRoot()+ seedQrSession(root)+ const { base } = await signedInBackend()++ const result = await run(root, ['grid', 'login', '--json'], base)++ expect(result.status).toBe(0)+ expect(ndjson(result.stdout)).toEqual([{ type: 'result', status: 'success', alreadySignedIn: true }])+ const record = readRecord(root)+ expect(record.args).toEqual(['login', '--harness', '--json'])+ expect(record.stdin).toBe(`${HARNESS_ISSUED}\n`)+ }, 20_000)++ it('reports grid\'s own refusal as grid\'s, after grid was handed the token', async () => {+ const root = tempRoot()+ seedQrSession(root)+ const { base } = await signedInBackend()+ // What the control plane says while the Harness backend has not yet learned the account's Google+ // identity (ADR 0046): the refusal that matters for this sign-in, and `grid`'s to word.+ const refusal = 'Harness hasn\'t confirmed this account\'s Google identity yet, so nothing was changed.\n'++ // 7, not 1: the hand-off's own fallback is 1, so only another code proves grid's is the one carried.+ const result = await run(root, ['grid', 'login', '--json'], base,+ { FAKE_GRID_EXIT: '7', FAKE_GRID_STDERR: refusal })++ expect(result.status).toBe(7)+ const [line] = ndjson(result.stdout)+ expect(line).toMatchObject({ type: 'result', status: 'error', code: 'GRID_LOGIN_FAILED', detail: refusal.trim() })+ expect(String(line.message)).not.toContain('harness login --force')+ expect(readRecord(root).stdin).toBe(`${HARNESS_ISSUED}\n`)+ }, 20_000)+})+describe('harness grid login — a signed-out computer', () => {it('runs the whole loopback sign-in first, then hands the new token over', async () => {const root = tempRoot()@@ -449,6 +498,42 @@ describe('harness grid login — when the hand-off fails', () => {expect(result.stderr).toContain('cannot sign you in')}, 20_000)+ describe('a refusal grid words itself', () => {+ // What the control plane says while Harness has not yet learned the account's Google identity+ // (ADR 0046): a sentence that names its own way forward, and so the one thing worth showing.+ const sentence = 'Harness hasn\'t confirmed this account\'s Google identity yet, so nothing was changed. '+ + 'Sign in to Harness once with Google, Apple or your email on any device, then try again.'++ it('puts grid\'s sentence in the message, and still carries what grid wrote verbatim', async () => {+ const root = tempRoot()+ seedSession(root)+ const { base } = await signedInBackend()++ const result = await run(root, ['grid', 'login', '--json'], base,+ { FAKE_GRID_EXIT: '1', FAKE_GRID_ENVELOPE: sentence, FAKE_GRID_STDERR: `${sentence}\n` })++ expect(result.status).toBe(1)+ const [line] = ndjson(result.stdout)+ expect(line).toMatchObject({ type: 'result', status: 'error', code: 'GRID_LOGIN_FAILED', message: sentence })+ // `detail` is the transcript, untouched: the envelope line and the plain sentence, as written.+ expect(String(line.detail).startsWith('{"error":')).toBe(true)+ expect(String(line.detail).endsWith(sentence)).toBe(true)+ }, 20_000)++ it('says it once on the human path, where grid speaks to the terminal itself', async () => {+ const root = tempRoot()+ seedSession(root)+ const { base } = await signedInBackend()++ const result = await run(root, ['grid', 'login'], base,+ { FAKE_GRID_EXIT: '1', FAKE_GRID_ENVELOPE: sentence, FAKE_GRID_STDERR: `${sentence}\n` })++ expect(result.status).toBe(1)+ expect(result.stderr.split(sentence)).toHaveLength(2)+ expect(result.stderr).toContain('`grid login --harness` exited 1.')+ }, 20_000)+ })+it('says nothing where the child said nothing, rather than sending empty keys', async () => {const root = tempRoot()seedSession(root)diff --git a/cli/src/lib/authSession.ts b/cli/src/lib/authSession.tsindex b5ff47893..6f6a24385 100644--- a/cli/src/lib/authSession.ts+++ b/cli/src/lib/authSession.ts@@ -11,8 +11,9 @@ export interface AuthSession {autonomousEnv: 'prod' | 'stag'computerId: stringmachineId?: string- /** How this computer signed in: `qr` — a phone scanned its QR (a Harness-issued session, which- * the Autonomous services behind billing and grid do not take); absent or `sso` — the browser. */+ /** How this computer signed in: `qr` — a phone scanned its QR (a Harness-issued sign-in, which+ * billing's Autonomous service does not take; grid does, through the Harness backend —+ * autonomous-grid ADR 0046); absent or `sso` — the browser. */method?: 'sso' | 'qr'/** The auth-service client these tokens were issued to, as the backend's exchange reported it.* A refresh has to name the same one. Absent is the backend's configured client. */diff --git a/cli/src/lib/gridAttach.spec.ts b/cli/src/lib/gridAttach.spec.tsindex 71a303d7a..e4e4af21b 100644--- a/cli/src/lib/gridAttach.spec.ts+++ b/cli/src/lib/gridAttach.spec.ts@@ -1,6 +1,9 @@-import { describe, expect, it, vi } from 'vitest'+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterEach, describe, expect, it, vi } from 'vitest'import { reconcileGridAttach, createGridAccess, type GridAttachDeps, type GridAttachResult } from './gridAttach.js'-import type { GridHandoffResult } from './gridHandoff.js'+import { handOffToGrid, type GridHandoffResult } from './gridHandoff.js'import type { EnsureResult } from './gridEnsure.js'const NAME = 'someone-7f3a91c4'@@ -193,6 +196,39 @@ describe('reconcileGridAttach — bringing grid into line for a grid feature', (})})+/**+ * The hand-off as the models picker's Set up runs it (`services/models.ts`): the real+ * `handOffToGrid` in json mode against a `grid` that refuses. `detail` is all the picker shows, so a+ * refusal that names its own way forward must arrive there in `grid`'s words.+ */+describe('reconcileGridAttach — a hand-off grid refuses', () => {+ const savedBin = process.env.HARNESS_GRID_BIN+ const dirs: string[] = []+ afterEach(() => {+ if (savedBin === undefined) delete process.env.HARNESS_GRID_BIN+ else process.env.HARNESS_GRID_BIN = savedBin+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })+ })++ it('carries grid\'s own sentence as the detail', async () => {+ const sentence = 'POST https://cp.example.test/v1/grid/auth/harness failed (401): {"detail":"This Harness '+ + 'sign-in has lapsed. Run `harness login` again."}'+ const dir = mkdtempSync(join(tmpdir(), 'grid-attach-'))+ dirs.push(dir)+ writeFileSync(join(dir, 'stderr.txt'), `${JSON.stringify({ error: { code: null, message: sentence, status: 401 } })}\n${sentence}\n`)+ const bin = join(dir, 'grid')+ writeFileSync(bin, ['#!/bin/sh', '/bin/cat > /dev/null', `/bin/cat "${join(dir, 'stderr.txt')}" >&2`, 'exit 1', ''].join('\n'), { mode: 0o755 })+ process.env.HARNESS_GRID_BIN = bin++ const r = await reconcileGridAttach(deps({+ signedInEmail: () => null,+ handoff: vi.fn((token: string) => handOffToGrid(token, { json: true })),+ }))++ expect(r).toMatchObject({ status: 'handoff-failed', name: NAME, detail: sentence })+ })+})+/*** The coordination half: when a reconcile runs — on demand, one at a time, never twice for what is* already done, and never as a remembered failure.diff --git a/cli/src/lib/gridEnvelope.ts b/cli/src/lib/gridEnvelope.tsnew file mode 100644index 000000000..972960cf4--- /dev/null+++ b/cli/src/lib/gridEnvelope.ts@@ -0,0 +1,33 @@+/**+ * The refusal envelope `grid --json` writes on stderr beside its plain sentence, one JSON line:+ * `{"error": {"code", "message", "status"}}` (autonomous-grid `cli/json_error.py`). Grid reads compare+ * its `code` (`gridReader.ts`); the sign-in hand-off shows its `message` (`gridHandoff.ts`). ⚠️ That+ * message is a subprocess's text on a person's screen, so control characters become spaces and it is+ * bounded; the `code` is compared, never shown, and is left exactly as sent.+ */+export interface GridEnvelope { code: string | null; message: string | null }++/** Fits `grid`'s rendering of a control-plane refusal (request line ~70 + ≤400 chars of reply). */+const MAX_MESSAGE_CHARS = 600+const CONTROL_CHARS = /[\p{Cc}\p{Cf}]+/gu // C0 (newline, tab), DEL, C1 (CSI), and invisible/bidi format++const isObject = (value: unknown): value is Record<string, unknown> => !!value && typeof value === 'object' && !Array.isArray(value)++function displayable(value: unknown): string | null {+ if (typeof value !== 'string') return null+ // By code point, so a cut never leaves half a surrogate pair.+ const chars = Array.from(value.replace(CONTROL_CHARS, ' ').replace(/\s+/g, ' ').trim())+ if (!chars.length) return null+ return chars.length > MAX_MESSAGE_CHARS ? `${chars.slice(0, MAX_MESSAGE_CHARS - 1).join('')}…` : chars.join('')+}++/** Every envelope on `stderr`, in the order written. Any other line — the plain sentence, a warning — is+ * skipped: the envelope is an addition to a shared stream, never the whole of it. */+export function gridEnvelopes(stderr: string): GridEnvelope[] {+ return stderr.split('\n').flatMap((line) => {+ let parsed: unknown+ try { parsed = line.trim().startsWith('{') ? JSON.parse(line.trim()) : null } catch { return [] }+ const error = isObject(parsed) && isObject(parsed.error) ? parsed.error : null+ return error ? [{ code: typeof error.code === 'string' ? error.code : null, message: displayable(error.message) }] : []+ })+}diff --git a/cli/src/lib/gridHandoff.spec.ts b/cli/src/lib/gridHandoff.spec.tsindex ee207ca0f..f610db1ba 100644--- a/cli/src/lib/gridHandoff.spec.ts+++ b/cli/src/lib/gridHandoff.spec.ts@@ -5,7 +5,8 @@* resolves to (`gridExec.ts`): the developer override, then the managed runtime, then PATH. A* hand-off that asked PATH on its own would sign in with one `grid` while models ran on another —* two versions writing one `~/.grid`. The token seam itself (stdin, never argv) is covered end to end- * in `gridCommand.spec.ts`; this file is only about WHICH child gets it.+ * in `gridCommand.spec.ts`; this file is about WHICH child gets it, and that every kind of sign-in+ * reaches it.*/import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'@@ -82,17 +83,6 @@ describe('handOffToGrid — which grid it runs', () => {expect(updateCheckSeenBy('override')).toBe('1')})- it('does not hand grid a session a phone approved: grid signs in with the Autonomous account', async () => {- const override = fakeGrid(join(root, 'elsewhere'), 'override')- process.env.HARNESS_GRID_BIN = override- const { handOffToGrid } = await load()-- const result = await handOffToGrid('hna_' + 'x'.repeat(43), { json: true })-- expect(result).toMatchObject({ code: 'GRID_NEEDS_SSO', exitCode: 1 })- expect(result.message).toContain('harness login --force')- })-it('prefers the managed runtime over a grid on PATH', async () => {fakeGrid(join(root, 'path-bin'), 'path')process.env.PATH = join(root, 'path-bin')@@ -117,6 +107,127 @@ describe('handOffToGrid — which grid it runs', () => {})})+/**+ * A computer signed in by QR holds a Harness-issued sign-in. The hand-off used to refuse one before+ * `grid` was ever asked, because the control plane could only read Autonomous tokens. It now asks the+ * Harness backend who holds one (autonomous-grid ADR 0046), so accepting or refusing it is `grid`'s+ * answer to give, and this module passes the token on like any other.+ */+describe('handOffToGrid — a Harness-issued sign-in', () => {+ /** The shape the Harness backend issues (`backend/src/lib/harnessTokenFormat.ts`): `hna_` and 43+ * base64url characters. The removed refusal matched on the prefix alone. */+ const HARNESS_ISSUED = `hna_${'Q'.repeat(43)}`++ it('hands it to grid on standard input, exactly as it does an Autonomous token', async () => {+ fakeGrid(join(root, 'path-bin'), 'path')+ process.env.PATH = join(root, 'path-bin')+ const { handOffToGrid } = await load()++ const result = await handOffToGrid(HARNESS_ISSUED, { json: true })++ expect(result).toMatchObject({ code: 'OK', exitCode: 0, message: '' })+ expect(argsOf('path')).toEqual(['login', '--harness', '--json'])+ expect(readFileSync(join(root, 'path.stdin'), 'utf8')).toBe(`${HARNESS_ISSUED}\n`)+ })+})++/**+ * What a refusal says. `grid` refuses on stderr, and under `--json` it writes one JSON line there —+ * `{"error": {"code", "message", "status"}}` (autonomous-grid `cli/json_error.py`) — before the+ * interpreter prints the same sentence in plain text. The daemon's Set up shows this module's+ * `message` and nothing else, so a refusal that names its own way forward has to arrive there, not+ * only on `stderr`.+ */+describe('handOffToGrid — grid\'s own refusal', () => {+ /** What the control plane says while Harness has not yet learned the account's Google identity+ * (ADR 0046), rendered the way `grid` renders every control-plane refusal (`control_plane._raise`). */+ const SENTENCE = 'POST https://cp.example.test/v1/grid/auth/harness failed (409): {"detail":"Harness hasn\'t '+ + 'confirmed this account\'s Google identity yet, so nothing was changed. Sign in to Harness once with '+ + 'Google, Apple or your email on any device, then try again."}'+ const ENVELOPE = JSON.stringify({ error: { code: null, message: SENTENCE, status: 409 } })++ /** A `grid` that reads the token, writes `stderr` and exits `status`. The text goes through a file+ * so no shell quoting stands between the test and the bytes `grid` would write. */+ function refusingGrid(dir: string, stderr: string, status: number): string {+ mkdirSync(dir, { recursive: true })+ const said = join(dir, 'stderr.txt')+ writeFileSync(said, stderr)+ const bin = join(dir, 'grid')+ writeFileSync(bin, ['#!/bin/sh', '/bin/cat > /dev/null', `/bin/cat "${said}" >&2`, `exit ${status}`, ''].join('\n'), { mode: 0o755 })+ return bin+ }++ it('carries the envelope\'s sentence as the message, and leaves stderr as grid wrote it', async () => {+ // The order the real `grid` writes them in: the envelope from `main()`'s handler, then the+ // interpreter's own print of the same `SystemExit` on its way out.+ const stderr = `${ENVELOPE}\n${SENTENCE}\n`+ process.env.HARNESS_GRID_BIN = refusingGrid(join(root, 'refuses'), stderr, 1)+ const { handOffToGrid } = await load()++ const result = await handOffToGrid('tok_refused', { json: true })++ expect(result).toMatchObject({ code: 'GRID_LOGIN_FAILED', exitCode: 1, message: SENTENCE, stderr })+ })++ it('falls back to the exit code when grid wrote no envelope', async () => {+ process.env.HARNESS_GRID_BIN = refusingGrid(join(root, 'plain'), `${SENTENCE}\n`, 1)+ const { handOffToGrid } = await load()++ const result = await handOffToGrid('tok_plain', { json: true })++ expect(result).toMatchObject({ code: 'GRID_LOGIN_FAILED', exitCode: 1, message: '`grid login --harness` exited 1.' })+ })++ it('falls back to the exit code when no envelope carries a sentence', async () => {+ const blank = JSON.stringify({ error: { code: 'some_code', message: ' \n ', status: 400 } })+ const none = JSON.stringify({ error: { code: null, message: null, status: null } })+ process.env.HARNESS_GRID_BIN = refusingGrid(join(root, 'blank'), `{not json\n${blank}\n${none}\n`, 1)+ const { handOffToGrid } = await load()++ const result = await handOffToGrid('tok_blank', { json: true })++ expect(result.message).toBe('`grid login --harness` exited 1.')+ })++ it('reads no envelope without json: grid\'s stderr went to the terminal, uncaptured', async () => {+ process.env.HARNESS_GRID_BIN = refusingGrid(join(root, 'human'), `${ENVELOPE}\n${SENTENCE}\n`, 1)+ const { handOffToGrid } = await load()++ const result = await handOffToGrid('tok_human')++ expect(result).toMatchObject({ code: 'GRID_LOGIN_FAILED', message: '`grid login --harness` exited 1.', stderr: '' })+ })++ it('still calls exit 2 an outdated grid, though argparse\'s refusal comes with an envelope too', async () => {+ // What a `grid` predating `--harness` writes under `--json`: argparse's `SystemExit(2)` carries no+ // sentence, so the envelope's is json_error's generic one — and "too old" is the only useful reading.+ const argparse = JSON.stringify({ error: { code: null, message: 'the command failed with exit status 2', status: null } })+ process.env.HARNESS_GRID_BIN = refusingGrid(join(root, 'old'), `${argparse}\nusage: grid login [-h]\n`, 2)+ const { handOffToGrid } = await load()++ const result = await handOffToGrid('tok_old', { json: true })++ expect(result).toMatchObject({ code: 'GRID_CLI_OUTDATED', exitCode: 2 })+ expect(result.message).toContain('too old')+ })++ it('shows the sentence as one bounded line, whatever bytes the child put in it', async () => {+ // Astral characters past the bound: a cut by UTF-16 unit would leave half a surrogate pair.+ const noisy = `first line\nsecond\tline \u001b[31mred\u001b[0m \u009b2J \u202eagain\u2066\u200b. ${'\u{1F600}'.repeat(700)}`+ const envelope = JSON.stringify({ error: { code: null, message: noisy, status: 500 } })+ process.env.HARNESS_GRID_BIN = refusingGrid(join(root, 'noisy'), `${envelope}\n`, 1)+ const { handOffToGrid } = await load()++ const result = await handOffToGrid('tok_noisy', { json: true })++ expect(result.message.startsWith('first line second line [31mred [0m 2J again . \u{1F600}')).toBe(true)+ expect(result.message).not.toMatch(/[\p{Cc}\p{Cf}]/u)+ expect(result.message).not.toMatch(/\p{Surrogate}/u)+ expect(Array.from(result.message)).toHaveLength(600)+ expect(result.message.endsWith('\u{1F600}…')).toBe(true)+ })+})+/*** The watchdog. `grid login --harness` makes two control-plane round trips, and a connection that is* accepted and then answered by nobody used to leave this promise pending for good — a `harnessdiff --git a/cli/src/lib/gridHandoff.ts b/cli/src/lib/gridHandoff.tsindex 3953d9007..acde17483 100644--- a/cli/src/lib/gridHandoff.ts+++ b/cli/src/lib/gridHandoff.ts@@ -1,5 +1,15 @@/**- * Hand an Autonomous account token to the `grid` CLI, so signing in to a grid needs no second browser.+ * Hand this computer's Harness access token to the `grid` CLI, so signing in to a grid needs no+ * second browser.+ *+ * **Every kind of sign-in goes to `grid`, and `grid` alone says no.** A browser sign-in holds an+ * Autonomous token; a computer signed in by QR holds a Harness-issued sign-in, whose token starts+ * `hna_`. This module used to refuse the second before `grid` was asked, because the control plane+ * could only read Autonomous tokens and a QR-signed computer was told to sign in again with Google or+ * Apple. The control plane now asks the Harness backend who holds either kind (autonomous-grid ADR+ * 0046), and a sign-in it cannot take — one that has lapsed, or an account whose Google identity+ * Harness has not yet learned — comes back as `grid`'s own refusal, which names its own way forward.+ * A check here would only be a second copy of that rule to fall out of step with it.** The seam is a child process and nothing else: `grid login --harness` reads the token off its own* standard input, exchanges it at the control plane, and owns everything after that. This module's@@ -13,6 +23,7 @@*/import { spawn } from 'node:child_process'import { binaryOnPath } from './binaryOnPath.js'+import { gridEnvelopes } from './gridEnvelope.js'import { gridBinaryPath, gridChildEnv } from './gridExec.js'/** The flag on `grid login` that means "read the token off stdin" (autonomous-grid's `cli/parser.py`).@@ -29,13 +40,14 @@ export const GRID_HANDOFF_FLAG = '--harness'*/const ARGPARSE_USAGE_EXIT = 2-export type GridHandoffCode = 'OK' | 'GRID_CLI_MISSING' | 'GRID_CLI_OUTDATED' | 'GRID_LOGIN_FAILED' | 'GRID_NEEDS_SSO'+export type GridHandoffCode = 'OK' | 'GRID_CLI_MISSING' | 'GRID_CLI_OUTDATED' | 'GRID_LOGIN_FAILED'export interface GridHandoffResult {code: GridHandoffCode/** The child's own exit code, propagated; 1 when there was no child, or it died on a signal. */exitCode: number- /** This module's own classification of the failure. Empty on success. Never contains the token. */+ /** What to show a person: `grid`'s own refusal under `json` ({@link refusalMessage}), else this+ * module's classification. Empty on success. Never contains the token (`grid` redacts it). */message: string/** The child's stdout, captured only when `json` was asked for; otherwise it went straight out. */stdout: string@@ -87,6 +99,13 @@ function failedMessage(status: number | null, signal: NodeJS.Signals | null): streturn `\`grid login ${GRID_HANDOFF_FLAG}\` ${how}.`}+/** `grid`'s sentence off its `--json` envelope, or null: none written, or stderr never captured (no+ * `json`). ⚠️ Found in ticket 03's review: Set up shows `message` alone, so a refusal naming its own+ * remedy reached the person as "`grid login --harness` exited 1." It is `grid`'s to word (ADR 0046). */+function refusalMessage(stderr: string): string | null {+ return gridEnvelopes(stderr).find((envelope) => envelope.message !== null)?.message ?? null+}+/*** Run `grid login --harness`, writing `token` to its standard input and closing it.*@@ -105,11 +124,6 @@ export async function handOffToGrid(// installing one, not a spawn error the caller has to recognise — and a present-but-unrunnable// one (EACCES, never ENOENT) is caught too. Resolved off this process's own environment, which is// the one place the override and the runtime dir are read from.- // A computer a phone signed in by QR holds a session Harness issued itself; grid signs in with the- // Autonomous account, which does not know it. Say what to do rather than let `grid` refuse it.- if (token.startsWith('hna_')) {- return { code: 'GRID_NEEDS_SSO', exitCode: 1, message: 'Grid needs a Google or Apple sign-in on this computer: harness login --force', stdout: '', stderr: '' }- }const binary = gridBinaryPath()if (!binaryOnPath(binary)) {return { code: 'GRID_CLI_MISSING', exitCode: 1, message: MISSING_MESSAGE, stdout: '', stderr: '' }@@ -174,7 +188,7 @@ export async function handOffToGrid(child.once('close', (status, signal) => {if (status === 0) { settle({ code: 'OK', exitCode: 0, message: '', stdout, stderr }); return }if (status === ARGPARSE_USAGE_EXIT) { settle({ code: 'GRID_CLI_OUTDATED', exitCode: status, message: OUTDATED_MESSAGE, stdout, stderr }); return }- settle({ code: 'GRID_LOGIN_FAILED', exitCode: status ?? 1, message: failedMessage(status, signal), stdout, stderr })+ settle({ code: 'GRID_LOGIN_FAILED', exitCode: status ?? 1, message: refusalMessage(stderr) ?? failedMessage(status, signal), stdout, stderr })})})}diff --git a/cli/src/lib/gridReader.ts b/cli/src/lib/gridReader.tsindex 547cc24b7..7a6b48c52 100644--- a/cli/src/lib/gridReader.ts+++ b/cli/src/lib/gridReader.ts@@ -22,6 +22,7 @@* public `grid` repository finds the two literals by these exact quoted spellings).*/import { VERSION } from '../version.js'+import { gridEnvelopes } from './gridEnvelope.js'import { gridExec, gridJson } from './gridExec.js'import { idKey } from './gridPicture.js'@@ -289,16 +290,7 @@ export async function readGridInfo(gridName: string): Promise<GridInfo | null> {/** The `code` of `grid`'s `--json` refusal envelope (one JSON line on stderr), or null. */function envelopeCode(stderr: string): string | null {- for (const line of stderr.split('\n')) {- const trimmed = line.trim()- if (!trimmed.startsWith('{')) continue- try {- const parsed = JSON.parse(trimmed) as unknown- const error = isObject(parsed) && isObject(parsed.error) ? parsed.error : null- if (error && typeof error.code === 'string') return error.code- } catch { /* not the envelope */ }- }- return null+ return gridEnvelopes(stderr).find((envelope) => envelope.code !== null)?.code ?? null}/**