diff --git a/README.md b/README.md index f81af7e0..ec03a98e 100644 --- a/README.md +++ b/README.md @@ -30,11 +30,13 @@ forge install --ssh USER@HOST ``` Replace `USER@HOST` with your server's SSH address or alias. The CLI asks for the -factory name, GitHub owner, repositories and coding account, then prepares the -server. It handles SSH and file transfers. +factory name and GitHub owner, then lists repositories and coding accounts to +choose from. Review the summary, edit anything you need, and confirm installation. +Forge handles SSH and file transfers. Your approval is required before project +merges by default; customization is under **Advanced**. Approve the Tailscale and GitHub browser prompts. Keep the terminal open until -setup gives you the web address. From there, **Installation progress** shows the +setup says **You can close this terminal**. From there, **Installation progress** shows the current step, anything waiting for you, and the first merge test. Codex sign-in can continue in the web app; other provider setup may require the CLI. diff --git a/docs/cli-fresh-host.md b/docs/cli-fresh-host.md index cee0549b..bb86322b 100644 --- a/docs/cli-fresh-host.md +++ b/docs/cli-fresh-host.md @@ -31,11 +31,22 @@ Install [uv](https://docs.astral.sh/uv/getting-started/installation/) first if n If your shell cannot find `forge`, run `uv tool update-shell` and open a new terminal. `anvil` is an example of an SSH alias; a `user@hostname` destination also works. -The interview records the factory name, GitHub owner and operators, repositories, -merge policies, provider logins and smoke target. It resolves the Forge revision -once. All selected repositories must belong to the chosen GitHub owner. A new -SSH fingerprint must be verified against the VM provider before use. -Review the preflight findings and confirm Apply once. +The default interview asks for the factory name, GitHub owner, repositories and +coding account, plus SSH host identity. Choose repositories and providers by +number; you can also type a repository name if it is not listed. All selected +repositories must belong to the chosen GitHub owner. + +Review one editable summary before preflight. Defaults are your GitHub account +as operator, Codex browser sign-in, approval before project merges, workflow +edits off, and a private repository for the first-merge test. **Advanced** offers +additional operators, network hostname, merge policies, explicit workflow-write +permission, other login methods and a different test repository. No passwords +or tokens belong in this interview. + +For an unfamiliar SSH host, verify its ED25519 fingerprint with your VM provider +before entering it. Leaving it blank uses your existing trusted SSH keys; it does +not trust a newly discovered host. Preflight checks the plan before the final +Apply confirmation. The deterministic intent-file interface is unchanged. The default smoke target creates two private repositories under the selected owner: one for the smoke issue, one for signed-publication qualification. Their @@ -47,13 +58,16 @@ any independent operator holds still apply. After preflight passes, the CLI prepares these GitHub targets, installs the host, and configures private HTTPS, the App and operator identity. It then opens **Installation progress** in Forge and hands the approved plan to the server. -You can close the terminal. The server prepares the worker environment while +Only after the CLI says **You can close this terminal** is the handoff confirmed. +The server prepares the worker environment while checking up to three repositories in parallel and waiting for Codex sign-in. Publication checks and the first-merge test start after their prerequisites pass. ### Browser steps -The CLI prints the exact browser actions as they become available: +The CLI prints the exact browser actions as they become available. Host and +network preparation still run before GitHub App consent; this is not an +all-consent-before-installation flow: 1. Approve the VM joining Tailscale if it needs authorization. 2. Open the local GitHub handoff, create the single Forge App, and install it on diff --git a/docs/onboarding-reference.md b/docs/onboarding-reference.md index d894f82a..8afc0b98 100644 --- a/docs/onboarding-reference.md +++ b/docs/onboarding-reference.md @@ -2,9 +2,9 @@ Detailed setup and repository protection reference. For the everyday walkthrough, see [Getting set up](onboarding.md). -`bin/forge setup` prepares the host and connects coding accounts in the terminal -(see [installation](installation.md)). Then open /onboarding on the trusted private -dashboard address. It has three steps: GitHub, Repository and Start. +Use the [guided installer](onboarding.md) for a new factory. It opens the web +installation page after bootstrap. Existing manual installations can continue +at `/onboarding`, with three steps: GitHub, Repository and Start. 1. **GitHub.** Register and install one Forge App through the guided flow. Select the repositories it may access, then refresh access in Forge. @@ -108,10 +108,16 @@ Guided setup allows up to four Build, two Review, one Audit and one Recovery wor These are ceilings: how many actually run depends on available memory (see [factory runtime](factory-runtime.md)), so a small host needs no tuning. -Connect or reconnect a harness from the VM terminal with +Connect or reconnect Codex in **Settings → Connections → Coding accounts**. +Choose Connect, open the OpenAI sign-in page and enter the displayed code. Forge +finishes sign-in and verifies Codex automatically. Closing the dialog does not +stop the login; return to the same page to resume it or request a fresh code +after expiry. + +Other providers and API-key/token modes currently use the CLI. Connect from the VM terminal with `bin/forge setup login codex --root ` or `bin/forge setup login claude --root `, then `bin/forge setup check` with -the same root. The UI shows connection status and terminal instructions. +the same root. The UI labels those modes as CLI instructions before you open them. Forge preserves refreshed installation-owned logins across runner cleanup; an older runner cannot overwrite a newer login. External imported files remain untouched. See [installation](installation.md) for API keys, model rotation and fresh VM setup. diff --git a/docs/onboarding-release-audit.md b/docs/onboarding-release-audit.md index 94afb3ac..b8779551 100644 --- a/docs/onboarding-release-audit.md +++ b/docs/onboarding-release-audit.md @@ -18,6 +18,29 @@ merge. Operator actions and time spent waiting for a prompt are separate measure | Where are settings? | Five categories compete for attention. Capacity and reset appear alongside normal operation. | General, Repositories, Connections. Fold capacity/reset; preserve deep links and unsaved edits. | | What should I do first? | Installation tests itself, but the README buried the path to real issue work. | Explain `ready`, planning groups, approval and Activity. Validate this handover in Group C. | +## Implementation follow-up + +The next integrated change implements the shorter default CLI interview, numbered +repository/provider choices and editable summary. Advanced choices retain workflow +permission and host identity consent. The browser handoff is announced only after +the server confirms that it accepted the setup plan; otherwise the CLI provides +its resume action. + +Codex browser connect, reconnect and verification now have a post-install web +path using the existing durable device-login lifecycle. Other provider/browser +adapters and API-key/token web entry remain separate work. The original findings +below describe the audit baseline; these two improvements address most of A/B. + +Remaining release work: + +- Move the remaining GitHub consent earlier; host/network preparation still comes + first. Do not claim all approvals happen before installation starts. +- Verify the integrated account-recovery changes on the deployed factory. +- Run Group C on a disposable supported Ubuntu x86-64 host. Record command-start + time separately because the historical saved timer begins after the interview. +- Keep additional provider modes explicit rather than presenting unsupported web + sign-in actions. New adapters and Mac-host support remain outside this release. + ## Delivery groups, in order ### A — Finish the default installation path (release blocker) diff --git a/docs/onboarding.md b/docs/onboarding.md index e5421d95..8af0e6e4 100644 --- a/docs/onboarding.md +++ b/docs/onboarding.md @@ -121,7 +121,11 @@ time to first merge when the run completes. ## Configuration and recovery For an active factory, use **Settings** to manage repository access, accounts and -configuration. **Settings → GitHub access → Add repository** checks access and +configuration. Codex browser sign-in and reconnect are available under +**Settings → Connections → Coding accounts**. Other providers and API-key/token +modes currently use the CLI and are labeled accordingly. + +**Settings → Repositories → Add repository** checks access and rules before **Enable automation**. Checking or discovering a repository alone does not enable it. Refresh expired checks when prompted. diff --git a/forge/account_web.py b/forge/account_web.py new file mode 100644 index 00000000..5f8266bf --- /dev/null +++ b/forge/account_web.py @@ -0,0 +1,115 @@ +"""Operator account recovery using the installation's owned device-login lifecycle.""" +import time +import uuid + +from forge_client.contracts import fields, require +from .installation_accounts import DeviceAccount +from .host_setup import LoginBusy +from .onboarding import Onboarding +from .settings import Settings +from .sqlite_identity import audit_in, identity_effect_lock +from .store.configuration import Configuration +from .store.runtime import required + + +class AccountWeb: + def __init__(self, root, *, setup=None, clock=time.time, device=None): + self.root, self.clock = root, clock + self.setup = setup or Onboarding(root, clock=clock) + self.store = required(root) + self.configuration = Configuration(self.store, clock=clock) + self.device = device or DeviceAccount(root, setup=self.setup, clock=clock) + + def saved(self, generation): + return self.configuration.get('account_web', generation) + + def view(self): + data = self.setup.read() + saved = self.saved(data['generation']) + record = data.get('device_logins', {}).get('codex') + account = {'provider': 'codex', 'status': 'idle'} + if record: + try: + result = self.device.call('codex', generation=data['generation'], setup_id=record['setup_id']) + account = {key: result[key] for key in ('provider', 'status', 'url', 'code', 'expires_at') if key in result} + except (ValueError, RuntimeError, OSError): + account['status'] = 'account_unavailable' + operation = saved['settings'] if saved else {} + return {'generation': data['generation'], 'revision': saved['revision'] if saved else 0, + 'setup_revision': self.setup.revision(data), 'account': account, + 'operation': {key: operation[key] for key in ('status', 'updated_at', 'error', 'verification') if key in operation}, + 'browser_providers': ['codex'], 'active': data['phase'] == 'active'} + + def request(self, value, *, actor_id): + fields(value, ('generation', 'revision', 'setup_revision', 'provider', 'action')) + require(value['provider'] == 'codex', 'device_login_unsupported') + require(value['action'] in ('connect', 'reconnect', 'retry', 'verify'), 'invalid_action') + with identity_effect_lock(self.store): + data = self.setup.read(); generation = data['generation'] + require(generation == value['generation'] and data['phase'] == 'active', 'setup_changed') + require(not Settings(self.root).paused(), 'factory_paused') + saved = self.saved(generation) + require(value['revision'] == (saved['revision'] if saved else 0) + and value['setup_revision'] == self.setup.revision(data), 'account_changed') + record = data.get('device_logins', {}).get('codex') + expired_retry = (saved and saved['settings']['status'] == 'connecting' + and value['action'] in ('retry', 'reconnect') and record + and self.clock() >= record['expires_at']) + if saved and saved['settings']['status'] in ('queued', 'connecting', 'verifying') and not expired_retry: + return self.view() + require(not data.get('operation'), 'setup_busy') + connected = next(row['connected'] for row in self.setup.harnesses(data) if row['id'] == 'codex') + require(value['action'] != 'verify' or connected, 'account_not_connected') + require(value['action'] != 'connect' or not connected, 'account_already_connected') + record = data.get('device_logins', {}).get('codex') + operation = {'status': 'queued', 'action': value['action'], 'updated_at': self.clock(), + 'setup_id': record['setup_id'] if record else uuid.uuid4().hex, + 'previous_session': record['id'] if record else None} + with self.store.write() as db: + self.configuration.replace_in(db, 'account_web', operation, subject=generation, + expected_revision=saved['revision'] if saved else 0) + audit_in(db, self.clock, 'account_operation_requested', details={ + 'actor_id': actor_id, 'provider': 'codex', 'action': value['action'], 'generation': generation}) + return self.view() + + def tick(self): + with identity_effect_lock(self.store): + data = self.setup.read(); generation = data['generation']; saved = self.saved(generation) + if data['phase'] != 'active' or Settings(self.root).paused() or not saved: + return + operation = saved['settings'] + if operation['status'] not in ('queued', 'connecting', 'verifying'): + return + following = dict(operation) + try: + if operation['status'] == 'verifying': + if data.get('operation'): return + harness = next(row for row in self.setup.harnesses(data) if row['id'] == 'codex') + passed = harness['models'] and all(row['status'] == 'passed' for row in harness['models']) + following['status'] = 'complete' if passed else 'failed' + if not passed: following['error'] = 'Codex verification did not pass. Try again.' + else: + if data.get('operation'): return + if operation['action'] == 'verify': + result = {'status': 'connected'} + else: + record = data.get('device_logins', {}).get('codex') + original = (record['id'] if record else None) == operation['previous_session'] + restart = original and operation['action'] in ('retry', 'reconnect') + if restart and record and record['phase'] not in ('failed', 'complete') and self.clock() < record['expires_at']: + observed = self.device.call('codex', generation=generation, setup_id=operation['setup_id']) + restart = observed['status'] == 'account_login_failed' + result = self.device.call('codex', generation=generation, setup_id=operation['setup_id'], apply=True, + retry=restart, reconnect=restart and operation['action'] == 'reconnect') + if result['status'] == 'connected': + self.setup.queue('harness_check', self.setup.revision(self.setup.read()), harness='codex') + following.update(status='verifying', verification=True) + else: + following['status'] = 'failed' if result['status'] in ('account_login_failed', 'write_unconfirmed') else 'connecting' + except LoginBusy: + return + except (ValueError, RuntimeError, OSError): + following.update(status='failed', error='Account connection stopped. Retry or check the factory status.') + if following != operation: + following['updated_at'] = self.clock() + self.configuration.replace('account_web', following, subject=generation, expected_revision=saved['revision']) diff --git a/forge/host_setup.py b/forge/host_setup.py index 528b2e96..3cabc357 100644 --- a/forge/host_setup.py +++ b/forge/host_setup.py @@ -110,13 +110,17 @@ def update(root, bind=None, assume_yes=False): check(root) +class LoginBusy(ValueError): + """Another caller owns this provider login; retry observation later.""" + + @contextmanager def login_lock(root, provider): with open(root / ('state-login-' + provider + '.lock'), 'a') as stream: try: fcntl.flock(stream, fcntl.LOCK_EX | fcntl.LOCK_NB) except BlockingIOError: - raise ValueError('Another terminal is already connecting this harness') from None + raise LoginBusy('Another terminal is already connecting this harness') from None yield diff --git a/forge/installation_accounts.py b/forge/installation_accounts.py index ca58e457..c840f052 100644 --- a/forge/installation_accounts.py +++ b/forge/installation_accounts.py @@ -80,11 +80,15 @@ def cleanup(self, record): require(not home.is_symlink() and home.stat().st_uid == os.getuid(), 'account_owner_changed') shutil.rmtree(home) - def call(self, provider, *, generation, setup_id, apply=False, retry=False): + def call(self, provider, *, generation, setup_id, apply=False, retry=False, reconnect=False): require(provider == 'codex', 'device_login_unsupported', 'This provider uses the existing guided terminal login.') require(type(apply) is bool and type(retry) is bool and (not retry or apply) + and type(reconnect) is bool and (not reconnect or retry) and isinstance(setup_id, str) and re.fullmatch('[a-f0-9]{32}', setup_id)) - with login_lock(self.root, provider), identity_effect_lock(self.root): + # Installation and account supervisors already hold the identity lock. + # Reads use the same order so they never hold the provider lock while + # waiting for a supervisor to release identity ownership. + with identity_effect_lock(self.root), login_lock(self.root, provider): data = self.setup.read() require(data['generation'] == generation and data['phase'] in ('setup', 'active'), 'setup_changed', 'Setup identity or phase changed during account login.') @@ -97,10 +101,10 @@ def call(self, provider, *, generation, setup_id, apply=False, retry=False): require(record['generation'] == generation and record['setup_id'] == setup_id, 'account_session_changed', 'This login belongs to an earlier setup; reset its owned login session first.') connected = next((item['connected'] for item in self.setup.harnesses(data) if item['id'] == provider), False) - if connected and not record: + if connected and not record and not reconnect: return {'status': 'connected', 'provider': provider} if record and record['phase'] == 'complete': - if connected: + if connected and not reconnect: return {'status': 'connected', 'provider': provider, 'session_id': record['id']} if not retry: return {'status': 'account_login_failed', 'provider': provider, 'session_id': record['id'], @@ -116,7 +120,7 @@ def call(self, provider, *, generation, setup_id, apply=False, retry=False): self.cleanup(record); self.save(generation, {**record, 'phase': 'complete'}) return {'status': 'connected' if apply else 'account_login_saved', 'provider': provider, 'session_id': record['id']} if retry and record: - require(record['phase'] == 'failed' or record['phase'] == 'complete' and not connected + require(record['phase'] == 'failed' or record['phase'] == 'complete' and (not connected or reconnect) or self.clock() >= record['expires_at'] or failed_start(self.inspect(record)), 'account_login_running', 'Finish the current device login before starting another one.') self.cleanup(record) @@ -201,7 +205,9 @@ def call(self, provider, *, generation, setup_id, apply=False, retry=False): 'A different login is now connected; inspect it before replacing provider credentials.') record = {**record, 'phase': 'finishing', 'credential_digest': hashlib.sha256(value.encode()).hexdigest()} self.save(generation, record) - pending_login(self.setup, provider, generation, {'secret': None, 'value': value, 'models': None, 'kind': 'api_key'}) + config = self.setup.active_runtime() if data['phase'] == 'active' else self.setup.runtime() + models = [entry['model'] for entry in config['provider_pool'] if entry['provider'] == provider] or None + pending_login(self.setup, provider, generation, {'secret': None, 'value': value, 'models': models, 'kind': 'api_key'}) # Reuse the same credential/configuration handoff as trusted terminal # login. It owns controller serialization and cooldown removal. if not same_login: diff --git a/forge/setup_service.py b/forge/setup_service.py index 49ea837e..f256a4f6 100644 --- a/forge/setup_service.py +++ b/forge/setup_service.py @@ -117,7 +117,7 @@ def access(self, data): settings.refresh() repo = data['selected'] if not settings.admission(repo['name'])['allowed']: - raise ValueError('Refresh all four GitHub App installations and grant access to the selected repository') + raise ValueError('Refresh GitHub access and grant the Forge App access to the selected repository') config = self.setup.runtime() github = self.github_class(settings, config) item = {'repo': repo['name'], 'repo_id': repo['id']} @@ -421,6 +421,8 @@ def tick(self): 'ON CONFLICT(name) DO UPDATE SET heartbeat_at=excluded.heartbeat_at,updated_at=excluded.updated_at', (now, now)) from .installation_web import InstallationWeb InstallationWeb(self.root, setup=self.setup).tick() + from .account_web import AccountWeb + AccountWeb(self.root, setup=self.setup).tick() data = self.setup.read() op = data.get('operation') scoped = bool(op and op['action'] == 'harness_check' and op.get('providers') and data['phase'] == 'active') diff --git a/forge_client/github.py b/forge_client/github.py index 12e393b9..33e42dba 100644 --- a/forge_client/github.py +++ b/forge_client/github.py @@ -123,6 +123,24 @@ def registration_owner(self, login): and value.get('login', '').lower() == login.lower()) return {k: value[k] for k in ('id', 'login', 'type')} + def installation_repositories(self, login): + """Recent choices for the human interview; plan resolves each choice again.""" + owner = self.registration_owner(login) + path = ('/orgs/' + owner['login'] + '/repos' if owner['type'] == 'Organization' + else '/user/repos') + values = self._request('GET', path + '?sort=pushed&per_page=100') + require(isinstance(values, list), 'github_invalid_response') + names = [] + for row in values: + require(isinstance(row, dict), 'github_invalid_response') + if ((row.get('owner') or {}).get('id') != owner['id'] + or row.get('archived') is not False or row.get('disabled') is not False): + continue + name = row.get('full_name') + require(isinstance(name, str) and NAME.fullmatch(name), 'github_invalid_response') + names.append(name) + return sorted(set(names), key=str.lower) + def pilot_issue(self, target, number, *, ready_label=None): require(isinstance(target, dict) and NAME.fullmatch(target.get('name', '')) and positive(number)) value = self._request('GET', f"/repos/{target['name']}/issues/{number}") diff --git a/forge_client/install_interview.py b/forge_client/install_interview.py new file mode 100644 index 00000000..643c330b --- /dev/null +++ b/forge_client/install_interview.py @@ -0,0 +1,173 @@ +"""A short human interview that produces the unchanged installation intent.""" +import re + +from .contracts import NAME, SetupError + +PROVIDERS = (('codex', 'Codex'), ('claude', 'Claude Code'), ('grok', 'Grok')) + + +def choice(prompt, options, *, ask, tell, default=None): + for number, (_, label) in enumerate(options, 1): + tell(f' {number}. {label}') + while True: + answer = ask(prompt).strip().lower() + if not answer and default is not None: + return default + if answer.isdigit() and 1 <= int(answer) <= len(options): + return options[int(answer) - 1][0] + if answer in [key for key, _ in options]: + return answer + tell('Choose a number from the list.') + + +def repositories(owner, github, *, ask, tell, previous=()): + tell('Choose repositories under ' + owner + '.') + try: + available = github.installation_repositories(owner) + except SetupError: + available = [] + tell('Repository discovery is unavailable. Enter repository names; preflight will check access.') + for number, name in enumerate(available, 1): + tell(f' {number}. {name}') + if available: + tell('Recent repositories shown. You can also enter names that are not listed.') + defaults = [row['name'] for row in previous] + while True: + entered = ask('Repositories (numbers or names, separated by spaces)' + + (' [' + ', '.join(defaults) + ']' if defaults else '') + ': ').strip() + values = re.split(r'[\s,]+', entered) if entered else defaults + names = [] + for value in values: + if value.isdigit(): + if not 1 <= int(value) <= len(available): + break + value = available[int(value) - 1] + if '/' not in value: + value = owner + '/' + value + if not NAME.fullmatch(value) or value.split('/')[0].lower() != owner.lower(): + break + names.append(value) + else: + if 1 <= len(names) <= 20 and len(set(name.lower() for name in names)) == len(names): + prior = {row['name'].lower(): row for row in previous} + return [dict(prior.get(name.lower(), {'name': name, 'merge_policy': 'human', + 'allow_workflow_edits': False})) for name in names] + tell('Choose 1–20 different repositories belonging to ' + owner + '.') + + +def provider(*, ask, tell, default='codex'): + tell('Choose a coding account. Provider usage may have a cost.') + selected = choice('Coding account [1]: ', PROVIDERS, ask=ask, tell=tell, default=default) + if selected != 'codex': + tell('This account connects through the CLI before the browser handoff.') + return {'id': selected, 'kind': 'browser'} + + +def host_key(ssh, *, ask, tell): + tell('SSH must use a trusted host key. For a new server, run forge setup host-key --ssh ' + ssh + + ' and verify the fingerprint with your provider.') + while True: + value = ask('Verified ED25519 fingerprint [use known_hosts]: ').strip() + if not value or re.fullmatch(r'SHA256:[A-Za-z0-9+/]{43}', value): + return value or None + tell('Enter the full SHA256 fingerprint, or leave blank to use an already trusted SSH key.') + + +def summary(value, tell): + tell('\nInstallation plan') + tell(' Host: ' + value['ssh']) + tell(' Factory: ' + value['name'] + ' (' + value['hostname'] + ')') + tell(' GitHub owner: ' + value['owner']) + tell(' Operators: ' + ', '.join(value['operators'])) + for row in value['repositories']: + policy = 'approval before merge' if row['merge_policy'] == 'human' else 'automatic merge' + tell(' ' + row['name'] + ': ' + policy + '; workflow edits ' + + ('allowed' if row['allow_workflow_edits'] else 'off')) + tell(' Coding accounts: ' + ', '.join(row['id'] + ' (' + row['kind'] + ')' for row in value['providers'])) + tell(' SSH trust: ' + (value['host_key'] or 'existing known_hosts')) + tell(' First merge: ' + ('private test repository' if value['smoke_target'] == 'scratch' else value['smoke_target'])) + tell('Setup installs Forge on this host, creates one GitHub App and ' + + ('two private test repositories.' if value['smoke_target'] == 'scratch' else + 'one private publication-test repository and a test issue in ' + value['smoke_target'] + '.')) + tell('Test repositories remain after setup. Your selected repositories enable after the test merge.') + tell('Forge requires Review and Audit before its merges and respects existing GitHub rules.') + + +def advanced(value, *, ask, tell): + options = (('hostname', 'Network hostname'), ('operators', 'Additional operators'), + ('policies', 'Merge approval and workflow edits'), ('providers', 'More coding accounts or login methods'), + ('smoke', 'First-merge test repository'), ('done', 'Back to summary')) + while True: + selected = choice('Advanced [6]: ', options, ask=ask, tell=tell, default='done') + if selected == 'done': + return + if selected == 'hostname': + value['hostname'] = ask('Network hostname [' + value['hostname'] + ']: ').strip() or value['hostname'] + elif selected == 'operators': + value['operators'] = ask('Operator GitHub logins [' + ' '.join(value['operators']) + ']: ').split() or value['operators'] + elif selected == 'smoke': + options_smoke = [('scratch', 'Private test repository (recommended)')] + options_smoke.extend((row['name'], row['name']) for row in value['repositories']) + tell('Choosing a project creates the first-merge test issue there.') + value['smoke_target'] = choice('Test repository [1]: ', options_smoke, ask=ask, tell=tell, default='scratch') + elif selected == 'policies': + for row in value['repositories']: + tell(row['name']) + row['merge_policy'] = choice('Merge policy [' + row['merge_policy'] + ']: ', + (('human', 'Wait for your approval'), ('auto', 'Merge automatically after checks pass')), + ask=ask, tell=tell, default=row['merge_policy']) + row['allow_workflow_edits'] = choice('Allow Forge to change GitHub Actions workflows? [' + + ('yes' if row['allow_workflow_edits'] else 'no') + ']: ', + (('no', 'No'), ('yes', 'Yes — grant workflow-write permission')), + ask=ask, tell=tell, default='yes' if row['allow_workflow_edits'] else 'no') == 'yes' + elif selected == 'providers': + tell('Current accounts: ' + ', '.join(row['id'] for row in value['providers'])) + account = provider(ask=ask, tell=tell) + kinds = [('browser', 'Browser sign-in'), ('api_key', 'API key')] + if account['id'] == 'claude': + kinds.append(('token', 'Claude token')) + account['kind'] = choice('Login method [1]: ', kinds, ask=ask, tell=tell, default='browser') + value['providers'] = [row for row in value['providers'] if row['id'] != account['id']] + [account] + + +def interview(ssh, github, *, ask=input, tell=None): + tell = tell or (lambda line: print(line, flush=True)) + actor = github.identity() + ssh = ssh or ask('SSH destination (alias or user@host): ').strip() + suggested = ssh.split('@')[-1] + name = ask('Factory name [' + suggested + ']: ').strip() or suggested + owner = ask('GitHub owner [' + actor['login'] + ']: ').strip() or actor['login'] + rows = repositories(owner, github, ask=ask, tell=tell) + account = provider(ask=ask, tell=tell) + fingerprint = host_key(ssh, ask=ask, tell=tell) + value = {'version': 1, 'ssh': ssh, 'name': name, 'revision': None, 'host_key': fingerprint, + 'hostname': re.sub('[^a-z0-9-]+', '-', name.lower()).strip('-')[:63], + 'owner': owner, 'operators': [actor['login']], 'repositories': rows, 'providers': [account], + 'smoke_target': 'scratch', 'codex_parallel_auth': True} + while True: + summary(value, tell) + selected = choice('Enter to check this plan, or choose a field to edit: ', + (('name', 'Factory name'), ('owner', 'GitHub owner'), ('repositories', 'Repositories'), + ('provider', 'Coding account'), ('advanced', 'Advanced'), ('host', 'Host identity')), + ask=ask, tell=tell, default='check') + if selected == 'check': + return value + if selected == 'name': + old_hostname = re.sub('[^a-z0-9-]+', '-', value['name'].lower()).strip('-')[:63] + value['name'] = ask('Factory name [' + value['name'] + ']: ').strip() or value['name'] + if value['hostname'] == old_hostname: + value['hostname'] = re.sub('[^a-z0-9-]+', '-', value['name'].lower()).strip('-')[:63] + elif selected in ('owner', 'repositories'): + previous = value['repositories'] + if selected == 'owner': + value['owner'] = ask('GitHub owner [' + value['owner'] + ']: ').strip() or value['owner'] + previous = [row for row in previous if row['name'].split('/')[0].lower() == value['owner'].lower()] + value['repositories'] = repositories(value['owner'], github, ask=ask, tell=tell, previous=previous) + if value['smoke_target'] not in [row['name'] for row in value['repositories']]: + value['smoke_target'] = 'scratch' + elif selected == 'provider': + value['providers'] = [provider(ask=ask, tell=tell)] + elif selected == 'host': + value['host_key'] = host_key(ssh, ask=ask, tell=tell) + else: + advanced(value, ask=ask, tell=tell) diff --git a/forge_client/installation.py b/forge_client/installation.py index 4f8d87c1..2d0c233b 100644 --- a/forge_client/installation.py +++ b/forge_client/installation.py @@ -4,7 +4,6 @@ import math from pathlib import Path import re -import shutil import time from .connection import connection_lock @@ -12,6 +11,7 @@ from .factory_setup import FactorySetup from .github import GitHub from .install import Installation, revision +from .install_interview import interview from .network import Network from .preflight import observe from .workflow import Journal @@ -467,6 +467,7 @@ def status(self): self.load() stages = deepcopy(self.state['stages']) complete = stages.get('handover', {}).get('status') == 'complete' + web_owned = self.state.get('server_preparation', {}).get('registered') is True report, report_path = None, None if complete: saved = install_report.storage(self.journal, self.state) @@ -486,50 +487,16 @@ def status(self): 'stages': stages, 'pending': pending, 'started_at': self.state['started_at'], 'completed_at': self.state.get('completed_at'), 'elapsed_seconds': max(0, self.state.get('completed_at', self.clock()) - self.state['started_at']), - 'next_action': None if complete or self.state.get('server_preparation') else ['forge', 'install', '--ssh', self.ssh, '--resume'], - 'web_owned': bool(self.state.get('server_preparation')), + 'next_action': None if complete or web_owned else ['forge', 'install', '--ssh', self.ssh, '--resume'], + 'web_owned': web_owned, 'setup_url': ((stages.get('identity', {}).get('receipt') or {}).get('origin', '').rstrip('/') + '/installation') - if self.state.get('server_preparation') else None, + if web_owned else None, 'handover_complete': complete, 'origin': (stages.get('identity', {}).get('receipt') or {}).get('origin'), 'report_path': str(self.journal.path) if complete else None, 'handover_report': report, 'handover_report_path': report_path} -def interview(ssh, github, *, ask=input, tell=None): - tell = tell or (lambda line: print(line, flush=True)) - actor = github.identity() - ssh = ssh or ask('SSH destination (configured alias or user@host): ').strip() - suggested = ssh.split('@')[-1] - name = ask('Factory name [' + suggested + ']: ').strip() or suggested - tell('Forge creates one private GitHub App. Its owner must be the same personal account or organization that owns all repositories selected here.') - owner = ask('GitHub App owner [' + actor['login'] + ']: ').strip() or actor['login'] - operators = ask('Operator logins [' + actor['login'] + ']: ').strip().split() or [actor['login']] - repos = ask('Repositories (OWNER/REPO, separated by spaces): ').strip().split() - rows = [] - tell('Human merge policy waits for your approval after Forge Review and Audit. Auto merges when Forge checks and existing GitHub rules pass.') - tell('Forge enforces Review and Audit before merging. Existing GitHub rules also apply; setup does not create or change them.') - for name_in_repo in repos: - mode = ask(name_in_repo + ' merge policy [human/auto; human]: ').strip() or 'human' - workflows = ask(name_in_repo + ' allow workflow edits? [y/N]: ').strip().lower() in ('y', 'yes') - rows.append({'name': name_in_repo, 'merge_policy': mode, 'allow_workflow_edits': workflows}) - providers = ask('Providers (codex, claude, grok; space-separated) [codex]: ').strip().split() or ['codex'] - accounts = [] - for provider in providers: - default = 'token' if provider == 'claude' and shutil.which('claude') else 'browser' - kind = ask(provider + ' login kind [browser/api_key/token; ' + default + ']: ').strip() or default - accounts.append({'id': provider, 'kind': kind}) - hostname = re.sub('[^a-z0-9-]+', '-', name.lower()).strip('-')[:63] - hostname = ask('Tailnet hostname [' + hostname + ']: ').strip() or hostname - tell('The first-merge test runs a small issue through Build, Review, Audit and merge. Scratch creates a private test repository; choosing a project runs the test there. A separate private repository tests signed publication.') - smoke = ask('Smoke target [scratch or chosen OWNER/REPO; scratch]: ').strip() or 'scratch' - tell('Known SSH host keys are required. For a new VM, use forge setup host-key and verify its fingerprint with the provider.') - fingerprint = ask('Verified ED25519 fingerprint (leave empty to use known_hosts): ').strip() or None - return {'version': 1, 'ssh': ssh, 'name': name, 'revision': None, 'host_key': fingerprint, 'hostname': hostname, - 'owner': owner, 'operators': operators, 'repositories': rows, 'providers': accounts, - 'smoke_target': smoke, 'codex_parallel_auth': True} - - def execute(args): import sys require(type(args.wait) is int and 0 <= args.wait <= 3600, 'invalid_wait', 'Use --wait between 0 and 3600 seconds.') @@ -584,6 +551,8 @@ def event(value): if input('Apply this installation, including its smoke issue and configured handover? [y/N] ').strip().lower() not in ('y', 'yes'): args._installation_report_displayed = True return report + print('Keep this terminal open for Tailscale and GitHub approval. ' + 'Forge will tell you when setup can continue in the browser.', file=sys.stderr, flush=True) args.apply = True args.wait = args.wait or 3600 if args.resume or args.apply: @@ -657,11 +626,12 @@ def display(result, *, tell=None): tell('Forge: ' + result['origin']) if result.get('web_owned') and not result.get('handover_complete'): tell('Continue setup in your browser: ' + result['setup_url']) - tell('The server keeps working after this terminal closes.') + tell('You can close this terminal. Follow progress and remaining actions in Forge.') if result.get('handover_report_path'): tell('Private report: ' + result['handover_report_path']) if result.get('report_path'): tell('Installation journal: ' + result['report_path']) - if result.get('next_action'): tell(shlex.join(result['next_action'])) + if result.get('next_action'): + tell('Setup still needs this CLI. Resume with: ' + shlex.join(result['next_action'])) def schemas(): diff --git a/legacy/forge-status.py b/legacy/forge-status.py index d318ff33..25200acb 100755 --- a/legacy/forge-status.py +++ b/legacy/forge-status.py @@ -385,7 +385,7 @@ def _dispatch_POST(self): if not self._session: # Without configured sign-in and a session, the API offers no control. self.send_error(401);return - if self.path not in {'/api/connections/preview', '/api/connections/decide', '/api/connections/revoke', '/api/auth/logout', '/api/auth/identity', '/api/settings/sync', '/api/factory/action', '/api/runtime', '/api/onboarding', '/api/installation', '/api/repositories/check', '/api/repositories/mirror', '/api/repositories/review-scope', '/api/repositories/merge-policy', '/api/repositories/github-protection', '/api/repositories/steward', '/api/repositories/enable', '/api/repositories/disable', '/api/repositories/deployment', '/api/repositories/environment', '/api/issues/action', '/api/issues/steward', '/api/issues/delivery', '/api/issues/verify', '/api/issues/environment', '/api/issues/refresh', '/api/issues/discussion', '/api/repositories/planning'}: + if self.path not in {'/api/connections/preview', '/api/connections/decide', '/api/connections/revoke', '/api/auth/logout', '/api/auth/identity', '/api/settings/sync', '/api/factory/action', '/api/runtime', '/api/onboarding', '/api/installation', '/api/accounts', '/api/repositories/check', '/api/repositories/mirror', '/api/repositories/review-scope', '/api/repositories/merge-policy', '/api/repositories/github-protection', '/api/repositories/steward', '/api/repositories/enable', '/api/repositories/disable', '/api/repositories/deployment', '/api/repositories/environment', '/api/issues/action', '/api/issues/steward', '/api/issues/delivery', '/api/issues/verify', '/api/issues/environment', '/api/issues/refresh', '/api/issues/discussion', '/api/repositories/planning'}: self.send_error(404);return # An attacker may cause a browser to send a form, but cannot read the # dashboard token or set this header cross-origin without CORS approval. @@ -443,6 +443,10 @@ def _dispatch_POST(self): self._auth.logout(self._session_token) self._send(json.dumps({'ok': True}), headers={'Set-Cookie': cookie(SESSION_COOKIE)}) return + if self.path == '/api/accounts': + from forge.account_web import AccountWeb + result = AccountWeb(WD).request(value, actor_id=self._operator_actor()) + self._send(json.dumps({'ok': True, **result}));return if self.path == '/api/installation': from forge.installation_web import InstallationWeb result = InstallationWeb(WD).request(value, actor_id=self._operator_actor()) @@ -700,7 +704,10 @@ def _get(self, u): except (ValueError,OSError,RuntimeError): self._redirect('/onboarding?connection_error=1') return - if u.path == '/api/installation': + if u.path == '/api/accounts': + from forge.account_web import AccountWeb + self._send(json.dumps({'ok': True, **AccountWeb(WD).view(), 'controls_token': self._action_token})) + elif u.path == '/api/installation': from forge.installation_web import InstallationWeb try: result = InstallationWeb(WD).view() diff --git a/tests/test_account_web.py b/tests/test_account_web.py new file mode 100644 index 00000000..5dfd952b --- /dev/null +++ b/tests/test_account_web.py @@ -0,0 +1,194 @@ +"""Post-install browser recovery shares device ownership and scoped verification.""" +import unittest +from unittest.mock import Mock, patch +from forge.account_web import AccountWeb +from forge_client.contracts import SetupError +from tests.test_installation_web import InstallationWebTests, InstallationHTTPTests + + +class AccountWebTests(unittest.TestCase): + active = InstallationWebTests.active + def setUp(self): + InstallationWebTests.setUp(self) + self.active() + self.device = Mock() + self.device.call.return_value = {'status': 'account_login_pending', 'provider': 'codex'} + self.web = AccountWeb(self.root, setup=self.setup, clock=lambda: self.now, device=self.device) + self.harnesses = patch.object(self.setup, 'harnesses', return_value=[{'id': 'codex', 'connected': False, 'models': []}]).start() + self.addCleanup(patch.stopall) + + # Do not inherit installation-specific assertions. + def request_account(self, action='connect', **changes): + view = self.web.view() + value = {key: view[key] for key in ('generation', 'revision', 'setup_revision')} + return self.web.request({**value, 'action': action, 'provider': 'codex', **changes}, actor_id='github:7') + + def test_durable_connect_survives_reload_without_duplicate_start(self): + first = self.request_account() + self.assertEqual(first['operation']['status'], 'queued') + self.device.call.assert_not_called() + self.request_account() + self.web.tick() + self.assertEqual(self.web.view()['operation']['status'], 'connecting') + resumed = AccountWeb(self.root, setup=self.setup, device=self.device) + resumed.tick() + self.assertEqual(self.device.call.call_count, 2) + self.assertEqual(self.device.call.call_args_list[0].kwargs['setup_id'], self.device.call.call_args_list[1].kwargs['setup_id']) + + def test_stale_generation_revision_and_unsupported_provider_refused(self): + for changes in ({'generation': 'old'}, {'revision': 99}, {'setup_revision': 'old'}, {'provider': 'claude'}): + with self.assertRaises(SetupError): self.request_account(**changes) + self.device.call.assert_not_called() + + def test_duplicate_old_request_cannot_restart_the_accepted_login(self): + view = self.web.view() + value = {key: view[key] for key in ('generation', 'revision', 'setup_revision')} + value.update(provider='codex', action='connect') + self.web.request(value, actor_id='github:7') + with self.assertRaises(SetupError): self.web.request(value, actor_id='github:7') + self.device.call.assert_not_called() + + def test_reset_or_pause_does_not_advance_login(self): + self.request_account() + with self.setup.store.transaction() as data: data['phase'] = 'resetting' + self.web.tick(); self.device.call.assert_not_called() + with self.assertRaises(SetupError): self.request_account() + + def test_expired_login_requires_explicit_retry(self): + self.request_account() + self.device.call.return_value = {'status': 'account_login_failed'} + self.web.tick() + self.assertEqual(self.web.view()['operation']['status'], 'failed') + count = self.device.call.call_count + self.web.tick(); self.assertEqual(count, self.device.call.call_count) + self.request_account('retry'); self.web.tick() + self.assertTrue(self.device.call.call_args.kwargs['retry']) + + def test_retry_after_runtime_interruption_resumes_unexpired_login(self): + with self.setup.store.transaction() as data: + data['device_logins'] = {'codex': {'id': 'saved', 'phase': 'running', 'expires_at': 900, + 'setup_id': 'a'*32}} + self.request_account('retry') + self.web.tick() + self.assertFalse(self.device.call.call_args.kwargs['retry']) + self.assertFalse(self.device.call.call_args.kwargs['reconnect']) + self.assertEqual(self.device.call.call_args.kwargs['setup_id'], 'a'*32) + + def test_completed_login_queues_only_codex_verification(self): + self.request_account() + self.device.call.return_value = {'status': 'connected'} + with patch.object(self.setup, 'queue') as queue: + self.web.tick() + self.assertEqual(queue.call_args.args[0], 'harness_check') + self.assertEqual(queue.call_args.kwargs, {'harness': 'codex'}) + self.assertEqual(self.web.view()['operation']['status'], 'verifying') + self.harnesses.return_value = [{'id': 'codex', 'connected': True, 'models': [{'status': 'passed'}]}] + self.web.tick() + self.assertEqual(self.web.view()['operation']['status'], 'complete') + + def test_observation_filters_provider_output(self): + with self.setup.store.transaction() as data: + data['device_logins'] = {'codex': {'id': 'a', 'setup_id': 'a'*32}} + self.device.call.return_value = {'provider': 'codex', 'status': 'account_login_required', + 'code': 'ABCD-12345', 'secret': 'never', 'reason': 'private output'} + view = self.web.view() + self.assertEqual(view['account']['code'], 'ABCD-12345') + self.assertNotIn('secret', view['account']); self.assertNotIn('reason', view['account']) + + +class AccountHTTPTests(unittest.TestCase): + setUp = InstallationHTTPTests.setUp + handler = InstallationHTTPTests.handler + + def test_accounts_require_operator_and_csrf(self): + value = {'generation': 'g', 'revision': 0, 'setup_revision': 'r', 'provider': 'codex', 'action': 'connect'} + with patch('forge.account_web.AccountWeb') as service: + service.return_value.view.return_value = {'active': True} + service.return_value.request.return_value = {'active': True} + handler = self.handler('/api/accounts', Host='attacker.example'); handler.do_GET() + handler.send_error.assert_called_once_with(403); service.assert_not_called() + handler = self.handler('/api/accounts', value, Origin='http://attacker.example'); handler.do_POST() + handler.send_error.assert_called_once_with(403); service.assert_not_called() + handler = self.handler('/api/accounts', value); handler.do_POST() + self.assertTrue(service.return_value.request.call_args.kwargs['actor_id'].startswith('github:')) + + def test_revoked_operator_session_cannot_read_codes_or_connect(self): + with patch('forge.operator_auth.OperatorAuth') as auth, patch('forge.account_web.AccountWeb') as service: + auth.return_value.config.return_value = {'origin': 'http://127.0.0.1:8787'} + auth.return_value.session.return_value = None + for body, method in ((None, 'do_GET'), ({}, 'do_POST')): + handler = self.handler('/api/accounts', body) + getattr(handler, method)() + handler.send_error.assert_called_once_with(401) + service.assert_not_called() + + +class AccountLockTests(unittest.TestCase): + from tests.test_installation_accounts import DeviceLoginTests as Fixture + setUp = Fixture.setUp + call = Fixture.call + + def web(self): + self.call(apply=True) + config = self.setup.runtime() + with self.setup.store.transaction() as data: data['phase'] = 'active' + self.setup.save_runtime(config, active=True) + web = AccountWeb(self.root, setup=self.setup, device=self.client, clock=lambda: self.now) + view = web.view() + web.request({**{key: view[key] for key in ('generation', 'revision', 'setup_revision')}, + 'provider': 'codex', 'action': 'connect'}, actor_id='github:7') + return web + + def test_concurrent_get_waiting_on_identity_cannot_fail_tick(self): + import threading + from contextlib import contextmanager + from forge.sqlite_identity import identity_effect_lock + web = self.web() + observing, ready, proceed = threading.Event(), threading.Event(), threading.Event() + results = [] + original_call = self.client.call + def observed_call(*args, **kwargs): + if threading.current_thread().name == 'account-get': + ready.set() + if not proceed.wait(3): raise AssertionError('GET was not released') + return original_call(*args, **kwargs) + @contextmanager + def observed_lock(root): + if threading.current_thread().name == 'account-get': observing.set() + with identity_effect_lock(root): yield + with patch.object(self.client, 'call', side_effect=observed_call), \ + patch('forge.installation_accounts.identity_effect_lock', observed_lock): + thread = threading.Thread(name='account-get', target=lambda: results.append(web.view())) + thread.start() + try: + self.assertTrue(ready.wait(3), 'GET did not read its saved operation') + with identity_effect_lock(self.root): + proceed.set() + self.assertTrue(observing.wait(3), 'GET did not reach the identity lock') + web.tick() + self.assertEqual(web.saved(self.generation)['settings']['status'], 'connecting') + finally: + proceed.set() + thread.join(3) + self.assertFalse(thread.is_alive()) + self.assertEqual(results[0]['account']['code'], 'ABCD-12345') + self.assertEqual(sum(call[1] == 'create' for call in self.calls), 1) + + def test_provider_lock_contention_leaves_login_pending(self): + from forge.host_setup import login_lock + web = self.web() + with login_lock(self.root, 'codex'): web.tick() + self.assertEqual(web.saved(self.generation)['settings']['status'], 'queued') + web.tick() + self.assertEqual(web.saved(self.generation)['settings']['status'], 'connecting') + + def test_expired_login_can_be_retried_before_supervisor_observes_expiry(self): + web = self.web(); web.tick() + previous = self.setup.read()['device_logins']['codex']['id'] + self.now += 901 + view = web.view() + web.request({**{key: view[key] for key in ('generation', 'revision', 'setup_revision')}, + 'provider': 'codex', 'action': 'retry'}, actor_id='github:7') + self.assertEqual(web.saved(self.generation)['settings']['status'], 'queued') + web.tick() + self.assertNotEqual(previous, self.setup.read()['device_logins']['codex']['id']) diff --git a/tests/test_install_interview.py b/tests/test_install_interview.py new file mode 100644 index 00000000..db0bcfb2 --- /dev/null +++ b/tests/test_install_interview.py @@ -0,0 +1,106 @@ +"""Human choices preserve the same explicit intent and never apply installation.""" +from unittest import TestCase +from unittest.mock import Mock + +from forge_client.contracts import SetupError +from forge_client.github import GitHub +from forge_client.install_interview import interview + + +class InterviewTests(TestCase): + def run_interview(self, answers, *, repositories=None, ssh='anvil'): + github = Mock() + github.identity.return_value = {'id': 1, 'login': 'owner'} + github.installation_repositories.return_value = repositories or ['owner/one', 'owner/two'] + prompts, output = [], [] + iterator = iter(answers) + def ask(prompt): + prompts.append(prompt) + return next(iterator) + result = interview(ssh, github, ask=ask, tell=output.append) + self.assertEqual(next(iterator, None), None, 'Unused answers') + return result, prompts, '\n'.join(output), github + + def test_default_path_is_six_questions_and_does_not_grant_workflow_access(self): + result, prompts, output, github = self.run_interview(['', '', '1,2', '', '', '']) + self.assertEqual(len(prompts), 6) + self.assertEqual(result['providers'], [{'id': 'codex', 'kind': 'browser'}]) + self.assertEqual(result['operators'], ['owner']) + self.assertEqual(result['smoke_target'], 'scratch') + self.assertIsNone(result['host_key']) + self.assertEqual(result['hostname'], 'anvil') + self.assertEqual(result['repositories'], [ + {'name': 'owner/one', 'merge_policy': 'human', 'allow_workflow_edits': False}, + {'name': 'owner/two', 'merge_policy': 'human', 'allow_workflow_edits': False}]) + self.assertNotIn('rules_repair', result) + self.assertIn('two private test repositories', output) + self.assertIn('approval before merge', output) + self.assertIn('existing GitHub rules', output) + self.assertIn('existing known_hosts', output) + self.assertEqual([call[0] for call in github.method_calls], ['identity', 'installation_repositories']) + + def test_invalid_choices_retry_without_broadening_selection(self): + result, _, output, _ = self.run_interview([ + '', '', '100', 'other/repo', '1 1', 'one owner/two', '9', '2', 'bad-key', '', '']) + self.assertEqual(result['providers'], [{'id': 'claude', 'kind': 'browser'}]) + self.assertEqual([row['name'] for row in result['repositories']], ['owner/one', 'owner/two']) + self.assertIn('CLI before the browser handoff', output) + self.assertIn('full SHA256 fingerprint', output) + + def test_summary_edits_and_explicit_workflow_grant(self): + result, _, output, _ = self.run_interview([ + '', '', '1', '', '', '1', 'New Factory', + '5', '3', '2', '2', '6', '']) + self.assertEqual(result['name'], 'New Factory') + self.assertEqual(result['hostname'], 'new-factory') + self.assertEqual(result['repositories'][0]['merge_policy'], 'auto') + self.assertTrue(result['repositories'][0]['allow_workflow_edits']) + self.assertIn('automatic merge; workflow edits allowed', output) + self.assertIn('grant workflow-write permission', output) + + def test_editing_owner_reselects_repositories_and_smoke_target(self): + result, _, _, _ = self.run_interview([ + '', '', '1', '', '', '5', '5', '2', '6', + '2', 'elsewhere', 'new', '']) + self.assertEqual(result['owner'], 'elsewhere') + self.assertEqual(result['repositories'][0]['name'], 'elsewhere/new') + self.assertEqual(result['smoke_target'], 'scratch') + + def test_discovery_failure_still_allows_explicit_names(self): + github = Mock() + github.identity.return_value = {'login': 'owner'} + github.installation_repositories.side_effect = SetupError('github_unavailable', 'unavailable') + answers = iter(['', '', 'project', '', '', '']) + output = [] + result = interview('anvil', github, ask=lambda _: next(answers), tell=output.append) + self.assertEqual(result['repositories'][0]['name'], 'owner/project') + self.assertIn('discovery is unavailable', '\n'.join(output)) + + def test_advanced_login_methods_operators_and_pinned_host_key(self): + fingerprint = 'SHA256:' + 'a' * 43 + result, _, _, _ = self.run_interview([ + '', '', '1', '', fingerprint, '5', '2', 'owner colleague', + '4', '2', '3', '1', 'custom-network', '6', '1', 'Renamed', '']) + self.assertEqual(result['host_key'], fingerprint) + self.assertEqual(result['operators'], ['owner', 'colleague']) + self.assertEqual(result['hostname'], 'custom-network') + self.assertEqual(result['providers'], [{'id': 'codex', 'kind': 'browser'}, {'id': 'claude', 'kind': 'token'}]) + + +class RepositoryChoicesTests(TestCase): + def test_discovery_is_read_only_and_excludes_other_owners_archived_and_disabled(self): + github = GitHub(executable='gh') + owner = {'id': 2, 'login': 'owner', 'type': 'User'} + row = {'owner': {'id': 2}, 'full_name': 'owner/one', 'archived': False, 'disabled': False} + github._request = Mock(side_effect=[owner, [row, {**row, 'owner': {'id': 3}}, + {**row, 'full_name': 'owner/archived', 'archived': True}, + {**row, 'full_name': 'owner/disabled', 'disabled': True}]]) + self.assertEqual(github.installation_repositories('owner'), ['owner/one']) + self.assertEqual([call.args[0] for call in github._request.call_args_list], ['GET', 'GET']) + self.assertEqual(github._request.call_args.args[1], '/user/repos?sort=pushed&per_page=100') + + def test_org_repositories_use_authenticated_org_inventory(self): + github = GitHub(executable='gh') + github._request = Mock(side_effect=[{'id': 2, 'login': 'org', 'type': 'Organization'}, []]) + self.assertEqual(github.installation_repositories('org'), []) + self.assertEqual(github._request.call_args.args[1], '/orgs/org/repos?sort=pushed&per_page=100') diff --git a/tests/test_install_replan.py b/tests/test_install_replan.py index 6b5d5bcc..02104902 100644 --- a/tests/test_install_replan.py +++ b/tests/test_install_replan.py @@ -9,7 +9,7 @@ from forge_client.cli import main, parser, execute as cli_execute from forge_client.contracts import SetupError, digest from forge_client.install import Installation -from forge_client.installation import Install, execute, interview as wizard +from forge_client.installation import Install, execute from forge_client.workflow import Journal from tests import test_install_coordinator as coordinator from tests.test_install_coordinator import interview, REVISION @@ -169,19 +169,3 @@ def test_successful_checks_hide_remediation_and_repository_labels_use_names(self self.assertNotIn('repository.42', output) self.assertIn('open https://github.com/owner/project', output) self.assertNotIn('Apply with:', output) - - def test_interview_explains_supervisor_policy_without_protection_or_repair_choice(self): - events = [] - answers = iter(['', '', '', 'owner/one', 'auto', '', '', '', '', '', '']) - github = Mock(); github.identity.return_value = {'login': 'owner'} - def ask(prompt): events.append(('ask', prompt)); return next(answers) - with patch('forge_client.installation.shutil.which', return_value=None): - result = wizard('anvil', github, ask=ask, tell=lambda line: events.append(('tell', line))) - self.assertNotIn('rules_repair', result) - self.assertNotIn('github_protection', result['repositories'][0]) - self.assertFalse(any('Rules repair' in text for kind, text in events if kind == 'ask')) - for explanation, question in (('private GitHub App', 'GitHub App owner'), - ('Human merge policy', 'merge policy ['), - ('first-merge test', 'Smoke target')): - self.assertLess(next(i for i, (kind, text) in enumerate(events) if kind == 'tell' and explanation in text), - next(i for i, (kind, text) in enumerate(events) if kind == 'ask' and question in text)) diff --git a/tests/test_install_server_handoff.py b/tests/test_install_server_handoff.py index 9148cc7b..4c1c6d0a 100644 --- a/tests/test_install_server_handoff.py +++ b/tests/test_install_server_handoff.py @@ -68,6 +68,35 @@ def test_capability_hands_off_after_identity_before_codex_or_repository_work(sel self.assertEqual(saved['providers'], [{'id': 'codex', 'kind': 'browser'}]) self.assertNotIn('github_protection', saved['repositories'][0]) + def test_unconfirmed_handoff_keeps_cli_resume_and_adopts_lost_reply(self): + factory = self.server() + original = factory.call.side_effect + def lose_reply(action, **parameters): + result = original(action, **parameters) + if action == 'prepare': + raise SetupError('connection_lost', 'Reply lost') + return result + factory.call.side_effect = lose_reply + with self.assertRaises(SetupError): + self.install.apply() + saved = self.journal.read()['server_preparation'] + self.assertFalse(saved['registered']) + result = self.install.status() + self.assertFalse(result['web_owned']) + self.assertIsNone(result['setup_url']) + self.assertEqual(result['next_action'], ['forge', 'install', '--ssh', 'anvil', '--resume']) + from forge_client.installation import display + lines = []; display(result, tell=lines.append) + self.assertNotIn('You can close this terminal', '\n'.join(lines)) + self.assertIn('Setup still needs this CLI', '\n'.join(lines)) + factory.call.side_effect = original + result = self.install.apply() + self.assertTrue(result['web_owned']) + self.assertIsNone(result['next_action']) + self.assertEqual(sum(call.args[0] == 'prepare' for call in factory.call.call_args_list), 1) + lines = []; display(result, tell=lines.append) + self.assertIn('You can close this terminal', '\n'.join(lines)) + def test_operator_attention_never_replays_retired_rule_repairs(self): factory = self.server(); self.install.apply() factory.prepare_repository.assert_not_called() diff --git a/tests/test_installation_accounts.py b/tests/test_installation_accounts.py index 552ac5e2..36660b75 100644 --- a/tests/test_installation_accounts.py +++ b/tests/test_installation_accounts.py @@ -213,6 +213,23 @@ def test_explicit_retry_reconnects_a_completed_but_removed_login(self): self.assertEqual(retried['status'], 'account_login_pending') self.assertNotEqual(retried['session_id'], completed['session_id']) + def test_explicit_reconnect_replaces_a_stored_but_expired_account_once(self): + self.call(apply=True); self.finish(); completed = self.call(apply=True) + self.assertEqual(self.call()['status'], 'connected') + replacement = self.call(apply=True, retry=True, reconnect=True) + self.assertNotEqual(replacement['session_id'], completed['session_id']) + with self.assertRaises(SetupError): self.call(apply=True, retry=True, reconnect=True) + self.assertEqual(sum(call[1] == 'create' for call in self.calls), 2) + + def test_reconnect_preserves_configured_models(self): + self.call(apply=True); self.finish(); self.call(apply=True) + config = self.setup.runtime() + config['provider_pool'][0]['model'] = 'gpt-5.4' + self.setup.save_runtime(config, active=False) + self.call(apply=True, retry=True, reconnect=True) + self.finish(); self.call(apply=True) + self.assertEqual(self.setup.runtime()['provider_pool'][0]['model'], 'gpt-5.4') + def test_lost_create_reply_reconciles_the_same_owned_container(self): original = self.client.run def lost(argv, **kw): diff --git a/ui/app/components/CodexAccountDialog.vue b/ui/app/components/CodexAccountDialog.vue new file mode 100644 index 00000000..bab81378 --- /dev/null +++ b/ui/app/components/CodexAccountDialog.vue @@ -0,0 +1,70 @@ + + diff --git a/ui/app/components/HarnessCard.vue b/ui/app/components/HarnessCard.vue index 843fd9dd..e80af51b 100644 --- a/ui/app/components/HarnessCard.vue +++ b/ui/app/components/HarnessCard.vue @@ -6,7 +6,7 @@ import { accountAnchor, type AccountAlert } from '~/utils/accounts' // page-level (contracts §3.7), so the error notice stays on the page and // never moves in here. // `alert`: this account's live health problem from the board poll, if any. -const props = defineProps<{ harness: Harness; activity?: SetupActivity | null; alert?: AccountAlert | null }>() +const props = defineProps<{ harness: Harness; activity?: SetupActivity | null; alert?: AccountAlert | null; browser?: boolean; operation?: string }>() const emit = defineEmits<{ open: [harness: Harness] }>() const line = computed(() => harnessLine(props.harness)) @@ -29,8 +29,11 @@ const BADGE = { sign_in_expired: 'Signed out', quota: 'Usage limit reached', una

{{ alert.title }} {{ alert.description }}

{{ line }} - - {{ alert.actionLabel }} + + {{ operation === 'verifying' ? 'Verifying…' : 'Sign-in progress' }} + + + {{ browser ? alert.actionLabel : 'CLI instructions' }} - {{ state === 'verify' ? 'Verify connection' : 'Connect' }} + {{ browser ? (state === 'verify' ? 'Verify connection' : 'Connect') : 'CLI instructions' }} diff --git a/ui/app/components/HarnessDialog.vue b/ui/app/components/HarnessDialog.vue index 7eb7e1ee..616f4028 100644 --- a/ui/app/components/HarnessDialog.vue +++ b/ui/app/components/HarnessDialog.vue @@ -62,15 +62,15 @@ async function copy(kind: 'login' | 'check' | 'token') {