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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions docs/code/advanced-settings.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,19 @@ Files you want to keep and show in the dashboard are registered separately as ru
| `DEVINTERN_TELEMETRY_DISABLED=1` | Nothing |
| `{ "analytics": { "enabled": false } }` in `~/.devintern/settings.json` | One anonymous `analytics_opt_out` event, then nothing |

**Setup events.** While you run `devintern init` or `devintern worker init`, the CLI also sends one anonymous event per setup step, so we can see where people stop. Every event from one run shares a random `setup_id` (new for each run, not tied to you, your repository, or your account). Events carry only step names, the tracker and agent type, pass/fail results, short result codes (for example `agent_missing` or `git_missing`), durations, and yes/no flags (for example whether you took the default tracker). They never include repository names, URLs, queries, paths, email addresses, or tokens.

| Event | Sent when |
| --------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
| `setup_started`, `worker_init_started` | Setup opens |
| `setup_step` | A step finishes: host checks, tracker chosen, credential check, query check, sign-in, service install, first task started |
| `setup_completed`, `worker_init_completed` | Setup finishes |
| `setup_failed`, `setup_declined`, `worker_init_failed` | Setup stops on a problem or you decline to continue, with the last step reached |
| `setup_abandoned` | You leave setup with Ctrl+C or by closing input, with the last step reached |
| `task_run`, `worker_task_run` | A task run ends; they also say whether it opened a pull request |

`DEVINTERN_TELEMETRY_DISABLED=1` turns all of these off.

See [devintern.com/privacy](https://devintern.com/privacy/).

## Prompt overrides
Expand Down
1 change: 1 addition & 0 deletions packages/code/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,7 @@ Everything under the output directory is a write-only debug artifact. Durable st
- **@mention runs** (`review/mention-trigger.ts`): the fleet mention handler passes the triggering comment or review as `address-review --mention <issue_comment|review_comment|review>:<id>`; the GitHub review adapter re-fetches it and addresses it as feedback (plus any `changes_requested` review), so mentions work on human PRs with no reviews. Relay `pr.review_submitted` on a non-agent PR goes to `relay/mention-handlers.ts` (mention in the body or line comments only); the sweep's third feed reads review bodies of recently updated open PRs. Relay and sweep share `processed_events` ids (`github:mentions` / `comment:<id>`, `review:<id>`); a review body is marked addressed as `review_body`. The relay holds an in-flight claim on that id while its run is going, and the sweep skips (and holds its cursor before) a claimed mention instead of joining the run. The relay acquirer dispatches envelopes in the background (serialized per PR/task/change, `relay/cursor-window.ts` commits the cursor only past settled envelopes), so one long run never holds envelopes for other subjects. `isBotAuthored` (Bot users, `[bot]` logins, bot aliases, `<!-- devintern` markers) guards every path against self-triggering
- **PR-job subprocess output** (`observability/child-output.ts`): while the worker log capture is active, address-review / resolve-conflicts / CI-fix / auto-merge children are piped and forwarded line by line through the console with a `[<subcommand> <pr-url>]` prefix, so their output reaches `worker.stdout.log`/`worker.stderr.log`; without a capture (manual runs) they inherit stdio
- **`worker init` steps** (`init/worker-init-steps.ts`): the wizard (`runWorkerInit`, `InputSource` `prompt`) and `--non-interactive` (`runNonInteractiveWorkerInit`, `flags`) run the same ordered `WORKER_INIT_STEPS` (host, tracker, workspace, query, settings, save, license, relay, github-app, readiness, service). `host` (`init/worker-init-host.ts`) runs only in the wizard, when `checkHost` is injected (the CLI does): it reports the agent CLI, git, and service manager before the first question, and the readiness and service steps do not repeat what it reported; flags mode reports the same harness check with its readiness checks and lists host problems first in its text output only. Each step is one function that branches only where its input or output differs; shared run state and the outcome both summaries read live in `init/worker-init-run.ts`, the later steps in `init/worker-init-activation.ts`, and flags-mode validation/atomic writes in `init/worker-init-noninteractive-plan.ts`. The wizard saves each answer in its own step (a stopped wizard keeps them); flags mode validates everything, writes once in `save`, and rolls back when an input check fails. Change a step there so both modes follow. A wizard step may return `{ back: "<step id>" }` to re-run from an earlier step (`run.revisit` names it); the query step does this after a credential or repository-access failure, and the tracker step then re-asks the current tracker's settings (`init/worker-init-tracker.ts`). The wizard's license, relay, and github-app steps print as one "Sign in with GitHub" step with at most one question: relay pairing starts with `noWait` and `init/worker-init-github-app-wait.ts` polls the pending GitHub pairing (Enter skips). Flags mode leaves pairing to `worker login`: `init/worker-sign-in-followup.ts` (injected into `account/cli.ts` from `worker/cli.ts`, which avoids an `account` → `init` import cycle) runs `worker connect --no-wait --json` after a sign-in and installs the service when `worker init --start` left `state/code/start-after-sign-in.json` (`worker/start-intent.ts`)
- **Onboarding funnel events** (`observability/setup-funnel.ts`, `observability/analytics.ts`): PostHog funnels are built on these names, so treat them as a public contract: never rename one, and add a step instead of repurposing it. One random `setup_id` per setup run (`beginSetupFunnel`: `runInit` always opens a fresh one, `runWorkerInit` and `worker init --non-interactive` join an open one or open their own; the opener closes it) rides on every event of the run; it is never derived from a path, repo, or account. Existing events that already mark a step carry `setup_id` + `funnel_step` (`setup_started`/`worker_init_started` → `init_started`; `setup_completed`/`worker_init_completed` → `completed`; `setup_failed`/`worker_init_failed` → `failed`; `setup_declined` and a declined host check → `declined`). Everything else is `setup_step` with `funnel_step` one of `host_checked`, `tracker_chosen`, `credentials_checked`, `query_checked`, `sign_in`, `service_install`, `first_task_started` (plus `first_pr_opened`, below), each with `outcome` (`passed`/`failed`/`skipped`/`started`) and a `reason` code from `FunnelReason`. `setup_abandoned` (Ctrl+C, closed input, too many invalid answers) carries `last_step`, the last progress step reached; `trackFunnelStep` is a no-op outside a setup run, so shared code (the tracker picker, the sign-in step) stays silent elsewhere. "First PR" is `task_run`/`worker_task_run` with `pr_opened: true` (set by `markPullRequestOpened` where the PR is created); the try-mode foreground run joins the setup through `DEVINTERN_SETUP_ID` (UUID only), and "second task" is a second `worker_task_run` per anonymous id. A new property must be added to `ALLOWED_PROP_KEYS` and `tests/setup-funnel.test.ts`; values are enums, booleans, or numbers, never free text (repo names, URLs, queries, paths, emails, tokens). Tests assert the sequences with `setAnalyticsCaptureForTests`
- **Standalone binary (`bun build --compile`) is not supported yet**: the CLI compiles and `--version`/`--help`/`bun:sqlite`/spawning agent CLIs from `PATH` work, but in a compiled binary `process.argv[1]` is the virtual `/$bunfs/root/<name>` and `process.execPath` is the binary itself. Every `spawn(process.execPath, [process.argv[1], ...])` self-respawn (task polling, PR jobs, automations, estimation, retries) and the service `ExecStart`/`ProgramArguments` built from `runtimePath` + `execPath` then pass `/$bunfs/root/<name>` as the first user argument. Files resolved from `import.meta.dir`/`import.meta.url` (dashboard UI, `prompts/`, `catalog/`) land under `/$bunfs` and are not found unless embedded, and `detectInstallKind` returns `unknown`, so auto-update is skipped. Install via Bun (`scripts/install.sh`) until those paths learn a compiled mode
- **Workspace worker composition** (`workspace/workspace-worker.ts`): `runWorkspaceWorker` only orders startup steps; the pieces live in `worker-startup.ts` (env, preflight, pickup gate), `worker-startup-recovery.ts` (tracker settings migration, then orphan recovery, both before any acquirer is built), `worker-maintenance.ts` (sweepers), `worker-sources.ts` / `worker-scheduled-acquirers.ts` / `fleet-event-acquirers.ts` (acquirers), and `worker-reload.ts` (reload gate and reloader). Every component follows reloads and shutdown through the `WorkerRuntime` registry (`worker-runtime.ts`): read the live `config` in a closure (never copy a reloadable value at construction), re-pace with `onPollIntervalChange`, reconcile with `onConfigApplied`, and release what it opened with `onStop` (hooks run once, in reverse registration order). A setting that cannot follow reloads goes in `STARTUP_ONLY_SETTINGS` (`worker-reload.ts`) and gets an edit in `tests/worker-reload.test.ts`. New worker modules import from `fleet-executor`/`fleet-event-acquirers`, never from `workspace-worker`
- **MCP server and proposals** (`lib/mcp/`, `lib/proposals/`, `state/proposals.ts`): `devintern mcp` serves stdio MCP (`@modelcontextprotocol/sdk`, zod schemas); it is dispatched in `src/index.ts` before the update check and legacy migration because stdout is the JSON-RPC channel, and it routes `console.log` to stderr. Read tools call `readWorkerDocument` (`worker/dashboard-read-cli.ts`), the same function behind `worker <runs|stats|...> --json`, so never add a parallel query path there. `get_workspace_config` swaps inline `env` values and URL credentials for `__DEVINTERN_SECRET_<n>__` placeholders (`proposals/workspace-text.ts`); `propose_workspace_change` restores them against the file whose sha256 is `baseHash`, so a proposal is only accepted against the current file. Queue-control tools (`lib/mcp/task-tools.ts`: `get_task`, `update_task`, `cancel_task`, `clear_harness_limit`) act directly and wrap the same functions as `worker task show|update`, `worker cancel`, and `worker harness clear-limit`, audited as `cli`. Delegation tools (`lib/mcp/delegation-tools.ts`) also act directly: `delegate_task` runs `runWorkerAdd` with `--json` (its `agent` option carries harness/model/effort), refused when `[mcp] allow_direct_delegation = false` (`workspace/mcp-settings.ts`, read per call); `wait_for_tasks` is `waitForTaskKeys` from `worker wait` with the deadline capped at 600 s; `list_my_tasks` reads `InjectedTaskStore.listMatching` via `workspace/delegated-tasks.ts`. Proposals are rows in the `assistant_proposals` table of `queue.db`; apply is human-only (`worker proposals apply`), claims the row once (`pending` → `applying`), and goes through `writeFileAtomic` + the `.worker.config-state.json` reload record (config), `runWorkerAdd` (task), or the running worker's `POST /api/automations/:id/run` (automation). The stored config text holds real secrets: only `toProposalView` (diff + hash) may leave the process
Expand Down
2 changes: 2 additions & 0 deletions packages/code/src/lib/agent/run-harness-git.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { isFinalPrDeliveryAttempt, MAX_PR_DELIVERY_ATTEMPTS } from "../task/acti
import { loadProjectSettings } from "../config/project-settings";
import { applyActionedTransition } from "../task/actioned-transition";
import { recordRunPr, recordRunPrFailure } from "../state/run-recorder";
import { markPullRequestOpened } from "../observability/setup-funnel";
import { parseGitHubPrUrl, recordAgentPrFromUrl } from "../state/worker-state";
import type { TaskTrackerClient } from "../trackers/client";
import type { Task } from "../../types/task-tracker";
Expand Down Expand Up @@ -411,6 +412,7 @@ export function createGitHelpers(ctx: FinalizeContext) {

// Register the PR so worker review-polling watches it automatically.
if (prResult.url) {
markPullRequestOpened();
recordAgentPrFromUrl(prResult.url, branchForPr, taskKey, prResult.changeRequest);
const runChange = prResult.changeRequest
? {
Expand Down
14 changes: 14 additions & 0 deletions packages/code/src/lib/cli/prompt-abort.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import { PromptAttemptsExceededError } from "@devintern/task-trackers";
import type { FunnelReason } from "../observability/analytics";

/** `cause` of the abort error a prompt session raises for Ctrl+C. */
const INTERRUPT_CAUSE = "SIGINT";

Expand Down Expand Up @@ -48,3 +51,14 @@ export function markPromptAbortReported(error: unknown): void {
export function isPromptAbortReported(error: unknown): boolean {
return typeof error === "object" && error !== null && reportedPromptAborts.has(error);
}

/**
* The allowlisted funnel code for a wizard that ended because the person left
* (Ctrl+C, closed input, or too many invalid answers); undefined for any other error.
*/
export function abandonReasonFor(error: unknown): FunnelReason | undefined {
if (isPromptInterrupt(error)) return "prompt_interrupted";
if (isPromptAbort(error)) return "input_closed";
if (error instanceof PromptAttemptsExceededError) return "too_many_invalid_answers";
return undefined;
}
35 changes: 21 additions & 14 deletions packages/code/src/lib/init/agent-reuse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,24 @@ export interface AgentReuseOffer {
defaultProblem: "missing" | "not-signed-in";
}

/**
* Why the default agent (Claude Code) is not usable, or null when it works,
* cannot be told apart from working, or the configuration is explicit (any
* `AGENT_HARNESS` or CLI path override is the user's own choice).
*/
export function defaultAgentProblem(
env: Env,
deps: AgentReuseDeps = {},
): AgentReuseOffer["defaultProblem"] | null {
if (env.AGENT_HARNESS?.trim() || env.AGENT_CLI_PATH?.trim()) return null;
const which = deps.which ?? defaultWhich;
const fallback = AGENTS[0];
if (!fallback) return null;
const defaultCommand = cliCommand(fallback, env);
if (!which(defaultCommand, env)) return "missing";
return signInOf(fallback, defaultCommand, env, deps) === "not-signed-in" ? "not-signed-in" : null;
}

/**
* An alternative to offer, or null when the configuration is explicit, the
* default agent works (or cannot be told apart from working), or no other
Expand All @@ -183,22 +201,11 @@ export interface AgentReuseOffer {
* @param env - The worker's environment (process env plus the workspace `.env`).
*/
export function findAgentReuseOffer(env: Env, deps: AgentReuseDeps = {}): AgentReuseOffer | null {
// Any explicit choice, including a CLI path override, is the user's.
if (env.AGENT_HARNESS?.trim() || env.AGENT_CLI_PATH?.trim()) return null;
const defaultProblem = defaultAgentProblem(env, deps);
if (!defaultProblem) return null;
const which = deps.which ?? defaultWhich;
const [fallback, ...others] = AGENTS;
if (!fallback) return null;
const defaultCommand = cliCommand(fallback, env);
let defaultProblem: AgentReuseOffer["defaultProblem"];
if (!which(defaultCommand, env)) {
defaultProblem = "missing";
} else if (signInOf(fallback, defaultCommand, env, deps) === "not-signed-in") {
defaultProblem = "not-signed-in";
} else {
return null;
}
const ready: ReadyAgent[] = [];
for (const agent of others) {
for (const agent of AGENTS.slice(1)) {
const command = cliCommand(agent, env);
if (!which(command, env)) continue;
if (signInOf(agent, command, env, deps) === "signed-in") {
Expand Down
17 changes: 15 additions & 2 deletions packages/code/src/lib/init/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,14 @@ import {
createPromptAttempts,
} from "@devintern/task-trackers";
import { hasHelpArg } from "../cli/help";
import { isPromptAbort, promptAbortReason } from "../cli/prompt-abort";
import { flushAnalytics, trackSetupCompleted, trackSetupStarted } from "../observability/analytics";
import { abandonReasonFor, isPromptAbort, promptAbortReason } from "../cli/prompt-abort";
import {
flushAnalytics,
trackSetupAbandoned,
trackSetupCompleted,
trackSetupStarted,
} from "../observability/analytics";
import { beginSetupFunnel, endSetupFunnel } from "../observability/setup-funnel";
import { findWorkspaceRepoForCheckout } from "../workspace/manual-run";
import { migrateLegacyCheckout } from "../workspace/migrate-checkout";
import type { ManualWorkspaceRun } from "../workspace/manual-run";
Expand Down Expand Up @@ -160,6 +166,8 @@ export async function runInit(deps: InitCommandDeps = {}): Promise<number> {
const cwd = deps.cwd ?? process.cwd();
const log = deps.log ?? console.log;
const interactive = deps.interactive ?? isInteractive(process.argv, process.stdin);
// One random id per run groups its funnel events; `worker init` below joins it.
beginSetupFunnel({ fresh: true });
try {
await migrateLegacyCheckout(cwd);
const registered = await findWorkspaceRepoForCheckout({ cwd });
Expand All @@ -185,6 +193,9 @@ export async function runInit(deps: InitCommandDeps = {}): Promise<number> {
}
return typeof process.exitCode === "number" ? process.exitCode : 0;
} catch (error) {
const abandoned = abandonReasonFor(error);
// The caller flushes before exiting; this only queues the event.
if (abandoned) await trackSetupAbandoned(abandoned);
if (isPromptAbort(error)) {
log(`\n❌ ${promptAbortReason(error)}; setup stopped. Re-run \`devintern init\`.`);
return 1;
Expand All @@ -194,6 +205,8 @@ export async function runInit(deps: InitCommandDeps = {}): Promise<number> {
return 1;
}
throw error;
} finally {
endSetupFunnel();
}
}

Expand Down
10 changes: 9 additions & 1 deletion packages/code/src/lib/init/try-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ import {
HEADLESS_AGENT_STDIO,
} from "../agent/spawn";
import { isAutomatedEnvironment } from "../config/env-detector";
import { SETUP_ID_ENV } from "../observability/analytics";
import { funnelProps } from "../observability/setup-funnel";
import { gitStatusPorcelain } from "./try-git";
import type { TryDeps } from "./try-mode";

Expand Down Expand Up @@ -89,13 +91,19 @@ export async function runReadOnlyScan(input: {
return stdout;
}

/** The environment for the run, plus the setup id so its outcome event joins the funnel. */
function childEnv(): NodeJS.ProcessEnv {
const setupId = funnelProps("first_task_started").setup_id;
return setupId ? { ...process.env, [SETUP_ID_ENV]: setupId } : process.env;
}

/** Spawn this CLI on one task file with the terminal attached; resolves to its exit code. */
export function runForegroundTask(input: { cwd: string; taskPath: string }): Promise<number> {
return new Promise((resolve, reject) => {
const child = spawn(
process.execPath,
[...process.execArgv, process.argv[1] as string, input.taskPath, "--create-pr"],
{ cwd: input.cwd, stdio: "inherit", env: process.env },
{ cwd: input.cwd, stdio: "inherit", env: childEnv() },
);
child.on("error", reject);
child.on("close", (code) => resolve(code ?? 1));
Expand Down
Loading
Loading