Skip to content
Merged
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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ Fragments are Agentwheel composition inputs, not runtime file-drop targets.
| `agentwheel uninstall <name-or-source>` | Remove a configured package from runtimes and config. |
| `agentwheel uninstall <name> --keep-files` | Remove from config/manifest while leaving runtime files unmanaged. |
| `agentwheel status` | Show configured packages, manifest/lock presence, and install state. For a named fleet, use `--fleet <fleet-id> --profile <name>`; `--fleet <fleet-id> --all` uses profile `all` when present. |
| `agentwheel ownership migrate-legacy` | Plan or apply metadata-only migration of current-owner legacy claims, including exact merge contributions, into the current install state. See [operator procedure](docs/ownership-legacy-migration.md). |
| `agentwheel ownership handoff <type/name>` | Transfer one manifest entry to a different workspace root after exact owner, hash, and revision checks; runtime content is not rewritten. |
| `agentwheel mcp retire <package>` | Preview removal of one exact legacy MCP contribution under an explicitly selected install-state key; add `--apply` only after review. |
| `agentwheel doctor` | Check runtime setup and suggest explicit companion/selected skill install commands when they are missing. |
Expand Down
105 changes: 105 additions & 0 deletions docs/ownership-legacy-migration.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
# Migrate current-owner legacy state

`ownership migrate-legacy` moves verified entries already owned by the current workspace (or
its registered fleet) from an explicitly selected old manifest into the state key that configured
`install` uses. It does not change owners, graph locks, workspace configuration, or runtime files.
Use `ownership handoff` separately when the owner must change. No historical graph lock is required.

```bash
cd /path/to/governing-workspace
agentwheel ownership migrate-legacy --local --agent example \
--source-state-key openclaw.user.old-key --json > /tmp/migration-plan.json
```

A registered fleet can instead use `--fleet example`. Choose one agent or one profile resolving to
one target. Configured packages must resolve to one adapter configuration and installation type.
The destination is calculated exactly as for install, including explicit configured state keys.
Use repeatable `--path relative/path` to select a subset; otherwise all current-owner entries move.
Other owners' source entries remain untouched.

The plan computes desired coverage from the current graph, as `ownership adopt-legacy` does, and
records it in the plan JSON and digest. Each selected entry reports whether the configured packages
still install it. An entry the graph no longer installs is refused by default: after migration the
next `install` would treat it as stale and remove its runtime files. Pass `--allow-undesired` only
when that removal is intended or the configuration will be updated first; the flag is part of the
digest, so plan and apply must agree on it. An entry whose path the graph assigns to a different
artifact is always refused. A destination manifest that is absent next to a stable graph lock is
refused too; reconcile that orphan lock before migrating.

Review the owner, target, source/destination keys, selected paths, full inventory revision and
plan digest. Apply the same selection, adding the reviewed values (use `absent` for a null revision).
The plan's `applyCommand` prints the exact command, including `--reason`:

```bash
agentwheel ownership migrate-legacy --local --agent example \
--source-state-key openclaw.user.old-key \
--plan-digest "$(jq -r .planDigest /tmp/migration-plan.json)" \
--expected-source-revision "$(jq -r '.source.revision // "absent"' /tmp/migration-plan.json)" \
--expected-destination-revision "$(jq -r '.destination.revision // "absent"' /tmp/migration-plan.json)" \
--expected-inventory-revision "$(jq -r .manifestInventoryRevision /tmp/migration-plan.json)" \
--apply --reason 'Migrate reviewed current-owner claims'
agentwheel install --local --agent example --dry-run --format json
```

Apply requires an effective `mutationPolicy` with `journal: "required"` (revisioning may be `off`
or `commit-after-verify`) and a durable receipt for the governing workspace. Without it, apply
refuses before touching target metadata. This ensures both destination and source journals have
a recovery path through `mutation recover-runtime <operation-id>`; keep the operation ID from
the command's mutation receipt output.

Local-run-as targets use the same command and pinned identity checks. Apply runs through the normal
GovernedMutation receipt and confined worker; SSH is unsupported. Planning is read-only. Apply takes
the target lock, re-reads both manifests and refuses unless their revisions still equal the plan's,
then checks the complete inventory, runtime hashes and runtime
snapshots again at each metadata commit. Drift, missing files, semantic commands/plugins, incomplete
merge ownership, overlapping claims and pending journals fail closed. Exact managed instruction
blocks and complete JSON/TOML/YAML merge contributions are verified using the existing ownership
checks. The full runtime file is guarded even when only one contribution is owned.

The destination commits first. If interrupted, recover the pending journal through the original
mutation receipt (`mutation recover-runtime <operation-id>`), then obtain a new plan. An exact
duplicate already in the destination is retired from the source without rewriting the destination.
An emptied source manifest and its old source lock are removed by the existing state cleanup.
An absent source yields an empty plan, so repeated migration is a no-op. With `--path`, a path that
is already absent from the source and present in the destination with a verified current-owner
entry is listed under `alreadyMigrated` and selects nothing, so the same command can be rerun. A
path missing from both manifests, or owned by another workspace, is still refused. A fresh digest
is required for each apply; do not reuse a pre-interruption plan.

## Operator validation on a snapshot copy

An operator first captures the runtime and `.agentwheel` into a separate readable snapshot using
their existing backup procedure, with no install or migration running. The checker refuses a
snapshot that holds a runtime apply lock or a pending apply journal. It only reads the snapshot
root it is given and never resolves a live service root itself; keeping the live root out of
`--snapshot-root` is the operator's responsibility. Pass only that
snapshot, an exact old state key, and the exact current owner string from the snapshot (after any
separately reviewed handoff). A metadata-only snapshot is insufficient: include every claimed
runtime path needed to verify hashes and merge contributions.

```bash
python3 scripts/legacy-migration-copy-check.py \
--snapshot-root "$SNAPSHOT_ROOT" --source-state-key "$SOURCE_STATE_KEY" \
--current-owner "$CURRENT_OWNER" --cli "$PWD/dist/index.js"
python3 scripts/legacy-migration-copy-check.py \
--snapshot-root "$SNAPSHOT_ROOT" --source-state-key "$SOURCE_STATE_KEY" \
--current-owner "$CURRENT_OWNER" --cli "$PWD/dist/index.js" --apply
python3 scripts/legacy-migration-copy-check.py \
--snapshot-root "$SNAPSHOT_ROOT" --source-state-key "$SOURCE_STATE_KEY" \
--current-owner "$CURRENT_OWNER" --cli "$PWD/dist/index.js" --apply \
--path relative/path
```

Each invocation creates a new disposable directory and prints its location. The CLI runs with a
minimal environment (`PATH`, `HOME` set to the copy, and the isolated mutation state root); on a
failure its stderr and stdout are printed before the checker exits. Repeatable `--path` is passed
through unchanged, and the rerun must report exactly those paths as already migrated. The copy is
an isolated empty workspace with no configured packages, so the checker always passes
`--allow-undesired`; desired coverage is verified only by the real plan. Only that copy's
manifest target roots and matching owner strings are rebased into an isolated plain workspace;
source/destination revisions and plan digests are then recomputed. The copy apply uses a durable
receipt, verifies all non-metadata bytes and modes, and proves the next plan selects nothing.
The printed directory is a full copy of the runtime snapshot and may hold the same sensitive files;
review it, then remove it. This verifies copied legacy claims, not the live endpoint,
service permissions, fleet identity or a real install; the CLI and confined-worker tests cover those
contracts separately. Never copy this rebased metadata back to the real target.
126 changes: 126 additions & 0 deletions scripts/legacy-migration-copy-check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
#!/usr/bin/env python3
"""Verify metadata-only migration on a disposable copy of an existing snapshot.

The operator must pass an already captured, readable snapshot containing
.agentwheel and its claimed runtime paths, never a live service root: this
script only reads --snapshot-root and cannot tell a snapshot from a live root.
The evidence directory it prints holds a full copy of that runtime; remove it
once the run has been reviewed.
"""
import argparse
import hashlib
import json
from pathlib import Path
import os
import shutil
import stat
import subprocess
import sys
import tempfile

PENDING_METADATA_SUFFIXES = ('.runtime-apply-lock', '.apply-journal.json')


def snapshot(root):
result = {}
for path in sorted(root.rglob('*')):
if path.relative_to(root).parts[0] == '.agentwheel':
continue
info = path.lstat()
if stat.S_ISLNK(info.st_mode):
raise RuntimeError(f'Symlinks are unsupported in this copy check: {path}')
result[str(path.relative_to(root))] = [stat.S_IMODE(info.st_mode),
hashlib.sha256(path.read_bytes()).hexdigest() if path.is_file() else None]
return result


def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--snapshot-root', type=Path, required=True)
parser.add_argument('--source-state-key', required=True)
parser.add_argument('--current-owner', required=True, help='exact owner string after any separately reviewed handoff')
parser.add_argument('--cli', type=Path, required=True)
parser.add_argument('--node', default='node')
parser.add_argument('--path', action='append', default=[], dest='paths',
help='select one exact relative runtime path (repeatable), passed to migrate-legacy')
parser.add_argument('--apply', action='store_true', help='also apply on the disposable copy and verify runtime equality')
args = parser.parse_args()
source = args.snapshot_root.resolve(strict=True)
cli = args.cli.resolve(strict=True)
if source == Path('/') or not (source / '.agentwheel').is_dir():
raise RuntimeError('Expected an already captured snapshot with .agentwheel metadata')
if any(path.is_symlink() for path in source.rglob('*')):
raise RuntimeError('Copy check refuses symlinks')
pending = sorted(path.name for path in (source / '.agentwheel').iterdir() if path.name.endswith(PENDING_METADATA_SUFFIXES))
if pending:
raise RuntimeError(f'Snapshot holds a runtime apply lock or pending journal, so it was captured mid-apply: {", ".join(pending)}')
key = args.source_state_key
if not key or any(c not in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-' for c in key):
raise RuntimeError('Source state key must be canonical')
base = Path(tempfile.mkdtemp(prefix='aw-legacy-copy-'))
print(f'Evidence directory (full runtime copy, remove after review): {base}', flush=True)
target, workspace, pack = base / 'target', base / 'workspace', base / 'pack'
shutil.copytree(source, target, symlinks=True)
state = json.loads((target / '.agentwheel' / f'{key}.install-manifest.json').read_text())
adapter, installation_type = state['adapter'], state['installationType']
if adapter not in ('openclaw', 'claude', 'codex', 'copilot', 'hermes'):
raise RuntimeError('Copy checker currently supports built-in adapters only')
if not any(entry.get('workspaceOwner') == args.current_owner for entry in state['entries']):
raise RuntimeError('No source entries have the exact selected current owner')
# Rebase only metadata in the disposable copy; runtime bytes remain untouched.
# The copy uses an isolated plain workspace instead of the real registered fleet.
for path in (target / '.agentwheel').glob('*.install-manifest.json'):
manifest = json.loads(path.read_text())
manifest['targetRoot'] = str(target)
for entry in manifest['entries']:
if entry.get('workspaceOwner') == args.current_owner:
entry['workspaceOwner'] = f'workspace-root:{workspace}'
path.write_text(json.dumps(manifest, indent=2) + '\n')
(workspace / '.agentwheel').mkdir(parents=True)
pack.mkdir()
config = {'schemaVersion': 4,
'agents': {'copy': {'adapter': adapter, 'root': str(target), 'transport': 'local', 'installationType': installation_type}},
# Migration resolves identity only: no sources are installed or executed.
'packages': [{'name': 'copy-selection', 'source': str(pack), 'driver': 'local', 'mode': 'pinned', 'installationType': installation_type}],
'mutationPolicy': {'reason': 'required', 'journal': 'required', 'revisioning': {'mode': 'off'}}}
(workspace / '.agentwheel/config.json').write_text(json.dumps(config, indent=2) + '\n')
# Keep operator credentials and Agentwheel overrides out of the copy run.
env = {'PATH': os.environ.get('PATH', os.defpath), 'HOME': str(target), 'AGENTWHEEL_MUTATION_STATE_ROOT': str(base / 'receipts')}
if 'LANG' in os.environ:
env['LANG'] = os.environ['LANG']
# The copy's pack is empty, so every entry is undesired here. A real apply must review
# desiredCoverage and run without --allow-undesired unless removal on next install is intended.
command = [args.node, str(cli), 'ownership', 'migrate-legacy', '--local', '--agent', 'copy', '--source-state-key', key,
'--allow-undesired', *[arg for path in args.paths for arg in ('--path', path)]]
def run(extra):
result = subprocess.run(command + extra, cwd=workspace, env=env, capture_output=True, text=True)
if result.returncode:
print(result.stderr, end='', file=sys.stderr)
print(result.stdout, end='', file=sys.stderr)
raise RuntimeError(f'migrate-legacy exited with {result.returncode}')
return result.stdout
before = snapshot(target)
plan = json.loads(run(['--json']))
(base / 'plan.json').write_text(json.dumps(plan, indent=2) + '\n')
print(f'Plan digest: {plan["planDigest"]}; selected entries: {len(plan["selected"])}', flush=True)
if not plan['selected']:
raise RuntimeError('Expected a nonempty migration plan')
if args.apply:
applied = run(['--apply', '--json', '--reason', 'Verify reviewed migration on disposable snapshot copy',
'--plan-digest', plan['planDigest'], '--expected-source-revision', plan['source']['revision'] or 'absent',
'--expected-destination-revision', plan['destination']['revision'] or 'absent',
'--expected-inventory-revision', plan['manifestInventoryRevision']])
(base / 'applied.json').write_text(applied)
if snapshot(target) != before:
raise RuntimeError('Runtime bytes or modes changed in disposable copy')
repeated = json.loads(run(['--json']))
if repeated['selected'] or sorted(item['path'] for item in repeated['alreadyMigrated']) != sorted(set(args.paths)):
raise RuntimeError('Migration was not idempotent')
(base / 'after.json').write_text(json.dumps(repeated, indent=2) + '\n')
print('PASS: copied claims migrated, runtime bytes/modes unchanged, rerun is a no-op')
elif snapshot(target) != before:
raise RuntimeError('Plan changed runtime files')


if __name__ == '__main__':
main()
Loading
Loading