introsio 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -6,6 +6,67 @@ project uses [semantic versioning](https://semver.org/).
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [0.5.0] - Unreleased draft
10
+
11
+ Run `int setup` again after updating, then `int doctor`, to refresh the installed
12
+ hook engine. Managed execution requires an authorized host and an eligible server
13
+ rollout; vendor adapters currently retain manual launch.
14
+
15
+ ### Added
16
+ - Local runner identity (`int runner init|status`), explicit project checkout
17
+ links (`int project link|inspect|verify`) and provider discovery (`int agent list`).
18
+ - Managed attempt inspection and reconciliation (`int workspace list|reconcile`),
19
+ pinned worktrees, durable attempt/process journals and conservative recovery.
20
+ - File activity reporting (`int workspace watch`) with independent reporting
21
+ sessions and workspace provenance.
22
+ - Immutable committed checkpoints, structured handovers and explicit protected
23
+ checkpoint publication through trusted host APIs.
24
+ - A protocol-v2 runner transport and trusted host loop that waits outside the
25
+ model, checks capabilities, fetches exact dependency commits and retains work
26
+ when authority or process termination is uncertain.
27
+ - Packaged managed-workspace and release guides, standalone GitHub CI and an npm
28
+ trusted-publishing workflow in the CLI mirror.
29
+
30
+ ### Changed
31
+ - Worker execution procedures use server-issued sessions, fenced attempt identity
32
+ and stable request IDs for retries. Managed input hooks use integration evidence.
33
+ - README installation, update instructions and command reference describe current
34
+ capabilities. Service architecture links work from npm and the GitHub mirror.
35
+ - npm publishing moves to the standalone repository so provenance matches package
36
+ metadata; monorepo release tags validate without publishing.
37
+
38
+ ### Fixed
39
+ - Standalone clone tests use an Execute toolset snapshot, checked against the
40
+ server contract when running inside the monorepo.
41
+
42
+ ## [0.4.0]
43
+
44
+ Parallel agents on one project. Run `int setup` again after updating: the
45
+ installed hook engine is versioned, and `int doctor` reports one that is behind.
46
+ New hook features are on by default; `int disable shared-tree | inputs | wait`
47
+ turns one off.
48
+
49
+ ### Added
50
+ - Parallel agents (README "Parallel agents"):
51
+ - `int worktree add <name>` / `list` / `remove`: one folder (git worktree) per
52
+ agent, on branch `agent/<name>`; `list` shows which agent works where, and
53
+ `remove` refuses while a live agent holds a task there or files are uncommitted.
54
+ - `shared-tree` hook: a claim in a folder another live agent session is working
55
+ in is refused once, naming `int worktree add`.
56
+ - `inputs` hook: after a claim, the dependency branches the task's starting point
57
+ lacks, with the merge command.
58
+ - `wait` hook and `int wait <retryAfter>`: when other workers hold all the ready
59
+ work, the agent waits (at most 4 minutes per call) and claims again instead of
60
+ stopping; one stop is sent back.
61
+ - `/introsio-execute` merges the branches of the tasks a task builds on before it
62
+ starts, records `outcome.branch` in local mode too, waits on `all_claimed` /
63
+ `awaiting_completion`, and describes the final integration task.
64
+
65
+ ### Changed
66
+ - `int mode` / `int gate` are repository-wide: set inside a linked worktree they
67
+ apply to the main checkout and every worktree, and `int gate run` runs in the
68
+ worktree you are in.
69
+
9
70
  ## [0.3.0]
10
71
 
11
72
  Run `int setup` again after updating: the installed hook engine is versioned, and
package/README.md CHANGED
@@ -1,16 +1,18 @@
1
- # int — connect any coding agent to Introsio
1
+ # Introsio CLI - connect coding agents to Introsio
2
2
 
3
3
  One command connects your coding agents to Introsio, gives them
4
4
  `/introsio-execute` for running a Developer Mode project, `/introsio-pause` and
5
5
  `/introsio-resume` for stopping anywhere and continuing exactly, and installs
6
6
  hooks that keep Introsio in step with what the agent actually did.
7
7
 
8
+ [npm package](https://www.npmjs.com/package/introsio) | [GitHub](https://github.com/introsio/Introsio-cli) | [Changelog](CHANGELOG.md)
9
+
8
10
  ## Install
9
11
 
10
- Needs Node 18 or newer and one or more coding agents.
12
+ Needs Node 18 or newer and one or more coding agents. Worktree and managed workspace commands also need Git 2.31 or newer. The npm package is `introsio`; it provides both `int` and `introsio` commands.
11
13
 
12
14
  ```bash
13
- npx introsio setup # try it once, nothing stays installed
15
+ npx introsio@latest setup # run setup without a global npm install
14
16
  ```
15
17
 
16
18
  ```bash
@@ -42,15 +44,37 @@ hook engine to `~/.introsio/kit`, so the hooks never depend on this checkout.
42
44
  | VS Code (Copilot) | user `mcp.json` | prompt file | none |
43
45
  | Windsurf | `mcp_config.json` | `int print-execute` / `print-pause` / `print-resume` → paste as workflows | none |
44
46
 
45
- **Signing in.** No key is stored anywhere. Each agent signs in through its own MCP
46
- OAuth flow (Introsio supports dynamic client registration and PKCE). `setup` tells
47
+ **Signing in.** Setup does not ask for an API key. Each agent signs in through its own MCP
48
+ OAuth flow (Introsio supports dynamic client registration and PKCE) and manages its own credentials. `setup` tells
47
49
  you the exact step for each agent, for example `/mcp` in Claude Code or
48
50
  `codex mcp login introsio`.
49
51
 
52
+ ## Run a project
53
+
54
+ Create a Developer Mode project and its plan in [Introsio](https://introsio.app), then sign in through your coding agent. From your repository:
55
+
56
+ ```bash
57
+ int doctor
58
+ int gate set "npm test" # use the check command for your repository
59
+ ```
60
+
61
+ In the agent, run `/introsio-execute <project name or id>` (Codex: `/prompts:introsio-execute`). Use `/introsio-pause` before stopping and `/introsio-resume` to continue. Windsurf users can copy the procedure with `int print-execute`.
62
+
63
+ ## Update
64
+
65
+ ```bash
66
+ npm install -g introsio@latest
67
+ int setup
68
+ int doctor
69
+ ```
70
+
71
+ For an npx-only installation, run `npx introsio@latest setup` again. Setup copies a versioned hook engine onto this computer; updating the npm package alone does not replace those installed hooks. Restart or reload your agent after setup.
72
+
50
73
  ## How it works
51
74
 
52
75
  The agent runs a project with the server's loop: `claimTask` → work → `completeTask`
53
- with an outcome (ADR-0008). The hooks never call Introsio themselves; they have no
76
+ with an outcome ([execution protocol](https://github.com/RASAPALLI-MAHESH/Introsio/blob/main/docs/adr/0008-agent-execution-protocol.md)).
77
+ The command procedures register a protocol-v2 worker session, retain the server-issued attempt identity and use stable claim/completion request IDs when retrying a lost response. Worker credentials stay out of outcomes, handoffs and repository files. The hooks never call Introsio themselves; they have no
54
78
  credential. They watch the agent's own Introsio calls and make sure it finishes
55
79
  the loop.
56
80
 
@@ -96,6 +120,9 @@ The hooks also include the following checks. Each one can be switched off
96
120
  | `reread` | Refuses once a context read the agent already has, or a schedule read straight after `nowReady` |
97
121
  | `log` | `~/.introsio/log.jsonl`, summed up by `int stats` |
98
122
  | `pause` | Snapshots the working tree when a task is paused, and checks the repository against a pause before it is resumed (below) |
123
+ | `shared-tree` | Refuses once a claim in a folder another live agent session is working in, naming `int worktree add` (below); the second claim goes through |
124
+ | `inputs` | After a claim, names each dependency branch (`inputs[].outcome.branch`) the task's starting point does not contain yet, with the merge command |
125
+ | `wait` | When other workers hold all the ready work (`all_claimed`), tells the agent to `int wait` and claim again, and sends one stop back |
99
126
 
100
127
  The gates and git guards only act in sessions that have used Introsio, and only
101
128
  on tasks that session claimed. Completing a personal task, or pushing in a repo
@@ -176,6 +203,60 @@ the lease to expire. Completing the task removes its snapshot;
176
203
  Tests: `test/pause.test.js` (real git repositories, the real hook script), and the
177
204
  server's `backend-node/src/tests/agentPause.test.js`.
178
205
 
206
+ ## Parallel agents
207
+
208
+ Several agents can run one project at the same time — any mix of Claude Code,
209
+ Codex, Cursor and the rest. Introsio's server hands each ready task to exactly one
210
+ worker (an atomic claim), passes each task the outcomes of the tasks it builds on,
211
+ and orders the work so the longest chain starts first. For projects using the manual branch workflow, four rules
212
+ keep the agents from getting in each other's way:
213
+
214
+ 1. **One folder per agent.** Two agents in one working tree share one branch and
215
+ one set of files: a `git switch` by one moves the other's next commit, `git add
216
+ -A` takes the other's half-done files, and every test run sees the other's
217
+ unfinished code. Give each agent its own git worktree:
218
+
219
+ ```bash
220
+ int worktree add w2 # ../<repo>-w2 on branch agent/w2
221
+ ```
222
+
223
+ ```bash
224
+ int worktree list # every worktree and the agent working in it
225
+ ```
226
+
227
+ ```bash
228
+ int worktree remove w2 # once its work is merged; the branch is kept
229
+ ```
230
+
231
+ All worktrees share the repository, so a branch made in one is visible in the
232
+ others, and `int mode` / `int gate` (set once, anywhere) apply to all of them —
233
+ a worktree with settings of its own keeps them. Untracked files (`node_modules`,
234
+ `.env`) are not copied, and a dev server needs its own port per worktree.
235
+ The `shared-tree` hook refuses, once, a claim made in a folder another live
236
+ agent is working in.
237
+ 2. **Start from the code you build on.** A task's dependencies may still be on
238
+ their own branches. `/introsio-execute` merges each `inputs[].outcome.branch`
239
+ before the work starts (github mode: off the default branch; local mode: into the
240
+ current branch), and records `outcome.branch` in both modes so the tasks after it
241
+ can do the same. The `inputs` hook names any branch that is still missing, with
242
+ the command.
243
+ 3. **Wait, don't quit.** When every ready task is held by another worker, claimTask
244
+ answers `all_claimed` with `retryAfter`. The agent runs `int wait <retryAfter>`
245
+ (at most 4 minutes per call) and claims again — a task finished early unlocks the
246
+ next ones at once. The `wait` hook sends a stop back once; after an hour the
247
+ agent reports what is still held and stops.
248
+ 4. **End with integration.** A plan with parallel work ends with one task that
249
+ depends on every task nothing else depends on: it merges all their branches,
250
+ runs the whole test suite and fixes what breaks between the pieces.
251
+
252
+ The server enforces the account's current worker limits. Tests: `test/parallel.test.js`.
253
+
254
+ ### Managed execution
255
+
256
+ Managed integration projects use pinned attempt workspaces and verified artifact inputs. Their trusted runner prepares the reserved base and exact dependency commits; manual branch-merging instructions above apply to the manual workflow. The `inputs` hook directs managed tasks to their runner.
257
+
258
+ The CLI supports runner registration, explicit project linking, provider discovery, attempt inspection and file activity reporting. Vendor adapters currently require manual launch; the trusted host APIs support execution and waiting outside the model. Read [Managed attempt workspaces](docs/managed-workspaces.md) for setup, authentication, checkpoint publication, recovery and current rollout limits.
259
+
179
260
  ## Edge cases (researched, reproduced, fixed)
180
261
 
181
262
  Each of these was first reproduced against the earlier kit, then fixed, and is kept
@@ -209,6 +290,10 @@ as a regression test in `test/edgecases.test.js` (same numbers).
209
290
  | R24 | On Windows, git (`C:/…`), Node (`C:\…`) and temp folders (`MAHESH~1`) spell one folder three ways, so `int mode` / `int gate` settings were never found by the hooks and edited files looked "outside" the repo (found on the first Windows run) | One canonical spelling (`canonicalPath` / `repoKey` in `lib/paths.mjs`, case-insensitive on Windows) for every settings key and file comparison; CI now runs on Windows, macOS and Linux |
210
291
  | R25 | `git push --all origin` went through: the guard skipped `--all`, which pushes every local branch, the default one included | `--all` / `--branches` are refused in github mode; `--tags` still passes |
211
292
  | R26 | `bash -c "git push origin main"` (or a wrapped commit of a key) went through: the quoted script was one word with no `git` in it | `sh`/`bash`/`zsh`/`dash`/`ksh -c` and `eval` scripts are checked like the bare command (behind `env`/`sudo` prefixes, nested up to 3 levels) for both the push guard and the secrets check |
293
+ | R27 | Two agents started in one checkout overwrote each other's branch and committed each other's files | `shared-tree` refuses, once, a claim in a folder another live session holds a task in; `int worktree add` gives each agent its own (`test/parallel.test.js`) |
294
+ | R28 | `int mode` / `int gate` set in the main checkout did nothing inside a linked worktree (its path is another settings key) | Settings are looked up for the worktree, then for the repository's main checkout (`git rev-parse --git-common-dir`); the CLI writes them repository-wide |
295
+ | R29 | A task whose dependency sat on an unmerged branch started from the default branch without that code | `/introsio-execute` merges `inputs[].outcome.branch` first; the `inputs` hook names each missing branch with its merge command |
296
+ | R30 | A parallel worker that found every ready task taken stopped for good, leaving the rest to one agent | claimTask's `all_claimed` → `int wait` and claim again; the `wait` hook sends one stop back. The server answers `all_claimed` (retry now) when every task it tried was won by workers claiming at the same moment, instead of a misleading "nothing can start" |
212
297
 
213
298
  Tested end to end with Claude Code 2.1.312 (headless `claude -p`, a stub Introsio
214
299
  MCP server over stdio, the installed hooks):
@@ -228,7 +313,16 @@ int gate set "<cmd>" [--timeout <sec>] | gate off | gate run | gate
228
313
  int features | enable <name> | disable <name>
229
314
  int claims | claims clear
230
315
  int paused [--prune [--days 30]]
316
+ int worktree add <name> [--base <ref>] [--branch <b>] [--dir <path>] | worktree list | worktree remove <name> [--force]
317
+ int wait <seconds | ISO time> [--max 240]
231
318
  int stats [--since 7d] [--project <id>] [--json]
319
+ int project link <id> --root <repo> --repository <owner/name>
320
+ int project inspect|verify <id> [--json]
321
+ int runner init|status [--json]
322
+ int agent list [--json]
323
+ int workspace list|reconcile [--json]
324
+ int workspace watch <attempt> [--provider codex] [--api <base-url>] [--once] [--new-session]
325
+ int version
232
326
  int print-execute | print-pause | print-resume
233
327
  ```
234
328
 
@@ -237,9 +331,8 @@ int print-execute | print-pause | print-resume
237
331
  repo-relative paths.
238
332
  - `--toolset` chooses which Introsio tools the agents load, and is remembered.
239
333
  `developer` (the default) plans and executes. `execute` is the slim set for
240
- running a plan that already exists — the 13 tools of the claim → complete loop,
241
- pause / resume and the hand-off, about a third of the tool definitions an agent
242
- carries on every turn. It cannot create or edit a plan; switch back with
334
+ running a plan that already exists, including worker sessions, the execution loop,
335
+ workspace/artifact tools, pause / resume and the hand-off. It cannot create or edit a plan; switch back with
243
336
  `int setup --toolset developer`.
244
337
  - `--url` points the agents at another MCP server, such as a local backend; it is
245
338
  remembered.
@@ -248,7 +341,30 @@ int print-execute | print-pause | print-resume
248
341
 
249
342
  ## Layout
250
343
 
344
+ `int runner init` creates one local runner identity in
345
+ `~/.introsio/runner/registry.json`. `int runner status --json` reads it for
346
+ scripts. Initialization is safe to repeat and returns the same ID across
347
+ processes. Keep the registry with the host's local state when restoring it.
348
+
251
349
  - `cli.mjs` — the `int` command
350
+ - `runner/agentRegistry.mjs` — local runner identity and registry
351
+ - `runner/projectLinks.mjs` — explicit local GitHub checkout links, validated before use
352
+ - `runner/workspaceJournal.mjs` — durable attempt identity and provisioning journal
353
+ - `runner/workspaceManager.mjs` — internal authorized pinned-commit worktree provisioning and read-only recovery inspection
354
+ - `runner/providers/` — provider capability discovery, explicit manual launch/stop fallback, checkpoint and resume interface
355
+ - `runner/workspaceRecovery.mjs` — conservative reconciliation; unknown or superseded authority retains all work
356
+ - `runner/workspaceResources.mjs` — private per-attempt resource directories, allowlisted process environment and loopback socket reservations
357
+ - `runner/runnerTransport.mjs` — stateless authenticated MCP client and private protocol-v2 worker session; refuses legacy execution and unexpected endpoint/attempt changes.
358
+ - `runner/processJournal.mjs` — unresolved process launch journal blocks automatic relaunch after a crash without trusting persisted PIDs.
359
+ - `runner/supervisedProcess.mjs` — internal trusted executable supervision, timeout, cancellation and repeated lease checks. Windows termination is best effort; Job Objects, crash-time process containment, and provider-specific authentication are not certified. No automatic headless launch is exposed.
360
+
361
+ `int workspace reconcile --json` performs offline read-only reconciliation. Without a verified server transport, all authority is unknown and no work is removed. Port reservations remain exclusive only until released; providers must handle bind collisions. Resource directories are not OS confinement.
362
+
363
+ `int agent list --json` reports local provider availability without executing providers or inspecting their credentials. No headless provider is certified yet.
364
+
365
+ `int workspace list --json` inspects managed attempts. No force removal or automatic cleanup is offered. Provisioning is an internal API requiring a verified server-authorization adapter; the CLI deliberately cannot provision from an untrusted local packet. Worktrees isolate indices and files, not OS permissions. Windows directory ACL hardening and authenticated remote integration are separate release gates.
366
+
367
+ Local linking (no remote API call, fetch, checkout or push): `int project link <projectId> --root <checkout> --repository <owner/name>`. Use `int project verify <projectId>` to revalidate origin and local Git metadata. A link is not server authorization; provisioning must also validate the authorized repository identity and pinned commit. Existing links are never silently replaced. Git 2.31+ is required.
252
368
  - `agents/<agent>.mjs` — one adapter per agent: detect, connect, command, hooks, uninstall, status
253
369
  - `hook/introsio-hook.mjs` → `normalize.mjs` (each agent's payload into one shape) → `engine.mjs` (the decisions) → `respond.mjs` (each agent's output format)
254
370
  - `hook/features/*.mjs` — one pure module per feature
@@ -261,29 +377,15 @@ Tests: `npm test` in this folder. They use plain
261
377
  Hook formats follow each agent's documentation as of October 2026. Agents change
262
378
  these often: run `int doctor` after updating an agent.
263
379
 
264
- ## Publishing a release (maintainers)
265
-
266
- The package is `introsio` on npm (commands `int` and `introsio`).
380
+ ## Contributing and releases
267
381
 
268
- 1. Bump `version` in `package.json` and describe the release in `CHANGELOG.md` (`int doctor` tells users on older hooks to re-run `int setup`), and merge.
269
- 2. Add the repository secret `NPM_TOKEN` once (an npm Automation token that may publish `introsio`).
270
- 3. Tag the release; `.github/workflows/agent-kit-release.yml` runs the tests, checks the tag against the version, and publishes with provenance:
382
+ Edit the CLI in the Introsio monorepo's `agent-kit/` folder. The standalone
383
+ [Introsio-cli repository](https://github.com/introsio/Introsio-cli) mirrors that
384
+ folder. Both checkouts can run `npm test` without installing dependencies.
271
385
 
272
- ```bash
273
- git tag agent-kit-v0.3.0 && git push origin agent-kit-v0.3.0
274
- ```
275
-
276
- To publish by hand instead: `npm login`, then `npm publish` from this folder (the tests run first via `prepublishOnly`).
277
-
278
- The code is edited only in the Introsio monorepo's `agent-kit/` folder. The
279
- standalone [Introsio-cli](https://github.com/introsio/Introsio-cli) repository is
280
- a mirror of that folder, updated from the monorepo root (never edited directly):
281
-
282
- ```bash
283
- git fetch cli
284
- git subtree split --prefix=agent-kit -b cli-only
285
- git push cli cli-only:main
286
- ```
386
+ See [Releasing to GitHub and npm](docs/releasing.md) for the local review checks,
387
+ mirror update, version tags and publishing workflow. npm publishes run from the
388
+ standalone repository so provenance matches the package's repository URL.
287
389
 
288
390
  ## License
289
391
 
package/cli.mjs CHANGED
@@ -11,13 +11,19 @@ import { Writer, nodePathOf, COMMANDS, commandText } from './agents/common.mjs';
11
11
  import { FEATURES, MODES, loadConfig, saveConfig, repoSettings, updateRepo, featureOn } from './lib/config.mjs';
12
12
  import { MAX_GATE_TIMEOUT_SEC } from './hook/features/gates.mjs';
13
13
  import { createGit } from './lib/git.mjs';
14
- import { homeDir, introsioDir, kitDir, logPath, configPath } from './lib/paths.mjs';
14
+ import { homeDir, introsioDir, kitDir, logPath, configPath, canonicalPath } from './lib/paths.mjs';
15
15
  import { readText } from './lib/jsonFile.mjs';
16
16
  import { loadOtherSessions, clearSessions } from './hook/state.mjs';
17
17
  import { summarize } from './hook/features/log.mjs';
18
18
  import { runGateCommand } from './hook/features/gates.mjs';
19
19
  import { listLocalPauses, removeLocalPause } from './hook/features/pause.mjs';
20
20
  import { sessionIsLive } from './hook/features/workerId.mjs';
21
+ import { treeKey, WAIT_STEP_SEC } from './hook/features/parallel.mjs';
22
+ import { readRunner, registerRunner } from './runner/agentRegistry.mjs';
23
+ import { linkProject, readProjectLink, verifyProjectLink } from './runner/projectLinks.mjs';
24
+ import { listWorkspaces } from './runner/workspaceManager.mjs';
25
+ import { reconcileWorkspaces } from './runner/workspaceRecovery.mjs';
26
+ import { discoverProviders } from './runner/providers/index.mjs';
21
27
 
22
28
  const KIT_SOURCE = path.dirname(fileURLToPath(import.meta.url));
23
29
  const DEFAULT_URL = 'https://api.introsio.app/mcp?toolset=developer';
@@ -191,12 +197,21 @@ function uninstall(flags) {
191
197
  out('Your settings and log in ~/.introsio stay; delete that folder to remove them too.');
192
198
  }
193
199
 
194
- function repoRoot(flags) {
195
- const root = createGit(path.resolve(typeof flags.repo === 'string' ? flags.repo : '.')).root();
200
+ /**
201
+ * The working tree a command runs in (`root`) and the repository's main checkout
202
+ * (`settingsRoot`, where `int mode` / `int gate` are kept): the same folder in an
203
+ * ordinary checkout; inside a linked worktree the settings stay repository-wide, so
204
+ * every parallel agent's worktree follows them.
205
+ */
206
+ function repoRoots(flags) {
207
+ const git = createGit(path.resolve(typeof flags.repo === 'string' ? flags.repo : '.'));
208
+ const root = git.root();
196
209
  if (!root) throw new Error('not inside a git repository (use --repo <dir>)');
197
- return path.resolve(root);
210
+ return { root: path.resolve(root), settingsRoot: path.resolve(git.mainRoot() ?? root), git };
198
211
  }
199
212
 
213
+ const repoRoot = (flags) => repoRoots(flags).settingsRoot;
214
+
200
215
  function status(flags) {
201
216
  const ctx = context(flags);
202
217
  out(`int ${VERSION} — hook engine ${fs.existsSync(ctx.hookScript) ? `installed at ${ctx.kitInstallDir}` : 'NOT installed (run int setup)'}`);
@@ -209,9 +224,10 @@ function status(flags) {
209
224
  const config = loadConfig(undefined, { strict: true });
210
225
  out('');
211
226
  out(`Features: ${Object.keys(FEATURES).map((name) => `${name}${featureOn(config, name) ? '' : ' (off)'}`).join(', ')}`);
212
- const root = createGit(process.cwd()).root();
227
+ const here = createGit(process.cwd());
228
+ const root = here.root();
213
229
  if (root) {
214
- const settings = repoSettings(config, root);
230
+ const settings = repoSettings(config, root, here.mainRoot());
215
231
  out(`This repo (${root}): mode ${settings.mode ?? 'auto (github if the project is linked to GitHub, else local)'} · test gate ${settings.gate ? `"${settings.gate}" (${settings.gateTimeoutSec}s)` : 'off'}`);
216
232
  }
217
233
  if (String(process.env.INTROSIO_HOOKS ?? '').toLowerCase() === 'off') out('INTROSIO_HOOKS=off is set in this shell — hooks do nothing here.');
@@ -238,7 +254,8 @@ function mode(positional, flags) {
238
254
 
239
255
  async function gate(positional, flags) {
240
256
  const action = positional[1];
241
- const root = repoRoot(flags);
257
+ // Settings are the repository's; `gate run` runs where you are (a worktree runs its own files).
258
+ const { settingsRoot: root, root: workRoot } = repoRoots(flags);
242
259
  const config = loadConfig(undefined, { strict: true });
243
260
  const settings = repoSettings(config, root);
244
261
  if (action === 'set') {
@@ -256,8 +273,8 @@ async function gate(positional, flags) {
256
273
  out(`${root}: test gate off`);
257
274
  } else if (action === 'run') {
258
275
  if (!settings.gate) return fail('no gate set — int gate set "<command>"');
259
- out(`Running "${settings.gate}" in ${root} …`);
260
- const result = await runGateCommand(settings.gate, root, settings.gateTimeoutSec);
276
+ out(`Running "${settings.gate}" in ${workRoot} …`);
277
+ const result = await runGateCommand(settings.gate, workRoot, settings.gateTimeoutSec);
261
278
  out(result.output);
262
279
  out(result.ok ? `✓ passed in ${Math.round(result.ms / 1000)}s` : result.timedOut ? `✗ timed out after ${settings.gateTimeoutSec}s` : `✗ failed (exit ${result.code})`);
263
280
  if (!result.ok) process.exitCode = 1;
@@ -352,6 +369,95 @@ function paused(flags) {
352
369
  }
353
370
  }
354
371
 
372
+ const WORKTREE_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
373
+
374
+ /**
375
+ * `int worktree add|list|remove`: one folder per parallel agent. Two agents in one
376
+ * working tree share one HEAD, index and set of files; a linked worktree gives each
377
+ * its own, while all of them share the repository — so a dependency's branch made in
378
+ * one worktree can be merged in another, and `int mode` / `int gate` apply to all.
379
+ */
380
+ function worktree(positional, flags) {
381
+ const action = positional[1] ?? 'list';
382
+ const { settingsRoot, git } = repoRoots(flags);
383
+ const now = Date.now();
384
+ const liveIn = (dir) => loadOtherSessions('', now).filter((session) => session.root === treeKey(dir) && sessionIsLive(session, now));
385
+
386
+ if (action === 'add') {
387
+ const name = positional[2];
388
+ if (!name || !WORKTREE_NAME.test(name)) return fail('usage: int worktree add <name> [--base <ref>] [--branch <name>] [--dir <path>] — a name of letters, digits, ".", "_" or "-"');
389
+ const branch = typeof flags.branch === 'string' ? flags.branch : `agent/${name}`;
390
+ const dir = path.resolve(typeof flags.dir === 'string' ? flags.dir : path.join(path.dirname(settingsRoot), `${path.basename(settingsRoot)}-${name}`));
391
+ if (fs.existsSync(dir)) return fail(`${dir} already exists — choose another name, or --dir <path>`);
392
+ const base = typeof flags.base === 'string' ? flags.base : 'HEAD';
393
+ const existing = git.localBranchExists(branch);
394
+ const args = existing ? ['worktree', 'add', dir, branch] : ['worktree', 'add', '-b', branch, dir, base];
395
+ const result = git.run(args, { timeout: 120_000 });
396
+ if (!result.ok) return fail(`git ${args.join(' ')} failed: ${result.err || result.out}`);
397
+ const settings = repoSettings(loadConfig(undefined, { strict: true }), settingsRoot);
398
+ out(`Created ${dir} on branch ${branch}${existing ? ' (it already existed)' : ` from ${base}`}.`);
399
+ out('Start one agent in that folder (cd there, open the agent, run /introsio-execute <project>). Every worktree shares this repository, so');
400
+ out('a branch one agent makes can be merged by the next.');
401
+ out('Untracked files are not copied: install dependencies there (e.g. npm install) and copy any .env it needs; give each worktree its own port if the app runs a server.');
402
+ out(`Settings: mode ${settings.mode ?? 'auto'}, test gate ${settings.gate ? `"${settings.gate}"` : 'off'} — the repository's, in every worktree.`);
403
+ out(`When its work is merged: int worktree remove ${name}`);
404
+ return;
405
+ }
406
+
407
+ if (action === 'remove' || action === 'rm') {
408
+ const target = positional[2];
409
+ if (!target) return fail('usage: int worktree remove <name | path> [--force]');
410
+ const linked = git.worktrees().slice(1);
411
+ const wanted = canonicalPath(path.resolve(target));
412
+ const match = linked.find((entry) => canonicalPath(entry.path) === wanted)
413
+ ?? linked.find((entry) => path.basename(entry.path) === `${path.basename(settingsRoot)}-${target}` || entry.branch === `agent/${target}` || entry.branch === target);
414
+ if (!match) return fail(`no worktree "${target}" — int worktree list shows them (the main checkout is never removed)`);
415
+ const busy = liveIn(match.path).find((session) => Object.keys(session.claims ?? {}).length > 0);
416
+ if (busy && !flags.force) {
417
+ return fail(`a live ${busy.agent ?? 'agent'} session (workerId ${busy.workerId ?? '?'}) still holds a task in ${match.path} — let it finish or pause first (--force removes it anyway)`);
418
+ }
419
+ const result = git.run(['worktree', 'remove', ...(flags.force ? ['--force'] : []), match.path], { timeout: 120_000 });
420
+ if (!result.ok) return fail(`${result.err || result.out} — commit or stash the work there first (--force throws it away)`);
421
+ out(`Removed ${match.path}.${match.branch ? ` Branch ${match.branch} is kept — merge it, or delete it with git branch -d ${match.branch}.` : ''}`);
422
+ return;
423
+ }
424
+
425
+ if (action === 'list' || action === 'ls') {
426
+ const entries = git.worktrees();
427
+ for (const [index, entry] of entries.entries()) {
428
+ const sessions = liveIn(entry.path);
429
+ out(`${index === 0 ? 'main' : ' '} ${entry.path} ${entry.branch ?? '(detached HEAD)'}${sessions.length > 1 ? ` ⚠ ${sessions.length} live agent sessions share this folder` : ''}`);
430
+ for (const session of sessions) {
431
+ const held = Object.values(session.claims ?? {});
432
+ out(` ${session.agent ?? 'agent'} (workerId ${session.workerId ?? '?'})${held.length ? ` on ${held.map((claim) => `"${claim.title}"`).join(', ')}` : ', no task held'}`);
433
+ }
434
+ }
435
+ if (entries.length <= 1) out('Only the main checkout. Give each parallel agent its own folder: int worktree add <name>');
436
+ return;
437
+ }
438
+ return fail('usage: int worktree add <name> | list | remove <name>');
439
+ }
440
+
441
+ /**
442
+ * `int wait <seconds | ISO time>`: what an agent runs when claimTask answers that
443
+ * other workers hold the ready work. Waits until then, but at most --max seconds
444
+ * (WAIT_STEP_SEC by default, under agents' shell-tool time limits), so the agent
445
+ * claims again at least that often — a task finished early unlocks work at once.
446
+ */
447
+ async function wait(positional, flags) {
448
+ const value = positional[1];
449
+ const max = flags.max !== undefined ? Number(flags.max) : WAIT_STEP_SEC;
450
+ if (!(max > 0) || max > 600) return fail('--max takes 1 to 600 seconds');
451
+ let until = Date.now() + max * 1000;
452
+ if (value !== undefined) {
453
+ until = /^\d+(\.\d+)?$/.test(value) ? Date.now() + Number(value) * 1000 : Date.parse(value);
454
+ if (!Number.isFinite(until)) return fail('usage: int wait <seconds | ISO time — e.g. the retryAfter claimTask gave> [--max <seconds>]');
455
+ }
456
+ const ms = Math.max(0, Math.min(until - Date.now(), max * 1000));
457
+ await new Promise((resolve) => { setTimeout(resolve, ms); });
458
+ out(`Waited ${Math.round(ms / 1000)}s. Now call claimTask { projectId, workerId } again.`);
459
+ }
460
+
355
461
  function parseSince(value) {
356
462
  const match = String(value ?? '').match(/^(\d+)([hdw])$/);
357
463
  if (!match) return null;
@@ -472,6 +578,24 @@ function doctor(flags) {
472
578
  if (problems) process.exitCode = 1;
473
579
  }
474
580
 
581
+ async function runner(positional, flags) {
582
+ const action = positional[1];
583
+ if (!['init', 'status'].includes(action) || positional.length !== 2) {
584
+ return fail('usage: int runner init|status [--json]');
585
+ }
586
+ const record = action === 'init' ? await registerRunner() : readRunner();
587
+ if (flags.json) return out(JSON.stringify({ registered: Boolean(record), ...record }));
588
+ if (!record) return out('Local runner is unregistered. Run int runner init.');
589
+ return out(`Local runner ${record.runnerId} on ${record.hostname} (${record.platform}/${record.arch})`);
590
+ }
591
+
592
+ async function projectLink(positional, flags) {
593
+ const [, action, id] = positional;
594
+ if (positional.length !== 3 || !['link', 'inspect', 'verify'].includes(action)) return fail('usage: int project link <id> --root <repo> --repository <owner/name> | inspect|verify <id>');
595
+ const record = action === 'link' ? await linkProject({ id, root: flags.root, repository: flags.repository }) : action === 'verify' ? verifyProjectLink(id) : readProjectLink(id);
596
+ return out(JSON.stringify(record ?? { linked: false }, null, flags.json ? 0 : 2));
597
+ }
598
+
475
599
  function help() {
476
600
  out(`int ${VERSION} — the Introsio agent kit: connect coding agents to Introsio and keep it updated while they execute
477
601
 
@@ -486,6 +610,18 @@ function help() {
486
610
  int claims | claims clear tasks your agents hold on this computer
487
611
  int stats [--since 7d] [--project <id>] [--json]
488
612
  int paused [--prune [--days 30]] work paused or interrupted on this computer, and how to resume it
613
+ int project link <id> --root <repo> --repository <owner/name>
614
+ int project inspect|verify <id> [--json]
615
+ int agent list [--json] discover supported manual coding-agent adapters
616
+ int workspace list|reconcile [--json] inspect managed attempts without deleting work
617
+ int runner init|status [--json] create or inspect this computer's local runner identity
618
+
619
+ int worktree add <name> [--base <ref>] [--branch <b>] [--dir <path>]
620
+ a folder of its own for one more parallel agent (branch agent/<name>)
621
+ int worktree list | remove <name> [--force]
622
+ int workspace watch <attempt> [--provider codex] [--api <base-url>] [--once] [--new-session]
623
+ int wait <seconds | ISO time> [--max 240]
624
+ what an agent runs when other workers hold the ready work, before claiming again
489
625
  int print-execute | print-pause | print-resume
490
626
  a command's procedure, to paste where an agent has no commands
491
627
 
@@ -517,6 +653,22 @@ async function run(command, positional, flags) {
517
653
  case 'claims': return claims(positional);
518
654
  case 'stats': return stats(flags);
519
655
  case 'paused': return paused(flags);
656
+ case 'runner': return runner(positional, flags);
657
+ case 'project': return projectLink(positional, flags);
658
+ case 'agent': {
659
+ if (positional.length !== 2 || positional[1] !== 'list') return fail('usage: int agent list [--json]');
660
+ return out(JSON.stringify(discoverProviders(), null, flags.json ? 0 : 2));
661
+ }
662
+ case 'workspace': {
663
+ if (positional[1] === 'watch') {
664
+ const { watchManagedActivity } = await import('./runner/managedActivity.mjs');
665
+ return out(JSON.stringify(await watchManagedActivity(positional[2], flags)));
666
+ }
667
+ if (positional.length !== 2 || !['list','reconcile'].includes(positional[1])) return fail('usage: int workspace list|reconcile [--json]');
668
+ return out(JSON.stringify(positional[1] === 'reconcile' ? await reconcileWorkspaces() : listWorkspaces(), null, flags.json ? 0 : 2));
669
+ }
670
+ case 'worktree': case 'worktrees': return worktree(positional, flags);
671
+ case 'wait': return wait(positional, flags);
520
672
  case 'print-execute': case 'print-pause': case 'print-resume': {
521
673
  const chosen = COMMANDS.find((item) => item.name === `introsio-${command.slice('print-'.length)}`);
522
674
  return out(commandText(context(flags), chosen, chosen.name === 'introsio-execute' ? 'the project the user names' : 'what the user names'));
@@ -0,0 +1,65 @@
1
+ # Managed attempt workspaces
2
+
3
+ These optional tools accompany the [agent setup and execution hooks](../README.md).
4
+ The CLI can link and inspect local state; provisioning and execution require an
5
+ authenticated trusted host. Current vendor adapters expose manual launch, and
6
+ live provider/staging acceptance remains pending.
7
+
8
+ ## Inspect local runner state
9
+
10
+ Run these from a terminal, replacing the project, checkout and repository values:
11
+
12
+ ```bash
13
+ int runner init
14
+ int project link PROJECT_ID --root /absolute/repository --repository OWNER/REPO
15
+ int project verify PROJECT_ID
16
+ int agent list --json
17
+ int workspace list --json
18
+ int workspace reconcile --json
19
+ ```
20
+
21
+ Use a Git 2.31+ checkout with the expected GitHub `origin`. Linking validates local
22
+ Git metadata and does not fetch, push or authorize remote execution. Existing
23
+ links are not silently replaced. `reconcile` is read-only; unknown authority
24
+ retains all work. There is no CLI provisioning, automatic launch or cleanup command.
25
+
26
+ ## Immutable checkpoints and handover
27
+
28
+ Before completing a managed task, a trusted executor can call its `captureArtifact({ handover, inputArtifactIds, publish })` callback. Commit the task's changes in the attempt worktree first. The handover requires a `summary` and accepts lists of `interfaces`, `decisions`, `verification` and `remaining` items. An optional `supersedes` ID records a rewritten checkpoint.
29
+
30
+ Local capture is the default. Pass `publish: true` to publish the exact committed SHA to a protected checkpoint branch. GitHub publication requires an active checkpoint ruleset on the linked repository. The runner verifies the branch tip and owned range, and retries reconcile the existing checkpoint. See [ADR-0019](https://github.com/RASAPALLI-MAHESH/Introsio/blob/main/docs/adr/0019-immutable-task-artifacts.md).
31
+
32
+ When the project selects a Phase 7 repository verification policy, checkpoint publication also requires the server's trusted workflow/credential preflight. The runner refuses changes to `.github/` and policy-protected source paths before pushing, preserving the local checkpoint for review. Candidate refs are independently checked by the server before publication and advancement. See [ADR-0022](https://github.com/RASAPALLI-MAHESH/Introsio/blob/main/docs/adr/0022-server-verification-engine.md) for the conservative supported CI profile and setup requirements.
33
+
34
+ ## Live file activity
35
+
36
+ With a task claimed in a prepared workspace, run `int workspace watch ATTEMPT_ID --provider codex` in another terminal. The collector reads `INTROSIO_ACTIVITY_ACCESS_TOKEN` from the host environment and registers an independently authenticated reporting session. Keep this credential outside model context. `--api` selects an HTTPS API base or loopback development endpoint. `--once` sends a single scan. After renewing a retired login, use `--new-session` to replace its reporting grant and retain the old pending metadata.
37
+
38
+ Execute → Agents shows sessions, last heartbeats, local commit observations and staged/unstaged file metadata. Observations have workspace provenance because people and other processes may also edit the files. The collector excludes known secret/generated paths and ignored files, batches filesystem notifications, rescans periodically and replays its journaled pending snapshot after a lost response. It sends metadata about at most 200 files per observation. Reporting credentials are omitted from CLI output.
39
+
40
+ The local runner stores its registry and attempt journals under `~/.introsio/runner` (or `INTROSIO_HOME/runner`). Link a project explicitly with `int project link PROJECT_ID --root /absolute/repository --repository OWNER/REPO`. Use `int runner init`, `int agent list` and `int workspace list|reconcile` to inspect local capabilities and retained attempts.
41
+
42
+ Trusted host integrations create a transport with `createRunnerTransport({ getAccessToken })`, open a project-scoped `openRunnerSession`, and call `runWorkerOnce` with a trusted executor. The server issues a private worker credential, authorizes the exact attempt and pins the linked repository commit. `runWorkspaceProcess` provides native executable supervision for a locally trusted adapter. Vendor adapters report manual launch capability. Workspaces are retained when authority is unavailable or termination is uncertain.
43
+
44
+ For managed integration runs, trusted hosts can use `runWorkerLoop` from `runner/runnerLoop.mjs`. Register actual capability tags, declared resources and launch/resume support in `openRunnerSession({ transport, projectId, profile })`, then pass the adapter's capabilities and executor to the loop. The host waits through `waitForWork` outside the model and launches only after a fresh claim. It fetches exact dependency SHAs and preserves the attempt's reserved base. Cancellation, idle timeout and offline retries are bounded. The executor must call the supplied `completeTask` and receive server confirmation to finish; otherwise the runner retains a checkpoint for review. Unsupported adapters return `manual_action_required`. See [ADR-0021](https://github.com/RASAPALLI-MAHESH/Introsio/blob/main/docs/adr/0021-dependency-scheduling-and-worker-wake.md).
45
+
46
+ The collector uses the same attempt journal and verifies repository, branch and base history before each scan. Reporting credentials stay in private local state and are removed from workspace listings. Integrations can supply `activityClient({ accessToken: async () => ... })` with a rotating credential source.
47
+
48
+ Hard CPU/RAM/disk isolation, supervision of escaped processes and provider-specific authentication require OS or provider adapters. Review retained work before removing any workspace.
49
+
50
+ ## Verification, integration and delivery
51
+
52
+ Managed tasks reserve an exact integration base and dependency artifacts. A local
53
+ test report or successful process exit does not establish server CI verification,
54
+ integration or delivery. The service verifies candidate-specific evidence before
55
+ advancing the shared integration ref. Delivery requires a separate owner-approved
56
+ plan and fresh server checks.
57
+
58
+ The production service defaults to observation mode. New managed work depends on
59
+ the deployment stage, project enrollment and owner pause state. Publishing this
60
+ CLI or running `int setup` does not change those settings. Existing uncertain
61
+ remote operations are reconciled while local attempt work is retained. See the
62
+ [managed execution rollout ADR](https://github.com/RASAPALLI-MAHESH/Introsio/blob/main/docs/adr/0025-managed-execution-release.md)
63
+ and [operations runbook](https://github.com/RASAPALLI-MAHESH/Introsio/blob/main/docs/runbooks/managed-execution-release.md)
64
+ for service release evidence and recovery.
65
+