tr-plugin-meta-harness 0.3.0 → 0.5.26
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/DESIGN.md +86 -0
- package/README.md +257 -11
- package/capability/BRICK.md +1 -1
- package/capability/index.mjs +154 -13
- package/cli.mjs +426 -41
- package/package.json +15 -3
- package/plugin.json +1457 -119
- package/skills/meta-harness/SKILL.md +63 -25
- package/src/adoption.mjs +102 -0
- package/src/agent-user.mjs +194 -0
- package/src/alerts.mjs +220 -14
- package/src/cascade.mjs +185 -0
- package/src/chat.mjs +80 -0
- package/src/codex-models.mjs +54 -0
- package/src/compat-harness.mjs +114 -0
- package/src/control.mjs +145 -0
- package/src/coordinator.mjs +267 -358
- package/src/dispatch-request.mjs +76 -0
- package/src/dispatch.mjs +119 -0
- package/src/documentation-authority.mjs +57 -0
- package/src/documentation.mjs +120 -32
- package/src/executor.mjs +101 -22
- package/src/gate-adapters/agy.mjs +155 -0
- package/src/gate-adapters/claude.mjs +303 -0
- package/src/gate-adapters/cline.mjs +111 -0
- package/src/gate-adapters/codex.mjs +164 -0
- package/src/gate-adapters/cursor.mjs +164 -0
- package/src/gate-adapters/devin.mjs +116 -0
- package/src/gate-adapters/dsh.mjs +284 -0
- package/src/gate-adapters/grok.mjs +112 -0
- package/src/gate-adapters/hermes.mjs +217 -0
- package/src/gate-adapters/hook-files.mjs +156 -0
- package/src/gate-adapters/index.mjs +131 -0
- package/src/gate-adapters/openclaw-plugin/gate-client.js +205 -0
- package/src/gate-adapters/openclaw-plugin/index.js +25 -0
- package/src/gate-adapters/openclaw-plugin/openclaw.plugin.json +9 -0
- package/src/gate-adapters/openclaw-plugin/package.json +15 -0
- package/src/gate-adapters/openclaw.mjs +288 -0
- package/src/gate-adapters/pi.mjs +146 -0
- package/src/gate.mjs +18 -0
- package/src/harness-updates.mjs +170 -0
- package/src/included-usage.mjs +344 -0
- package/src/jobs.mjs +135 -0
- package/src/json-reply.mjs +22 -0
- package/src/learner.mjs +97 -67
- package/src/maintenance.mjs +18 -0
- package/src/mcp-server.mjs +228 -0
- package/src/model-catalog.mjs +195 -0
- package/src/model-selection.mjs +67 -0
- package/src/paths.mjs +23 -0
- package/src/pool.mjs +69 -0
- package/src/process-manager.mjs +246 -0
- package/src/process-worker.mjs +18 -0
- package/src/reasoning.mjs +231 -0
- package/src/remote-operation.mjs +76 -0
- package/src/review.mjs +241 -0
- package/src/reviews.mjs +25 -0
- package/src/router-benchmark-corpus.mjs +16 -0
- package/src/router-benchmark.mjs +208 -0
- package/src/router.mjs +265 -346
- package/src/runtime.mjs +30 -8
- package/src/session/claude.mjs +358 -0
- package/src/session/codex.mjs +501 -0
- package/src/session/result.mjs +90 -0
- package/src/session/resume.mjs +393 -0
- package/src/session/run.mjs +258 -0
- package/src/session-jobs.mjs +77 -0
- package/src/setup.mjs +6 -3
- package/src/ssss-store.mjs +20 -0
- package/src/telemetry.mjs +267 -0
- package/src/termination.mjs +28 -0
- package/src/threads.mjs +150 -0
- package/src/usage-queue.mjs +137 -0
- package/src/verify-ssss.mjs +102 -0
- package/src/worker.mjs +955 -84
- package/src/worktree.mjs +244 -0
- package/ui/chunks/adapter-docs-freshness.md +16 -0
- package/ui/chunks/chat-handoff.md +26 -0
- package/ui/chunks/fleet-maintenance.md +21 -0
- package/ui/chunks/harness-inventory.md +21 -0
- package/ui/chunks/included-access.md +18 -0
- package/ui/chunks/included-usage-verification.md +15 -0
- package/ui/chunks/independent-review.md +17 -0
- package/ui/chunks/managed-execution.md +20 -0
- package/ui/chunks/official-documentation.md +18 -0
- package/ui/chunks/quota-recovery.md +21 -0
- package/ui/chunks/review-routing-decision.md +16 -0
- package/ui/chunks/route-work.md +18 -0
- package/ui/chunks/routing-evidence.md +18 -0
- package/ui/chunks/run-ledger.md +18 -0
- package/ui/chunks/session-controls.md +16 -0
- package/ui/home.js +198 -0
- package/ui/DESIGN.md +0 -32
- package/ui/card.js +0 -845
|
@@ -1,37 +1,75 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: meta-harness
|
|
3
|
-
description: Discover,
|
|
3
|
+
description: Discover, route, coordinate, review and run coding agent harnesses through Total Recall across mesh nodes.
|
|
4
|
+
version: 0.5.25
|
|
4
5
|
repo_scoped: false
|
|
5
6
|
---
|
|
6
7
|
|
|
7
|
-
#
|
|
8
|
+
# Metaharness
|
|
8
9
|
|
|
9
|
-
|
|
10
|
+
Coordinates coding agent harnesses across mesh nodes. `cli-agents` is an alias of `meta-harness`. Run `total-recall meta-harness --help` for flags.
|
|
10
11
|
|
|
11
|
-
##
|
|
12
|
-
1. **
|
|
13
|
-
2. **
|
|
14
|
-
3. **
|
|
15
|
-
4. **
|
|
12
|
+
## Rules
|
|
13
|
+
1. **Believe the status words.** `ready` was proved by a login probe. `unverified` has no probe, so only a completed run proves it. `needs_auth`, `blocked` and `exhausted` cannot take work; the reason is in `quotaNote` and in `excluded`.
|
|
14
|
+
2. **No figure without a source.** `benchmarks` shows only fetched figures with their source and time. A dash means nobody measured it. Adapter quality and cost scores are configured priors, not measurements.
|
|
15
|
+
3. **Code is written through `route --execute`, `coordinate --execute` or race**, each on its own `meta-harness/...` branch. Nothing merges into your branch; review it and merge it yourself. `dispatch` keeps edits only with `permissions: {"read": true, "write": true}`; without it the agent works in a disposable checkout and its edits are discarded. The first line dispatch prints to stderr says which (`edits`).
|
|
16
|
+
4. **Use the calling harness's native background function.** Give it `total-recall meta-harness orchestrate "<task>" --execute --json` as one command. The command returns the final result and exit status to that background task. Executed `route` and `coordinate`, and `dispatch`, `fork` and `resume`, also return terminal results by default. `--background` (or `--background true`) explicitly detaches for callers that need only a job ID; `--background false` stays attached. `dispatch --stdin` reads JSON `{agent, cwd, prompt, timeoutMs?}`. An attached or remote dispatch runs 5 minutes and a local detached one 60 minutes unless `timeoutMs` changes it; the limits are 90 minutes for a detached or terminal/background-task call (the host passes its timer as TR_PLUGIN_TIMEOUT_MS) and 9 minutes otherwise. Pipeline implementer stages run up to 60 minutes and other stages 15. `resume` and `fork` keep the saved job's deadline, and `--timeout-ms` overrides it within the same limits. Use `cancel <job>` to stop a job and preserve changed work on its branch.
|
|
17
|
+
5. **Check the outcome, not the status word.** `running` says the process is alive. A job whose process is gone reads `failed` with `failureKind: lost`. Work is done when the result is `ok`, the branch holds the commit and the gate passed.
|
|
18
|
+
6. **Cost and circuit breakers.** dsh, hermes and other metered harnesses bill per token, and `route` warns when it picks one. Before every `dispatch` and `reasoning` run, and in `alerts check` (every 5 minutes), the breakers stop background work above 15 internal agent launches in 15 minutes, 40 background agent launches in 15 minutes (a job's own record and a run that never launched an agent do not count), or 15M new background tokens in 1 hour (cache reads are not counted, because they re-read context already paid for). The operator's own sessions never trip them.
|
|
19
|
+
7. **Billing is a policy, never a fallback.** With included usage required, automatic routing uses only subscription harnesses and never moves to paid use. To run a metered harness on purpose, name it: `route "<task>" --execute --agent dsh`. It runs alone, does not escalate to another harness, and still passes every admission check.
|
|
16
20
|
|
|
17
|
-
##
|
|
21
|
+
## Commands
|
|
22
|
+
- `router-benchmark [--k 20] [--repeats 3] [--catalog-samples 24] [--corpus file.json] [--min-recall 0.8] [--min-mrr 0.5] [--max-p95-ms 1000] [--baseline report.json] [--max-recall-drop 0] [--save] --json`: measure actual host capability retrieval separately from owner harness readiness scenarios. No provider or plugin tasks run. Explicit save creates an owner SSSS report/event, separate from execution receipts. API/MCP/router cases and capability refusals are unsupported until the production router supports them.
|
|
23
|
+
- `status`, `inspect --node <id>`, `upstream`, `changelog <agent>`, `catalog`, `nodes`: what is installed, signed in and current.
|
|
24
|
+
- `quota [--node <id>]`: readiness, measured usage and walls, OpenRouter balance, and memory across the fleet.
|
|
25
|
+
- `benchmarks`: pricing, Artificial Analysis indices, SWE-bench Pro, and pass rates from this machine's receipts. Refresh with `maintenance --models`.
|
|
26
|
+
- `maintenance --harnesses [--agent <id>] [--dry-run]`: update each installed harness with its own update command (claude, codex, agy, grok, cursor, hermes, pi, cline, openclaw; dsh through npm, forward only), daily on the maintenance node. Hermes is asked first with `hermes update --check`, because its update restarts the gateway. pi, cline, openclaw and dsh wait while a copy is running (`busy`), and a pinned runtime is left to its installer (`managed`).
|
|
27
|
+
- `route "<task>" [--jev] [--model <id>] [--agent <id>] [--prefer-local|--prefer-frontier] [--allow-unknown-auth] [--execute [--gate] [--tier fast|full|remote] [--wait]]`: pick a harness; with `--execute`, run it on its branch and escalate on failure. `--agent` runs that harness only. A Codex model must be on the signed-in account's own list; when Codex's configured default is not, Codex is excluded with the reason until the default changes or `--model` names a listed one.
|
|
28
|
+
- `coordinate "<task>" --mode pipeline|council|race [--execute] [--gate] [--auto-review] [--allow-same-family] [--background]`: without `--execute` it only reports the plan and its blockers.
|
|
29
|
+
- `decompose "<task>"`: the stages and which ready harness takes each.
|
|
30
|
+
- `review [<git-range>] [--staged] [--author <id>] [--reviewer <id>] [--thread <id>]`: review by another model family. `NO_DIFF` means there was nothing to review.
|
|
31
|
+
- `dispatch --stdin [--background]` with JSON `{agent, cwd, prompt, permissions, timeoutMs, model, node, allowUnknownAuth}`; any other field is refused: one bootstrapped run with a receipt.
|
|
32
|
+
- `cancel <job>`: stop a running local job by ID prefix or log path. Wait up to 60 seconds for its cancelled result. Finished and unknown jobs return an error. Use `watch <job>` to read progress.
|
|
33
|
+
- `reply <job> "<text>"`: steer the running turn or answer its oldest question. `approve <job> <request> allow|deny` answers an approval. Native requests and MCP requests use the same approval policy.
|
|
34
|
+
- `watch <job> [--node <owner>] --json`: query the active attempt or terminal failure locally or across the mesh. Use this for an explicit status request. Native background tasks deliver completion to their originating session.
|
|
35
|
+
- `interrupt <job>`: stop the current turn and keep its session for `resume`. `goal <job> "<text>"` replaces the running job's goal.
|
|
36
|
+
- `fork <job> [--at <turn>] [--background]`: start a new job from the session history on a new branch. Selected turns require native support. `resume <job> "<text>" [--background]` continues a finished session on its saved branch. Both commands keep the parent's history.
|
|
37
|
+
- `route`, `coordinate` and `dispatch` accept `--goal`, `--max-turns`, `--max-budget-usd`, `--max-tokens`, `--result-schema <file>`, `--approvals auto|operator|rules` and `--question-timeout-ms`. Dispatch accepts the same fields in camelCase in its stdin JSON (`approvalPolicy` selects approvals). The default goal is the task. Completion requires a separate goal check with concrete evidence. File changes alone do not prove completion. A limit fails the job without escalation. Structured results get one correction turn if validation fails, and the goal check gets the same single correction turn before the job fails. A result or goal reply may be bare JSON or exactly one fenced JSON block, with or without prose around it; no JSON or more than one block is invalid. The goal check carries optional `notes` for unfinished work outside this goal (Codex receives a strict copy of every output schema, with all properties required); notes never fail a job, while a non-empty `remaining` still does.
|
|
38
|
+
- `mcp [--approvals auto|operator|rules] [--question-timeout-ms <ms>]`: serve the job's `ask` and `approve` tools over stdio. Metaharness configures this server for Claude and Codex. `watch <job>` includes capabilities, usage, plans, diffs, hooks, model reroutes and waiting requests.
|
|
39
|
+
- A routed change gets a review from another model family after its gate and before its push. A blocking finding or an unreadable review stops the push. The job result contains the review.
|
|
40
|
+
- A token or USD cap requires measured usage. A harness that cannot report the required usage fails with `failureKind: limit`. A zero USD cap starts no agent turn. Goal checks and JSON corrections count toward job limits. JSON Schema assertions outside the portable validator's supported set fail validation. For DSH only, each `status`/`step_end` frame carries that step's own usage, which is summed across the run (cached input is reported separately and not counted) and checked after every step; `turn_end` counts one turn and `tool_call` starts a step named by its tool, while `tool_result` still ends it. Other harnesses are unchanged.
|
|
41
|
+
- `reasoning-config [--agent <id>] [--model <model>] [--max-usage-percent <1-100>] [--enable <id>] [--disable <id>]`: the harness and model for background reasoning such as lesson reviews. With nothing configured, background reasoning is refused; it never falls back to adapter order. Codex reasoning is held, with no model call, while Codex usage is at or above the threshold, and callers retry after 30 minutes. A harness with an operator OpenRouter binding (`openrouter-bind`) may be listed and is billed through it. No flags shows the saved file and the effective order.
|
|
42
|
+
- `threads list|show|create|close|delete`, `learn`, `alerts check|test [--dry-run]`, `adapter list|add|remove`.
|
|
43
|
+
- `reviews`: read the durable review ledger, including selected diff, commit, reviewer, verdict and disposition. Thread deletion does not remove reviews.
|
|
44
|
+
- `threads cleanup-fixtures [--dry-run]`: one-time cleanup of exact test fixture titles. The atomic SSSS record lists removed and retained IDs. Real end-to-end job threads stay in place.
|
|
45
|
+
- `adoption [--node <id> | --all]`: inspect native gate activity and real managed run receipts separately from installation and login.
|
|
46
|
+
- `docs-status`, `docs-refresh`, `docs-search --query <q>`, `docs-read`, `maintenance`, `setup`, `runtime <agent> <maintenance-command>`. Use dispatch for agent tasks and the service owner for gateway changes.
|
|
18
47
|
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
48
|
+
`setup --node <recorded-node>` places documentation maintenance, model maintenance
|
|
49
|
+
and quota alerts through the existing daemon. The `maintenance` placement owns
|
|
50
|
+
official documentation. Peers use `docs-status`, `docs-read`, and `docs-search` to
|
|
51
|
+
query that source through the mesh. Maintenance reports setup, gate, and documentation failures separately.
|
|
52
|
+
It also removes job records whose files are all older than 30 days, except jobs
|
|
53
|
+
whose process is still alive, so `watch`, `cancel` and `continue` cover the last 30 days.
|
|
23
54
|
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
- `total-recall meta-harness route "<task>"`: Two-stage RouteLLM classifier and gate cascade evaluation.
|
|
55
|
+
Managed Codex jobs save resumable history in the `metaharness-jobs` directory under
|
|
56
|
+
the native Codex home, outside the interactive chat list. Use Metaharness `watch`,
|
|
57
|
+
`resume` and `fork` for those jobs. Internal reasoning sessions remain ephemeral.
|
|
28
58
|
|
|
29
|
-
|
|
30
|
-
- `
|
|
31
|
-
- `
|
|
32
|
-
- `
|
|
59
|
+
- `orchestrate "<task>" [--orchestrator <id>] [--execute] [--auto-review] [--gate] [--allow-same-family] [--wait|--background]`: the default for project work. It fans out subagents and returns their verified result to the caller.
|
|
60
|
+
- `process <action> [target] [task] [--node] [--cwd] [--name] [--tools] [--setting-sources] [--model] [--tail] [--read-only] [--no-detach] [--allow-unknown-auth]`: manage owned agent processes with SSSS lifecycle records.
|
|
61
|
+
- `run-command` (JSON on stdin): run an explicit plugin command through the selected agent and node.
|
|
62
|
+
- `chat-target --brains <list>`, `chat-default <adapter> [--url <url>]`: the default Chat harness for the selected brains.
|
|
63
|
+
- `priority-cache [--add <checkout>|--remove <checkout>]`: operator only; show or change prioritized checkouts.
|
|
64
|
+
- `included-status [--probe codex]`, `included-enforce`, `included-bind-claude`, `included-bind-claude-plan`, `included-bind-claude-token --key <name>`, `included-bind-agy`, `openrouter-bind <agent> <key> --model <id>`: the billing policy and its evidence. Operator only. `included-bind-agy` lets Antigravity run on the signed-in personal Google plan (Free, Pro or Ultra); a bound run is launched with the plan forced and with no Google API key or Cloud project in its environment, and it is refused while Antigravity's saved settings select an API key, paid AI credits or a Cloud project.
|
|
65
|
+
- `usage-queue`, `usage-retry <job>`, `usage-cancel <job>`: jobs waiting for included usage.
|
|
66
|
+
- `usage-reconcile [--apply]`: preview or archive expired internal reasoning records that have no replay request. Their originating workflows own future retries.
|
|
67
|
+
- `agent-user [<name>|--clear]`: the non-root user Claude runs as when Metaharness runs as root on Linux.
|
|
68
|
+
- `docs-ensure [--agent <id>]`, `docs-sources`, `docs-read --agent <id> --url <url>`: refresh missing documentation, list approved sources, read cached pages.
|
|
33
69
|
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
-
|
|
37
|
-
|
|
70
|
+
Other options: `watch --tail <n>`; `reply|approve|interrupt|goal --local-delivery` (set by remote delivery, not by hand); `learn --void <id> --reason <text>`; `alerts check --threshold <percent>`; `threads --title --summary --status --platform --branch`; `review --allow-unknown-auth`; `coordinate --allow-unknown-auth`; `router-benchmark --core-root <path> --allow-catalog-change`.
|
|
71
|
+
|
|
72
|
+
Use `--timeout-ms` on route, coordinate, orchestrate or review to bound a remote operation. The calling harness also needs a background-task deadline long enough for the command.
|
|
73
|
+
|
|
74
|
+
## When something fails
|
|
75
|
+
Read `failureKind` on the result. `lost`: the process died without a result; read its branch and events, then run it again. `circuit-breaker`: a breaker stopped it; the message names the limit. `model`: the harness cannot run that model. `limit`: a cap was reached, or the harness cannot report the usage the cap needs (DSH reports no USD). `quota` carries `resetsAt`, and routing avoids that harness until then. `auth` and `not-ready` mean the operator must sign in or install something. These do not count against a harness's pass rate; `agent` and `gate` failures do.
|
package/src/adoption.mjs
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import { executeOnNode, listTargets } from './executor.mjs';
|
|
4
|
+
import { readReceipts } from './learner.mjs';
|
|
5
|
+
import { agentEnvironment, findBinary, inspectAgents, runProcess } from './worker.mjs';
|
|
6
|
+
|
|
7
|
+
const { version } = JSON.parse(fs.readFileSync(new URL('../plugin.json', import.meta.url), 'utf8'));
|
|
8
|
+
|
|
9
|
+
async function readPreflight(args) {
|
|
10
|
+
const binary = findBinary('total-recall');
|
|
11
|
+
if (!binary) throw new Error('Total Recall CLI is unavailable');
|
|
12
|
+
const result = await runProcess(binary, ['preflight', ...args, '--json'], {
|
|
13
|
+
cwd: os.homedir(), env: agentEnvironment(), timeoutMs: 25000,
|
|
14
|
+
});
|
|
15
|
+
if (result.reason || result.exitCode !== 0) throw new Error(`Preflight query failed: ${result.reason || `exit ${result.exitCode}`}`);
|
|
16
|
+
return JSON.parse(result.stdout);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const describeRun = run => run ? {
|
|
20
|
+
id: run.id, at: run.timestamp, success: run.success === true, exitCode: run.exitCode ?? null,
|
|
21
|
+
failureKind: run.failureKind ?? null,
|
|
22
|
+
...(run.billingMode ? { billingMode: run.billingMode } : {}),
|
|
23
|
+
...(run.tools?.length ? { tools: run.tools } : {}),
|
|
24
|
+
} : null;
|
|
25
|
+
|
|
26
|
+
function latestRuns(receipts) {
|
|
27
|
+
const runs = new Map();
|
|
28
|
+
for (const row of receipts) {
|
|
29
|
+
const time = Date.parse(row.timestamp);
|
|
30
|
+
if (row.node !== 'local' || !Number.isFinite(time)) continue;
|
|
31
|
+
const state = runs.get(row.harness) || {};
|
|
32
|
+
if (!state.attempt || time >= Date.parse(state.attempt.timestamp)) state.attempt = row;
|
|
33
|
+
if (row.success === true && row.exitCode === 0 && (!state.completed || time >= Date.parse(state.completed.timestamp))) state.completed = row;
|
|
34
|
+
runs.set(row.harness, state);
|
|
35
|
+
}
|
|
36
|
+
return runs;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** This query never launches an agent or treats a synthetic hook test as live activity. */
|
|
40
|
+
export async function inspectLocalAdoption({ inspect = inspectAgents, receipts = readReceipts, preflight = readPreflight } = {}) {
|
|
41
|
+
const [inventory, history, gates] = await Promise.allSettled([
|
|
42
|
+
inspect(), receipts(), preflight(['report']),
|
|
43
|
+
]);
|
|
44
|
+
const issues = [];
|
|
45
|
+
const inventoryRows = Array.isArray(inventory.value?.agents) ? inventory.value.agents : null;
|
|
46
|
+
const receiptRows = Array.isArray(history.value) ? history.value : null;
|
|
47
|
+
const adapterRows = Array.isArray(gates.value?.adapters) ? gates.value.adapters : null;
|
|
48
|
+
const decisions = gates.value?.compliance?.byHarness;
|
|
49
|
+
if (!inventoryRows) issues.push('Agent inventory unavailable');
|
|
50
|
+
if (!receiptRows) issues.push('Managed run receipts unavailable');
|
|
51
|
+
if (!adapterRows || !decisions) issues.push('Native preflight evidence unavailable');
|
|
52
|
+
const runs = latestRuns(receiptRows || []);
|
|
53
|
+
const adapters = new Map((adapterRows || []).map(row => [row.id, row.verification]));
|
|
54
|
+
const agents = (inventoryRows || []).map(({ id, name, installed, authenticated, version, blockedBy }) => {
|
|
55
|
+
const gate = adapters.get(id);
|
|
56
|
+
const decisionCount = decisions ? (Object.hasOwn(decisions, id) ? decisions[id]?.total ?? 0 : 0) : null;
|
|
57
|
+
const hookStatus = !adapterRows ? 'unknown' : !gate || gate.level === 'not wired' ? 'unsupported' : gate.installed ? 'configured' : 'missing';
|
|
58
|
+
const { attempt, completed } = runs.get(id) || {};
|
|
59
|
+
return {
|
|
60
|
+
id, name, installed, authenticated, version: version ?? null, ...(blockedBy ? { blockedBy } : {}),
|
|
61
|
+
nativeGate: { status: hookStatus, recentDecisions: decisionCount },
|
|
62
|
+
managedRun: { lastAttempt: describeRun(attempt), lastCompleted: describeRun(completed) },
|
|
63
|
+
};
|
|
64
|
+
});
|
|
65
|
+
const installed = agents.filter(agent => agent.installed);
|
|
66
|
+
const managedCompletions = installed.filter(agent => agent.managedRun.lastCompleted).length;
|
|
67
|
+
return {
|
|
68
|
+
ok: issues.length === 0, pluginVersion: version,
|
|
69
|
+
issues, agents,
|
|
70
|
+
summary: { installed: installed.length, managedCompletions, liveHookActivity: installed.filter(agent => agent.nativeGate.recentDecisions > 0).length },
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export async function inspectFleetAdoption({ node, inventory = listTargets, readLocal = inspectLocalAdoption, execute = executeOnNode } = {}) {
|
|
75
|
+
const targets = await inventory();
|
|
76
|
+
const nodes = node ? targets.nodes.filter(row => row.id === node || row.name === node) : targets.nodes;
|
|
77
|
+
if (!nodes.length) throw new Error('Select a recorded node from meta-harness nodes');
|
|
78
|
+
const results = await Promise.all(nodes.map(async target => {
|
|
79
|
+
const row = { node: target.id, name: target.name };
|
|
80
|
+
if (!target.self && target.online === false) return { ...row, status: 'offline' };
|
|
81
|
+
if (!target.self && !target.accessConfigured) return { ...row, status: 'no-cli-access' };
|
|
82
|
+
try {
|
|
83
|
+
let report;
|
|
84
|
+
if (target.self) report = await readLocal();
|
|
85
|
+
else {
|
|
86
|
+
const result = await execute(target.id, {
|
|
87
|
+
operation: 'direct', useHome: true, timeoutMs: 40000,
|
|
88
|
+
argv: ['total-recall', 'meta-harness', 'adoption', '--json'],
|
|
89
|
+
});
|
|
90
|
+
try { report = JSON.parse(result.output); } catch { /* The installed CLI did not supply an adoption report. */ }
|
|
91
|
+
if (report?.error === 'Unknown operation: adoption') return { ...row, status: 'update-required', error: 'The installed Metaharness does not support adoption reports.' };
|
|
92
|
+
if (!report || !Array.isArray(report.agents) || typeof report.pluginVersion !== 'string' || typeof report.ok !== 'boolean' || (report.ok && !result.ok)) {
|
|
93
|
+
return { ...row, status: 'adoption-unavailable', error: 'The installed Metaharness did not return an adoption report. Verify its version and CLI availability.' };
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return { ...row, status: report.ok ? 'inspected' : 'partial', report };
|
|
97
|
+
} catch (error) {
|
|
98
|
+
return { ...row, status: 'probe-failed', error: String(error?.message || error).slice(0, 400) };
|
|
99
|
+
}
|
|
100
|
+
}));
|
|
101
|
+
return { ok: !targets.meshError && results.every(row => row.status === 'inspected'), ...(targets.meshError ? { meshError: targets.meshError } : {}), nodes: results };
|
|
102
|
+
}
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
/** The non-root Unix user Claude runs as when Metaharness itself runs as root on Linux. */
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { execFileSync } from 'node:child_process';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import { configDir } from './paths.mjs';
|
|
7
|
+
import { gitMetadataEntries } from './worktree.mjs';
|
|
8
|
+
|
|
9
|
+
const VERSION = 1;
|
|
10
|
+
const NAME = /^[a-z_][a-z0-9_-]{0,31}$/;
|
|
11
|
+
const defaultExec = (file, args, options = {}) => execFileSync(file, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], ...options });
|
|
12
|
+
|
|
13
|
+
export const validAgentUser = name => typeof name === 'string' && NAME.test(name);
|
|
14
|
+
|
|
15
|
+
async function userStore() {
|
|
16
|
+
const { PluginStateStore } = await import('./ssss-store.mjs');
|
|
17
|
+
return new PluginStateStore(path.join(configDir(), 'agent-user.json'), 'meta-harness');
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function requireOperator() {
|
|
21
|
+
if (process.env.TR_META_HARNESS_RUN) throw new Error('Only the operator may change the agent user.');
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export async function readAgentUser() {
|
|
25
|
+
const state = (await userStore()).read({ version: VERSION, user: null });
|
|
26
|
+
if (state?.version !== VERSION || (state.user !== null && !validAgentUser(state.user))) {
|
|
27
|
+
throw new Error('The agent user setting is invalid; dispatch stopped.');
|
|
28
|
+
}
|
|
29
|
+
return state.user;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export async function writeAgentUser(name) {
|
|
33
|
+
requireOperator();
|
|
34
|
+
if (name !== null && !validAgentUser(name)) throw new Error('The agent user must match ^[a-z_][a-z0-9_-]{0,31}$.');
|
|
35
|
+
(await userStore()).write({ version: VERSION, user: name });
|
|
36
|
+
return { user: name };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Claude refuses full permissions as root, so only a root Linux host needs another user. */
|
|
40
|
+
export function agentUserRequired({ platform = process.platform, euid = process.geteuid?.() } = {}) {
|
|
41
|
+
return platform === 'linux' && euid === 0;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function resolveAgentAccount(name, { exec = defaultExec } = {}) {
|
|
45
|
+
if (!validAgentUser(name)) throw new Error('The agent user must match ^[a-z_][a-z0-9_-]{0,31}$.');
|
|
46
|
+
let line;
|
|
47
|
+
try { line = String(exec('getent', ['passwd', name])).split('\n')[0]; }
|
|
48
|
+
catch { throw new Error(`The agent user ${name} does not exist on this node.`); }
|
|
49
|
+
const fields = line.split(':');
|
|
50
|
+
const uid = Number(fields[2]);
|
|
51
|
+
const gid = Number(fields[3]);
|
|
52
|
+
if (fields.length !== 7 || fields[0] !== name || !/^\d+$/.test(fields[2]) || !/^\d+$/.test(fields[3]) ||
|
|
53
|
+
!Number.isSafeInteger(uid) || !Number.isSafeInteger(gid) || uid > 4294967294 || gid > 4294967294 || !path.isAbsolute(fields[5])) {
|
|
54
|
+
throw new Error(`The agent user ${name} does not exist on this node.`);
|
|
55
|
+
}
|
|
56
|
+
if (uid === 0) throw new Error('The agent user must not be root (uid 0).');
|
|
57
|
+
return { user: name, uid, gid, home: fields[5] };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Check using the target identity, after Node is reachable through its ACL grant. Never provision users. */
|
|
61
|
+
export function verifyAgentHome(account, { exec = defaultExec } = {}) {
|
|
62
|
+
try {
|
|
63
|
+
exec(process.execPath, ['--input-type=module', '-e',
|
|
64
|
+
"import fs from 'node:fs'; fs.accessSync(process.cwd(), fs.constants.R_OK | fs.constants.W_OK | fs.constants.X_OK);"],
|
|
65
|
+
{ uid: account.uid, gid: account.gid, cwd: account.home,
|
|
66
|
+
env: { HOME: account.home, USER: account.user, LOGNAME: account.user } });
|
|
67
|
+
} catch {
|
|
68
|
+
throw new Error(`The agent user ${account.user} needs an existing readable, writable home at ${account.home}; provision it before dispatch.`);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Find existing repositories under a grant, without following workspace symlinks. */
|
|
73
|
+
export function gitProtectionPaths(directory, { exec = defaultExec } = {}) {
|
|
74
|
+
const protectedPaths = new Set();
|
|
75
|
+
const entries = gitMetadataEntries(directory);
|
|
76
|
+
for (const entry of entries) if (entry.symlink) throw new Error(`Refusing to resolve git metadata through the symlink ${entry.metadata}.`);
|
|
77
|
+
const common = (cwd, required) => {
|
|
78
|
+
let output;
|
|
79
|
+
try { output = String(exec('git', ['-C', cwd, 'rev-parse', '--git-common-dir'])).trim(); }
|
|
80
|
+
catch (error) {
|
|
81
|
+
if (required) throw new Error(`Cannot resolve git metadata in ${cwd}: ${error.message}`);
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
if (!output) throw new Error(`Cannot resolve git metadata in ${cwd}: empty common directory`);
|
|
85
|
+
protectedPaths.add(path.resolve(cwd, output));
|
|
86
|
+
};
|
|
87
|
+
const checkouts = new Set(entries.map(entry => entry.cwd));
|
|
88
|
+
common(path.resolve(directory), checkouts.has(path.resolve(directory)));
|
|
89
|
+
for (const cwd of checkouts) if (cwd !== path.resolve(directory)) common(cwd, true);
|
|
90
|
+
for (const entry of entries) protectedPaths.add(entry.metadata);
|
|
91
|
+
return [...protectedPaths];
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function canTraverse(stat, account) {
|
|
95
|
+
const mode = stat.mode;
|
|
96
|
+
return Boolean(mode & 0o001) || (stat.gid === account.gid && Boolean(mode & 0o010)) || (stat.uid === account.uid && Boolean(mode & 0o100));
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** True when the directory already carries a named ACL entry for the user, which is then left as it is. */
|
|
100
|
+
function hasNamedAclEntry(dir, user, { exec = defaultExec, uid } = {}) {
|
|
101
|
+
try {
|
|
102
|
+
return String(exec('getfacl', ['-p', '-c', dir])).split('\n').some(line =>
|
|
103
|
+
line.startsWith(`user:${user}:`) || (uid !== undefined && line.startsWith(`user:${uid}:`)));
|
|
104
|
+
} catch (error) {
|
|
105
|
+
throw new Error(`getfacl failed for ${dir}; cannot preserve existing ACLs. Ensure the acl package is installed: ${String(error.stderr || error.message).trim()}`);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Give the agent user access with POSIX ACLs and never chown. An ancestor the user cannot already traverse gets
|
|
111
|
+
* execute only, so the user can reach a granted path under /root without listing it. A directory grant is recursive and also
|
|
112
|
+
* a default ACL, so files created later stay reachable; a file grant covers that file alone. `protect`
|
|
113
|
+
* (git directories) is applied after every other grant and leaves the agent read access only.
|
|
114
|
+
*/
|
|
115
|
+
export function grantAgentAccess(account, { writable = [], readOnly = [], protect = [] } = {}, { exec = defaultExec, lstat = fs.lstatSync, stat = fs.statSync, namedEntry = hasNamedAclEntry } = {}) {
|
|
116
|
+
const user = account.user;
|
|
117
|
+
if (!validAgentUser(user)) throw new Error('Invalid agent user for ACL grants.');
|
|
118
|
+
const setfacl = args => {
|
|
119
|
+
try { exec('setfacl', args); }
|
|
120
|
+
catch (error) {
|
|
121
|
+
const missing = error.code === 'ENOENT';
|
|
122
|
+
throw new Error(missing ? 'setfacl is not installed; install the acl package so the agent user can reach the workspace.'
|
|
123
|
+
: `setfacl failed (${args.join(' ')}); the filesystem must support ACLs and the acl package must be installed: ${String(error.stderr || error.message).trim()}`);
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
const writes = [...new Set(writable.map(item => path.resolve(item)))];
|
|
127
|
+
const inside = (parent, item) => { const relative = path.relative(parent, item); return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative)); };
|
|
128
|
+
// Code and executable read grants can overlap a writable checkout. Never downgrade its ACL.
|
|
129
|
+
const reads = [...new Set(readOnly.map(item => path.resolve(item)))].filter(item => !writes.some(parent =>
|
|
130
|
+
item === parent || (inside(parent, item) && fs.statSync(parent).isDirectory())));
|
|
131
|
+
const grants = [...reads.map(item => ({ item, write: false })), ...writes.map(item => ({ item, write: true }))];
|
|
132
|
+
const granted = new Set(grants.map(({ item }) => item));
|
|
133
|
+
// Git directories are read-only for the agent, whether or not a writable grant covers them: root runs
|
|
134
|
+
// git there later, so an agent-planted hook or config would run as root. They are applied last.
|
|
135
|
+
const protects = [...new Set(protect.map(item => path.resolve(item)))].filter(item => {
|
|
136
|
+
let stat;
|
|
137
|
+
try { stat = fs.lstatSync(item); } catch (error) { if (error.code === 'ENOENT') return false; throw error; }
|
|
138
|
+
if (stat.isSymbolicLink()) throw new Error(`Refusing to grant access through the symlink ${item}.`);
|
|
139
|
+
return true;
|
|
140
|
+
});
|
|
141
|
+
// Named-user ACLs cannot restrict an inode's owner, and recursive setfacl skips symlink targets.
|
|
142
|
+
// Refuse either case before any grant could expose metadata through the writable workspace.
|
|
143
|
+
const inspect = [...protects];
|
|
144
|
+
const inspected = new Set();
|
|
145
|
+
while (inspect.length) {
|
|
146
|
+
const item = inspect.pop();
|
|
147
|
+
if (inspected.has(item)) continue;
|
|
148
|
+
inspected.add(item);
|
|
149
|
+
const stat = lstat(item);
|
|
150
|
+
if (stat.isSymbolicLink()) throw new Error(`Cannot protect git metadata through the symlink ${item}.`);
|
|
151
|
+
if (stat.uid === account.uid) throw new Error(`Cannot protect ${item}: it is owned by the agent user ${user}.`);
|
|
152
|
+
if (stat.isDirectory()) for (const entry of fs.readdirSync(item)) inspect.push(path.join(item, entry));
|
|
153
|
+
}
|
|
154
|
+
const covered = item => writes.some(parent => inside(parent, item) && fs.statSync(parent).isDirectory());
|
|
155
|
+
const ancestors = new Set();
|
|
156
|
+
for (const { item } of [...grants, ...protects.filter(item => !covered(item)).map(item => ({ item }))]) {
|
|
157
|
+
for (let dir = path.dirname(item); ; dir = path.dirname(dir)) {
|
|
158
|
+
if (!granted.has(dir)) ancestors.add(dir);
|
|
159
|
+
if (dir === path.parse(dir).root) break;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
// Ancestors first: a granted directory that is also an ancestor must keep its wider grant.
|
|
163
|
+
// A named-user entry replaces the "other" permissions for that user, so it must never narrow access
|
|
164
|
+
// the user already has (/tmp at 1777, / at 755). Add it only where traversal is otherwise impossible.
|
|
165
|
+
for (const dir of ancestors) {
|
|
166
|
+
if (canTraverse(stat(dir), account) || namedEntry(dir, user, { exec, uid: account.uid })) continue;
|
|
167
|
+
setfacl(['-m', `u:${user}:x`, dir]);
|
|
168
|
+
}
|
|
169
|
+
for (const { item, write } of grants) {
|
|
170
|
+
const directory = fs.statSync(item).isDirectory();
|
|
171
|
+
if (directory) setfacl(write ? ['-R', '-m', `u:${user}:rwX,d:u:${user}:rwX`, item] : ['-R', '-m', `u:${user}:rX`, item]);
|
|
172
|
+
else setfacl(['-m', `u:${user}:${write ? 'rwX' : 'rX'}`, item]);
|
|
173
|
+
}
|
|
174
|
+
for (const item of protects) {
|
|
175
|
+
if (fs.statSync(item).isDirectory()) setfacl(['-R', '-m', `u:${user}:rX,d:u:${user}:rX`, item]);
|
|
176
|
+
else setfacl(['-m', `u:${user}:r`, item]);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* What the MCP server, started by Claude as the agent user, needs: this job's inbox and event log, and
|
|
182
|
+
* read access to the plugin source and the node binary. The brain, the secrets store and other jobs stay
|
|
183
|
+
* closed, so the server cannot read the credential store; its `decision` approval call, which needs
|
|
184
|
+
* Total Recall as root, is the part that cannot run as the agent user. Operator approvals only use
|
|
185
|
+
* these job files and do not need Decision or credentials.
|
|
186
|
+
*/
|
|
187
|
+
export async function mcpAccess(job) {
|
|
188
|
+
const { jobPaths } = await import('./control.mjs');
|
|
189
|
+
const { inbox, events } = jobPaths(job);
|
|
190
|
+
fs.mkdirSync(path.dirname(events), { recursive: true, mode: 0o700 });
|
|
191
|
+
for (const file of [inbox, events]) fs.closeSync(fs.openSync(file, 'a', 0o600));
|
|
192
|
+
const source = path.dirname(fileURLToPath(import.meta.url));
|
|
193
|
+
return { writable: [inbox, events], readOnly: [source, fs.realpathSync(process.execPath)] };
|
|
194
|
+
}
|