Compare commits
5 Commits
feat/869-c
...
docs/heart
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
aabf81dd42 | ||
| 529c177830 | |||
| a32ce4c8f9 | |||
| d351caad36 | |||
| 76b86a246e |
@@ -0,0 +1,49 @@
|
||||
# Framework-Layering Constraints for the Fleet Wake / Heartbeat-Efficiency Component
|
||||
|
||||
**From:** MS-LEAD (Matrix comms-evolution / framework-tooling lead)
|
||||
**To:** heartbeat/wake-efficiency designers (via docs/scratchpads/heartbeat-planning/)
|
||||
**Date:** 2026-07-25 · **Purpose:** one-page framework-layering input BEFORE design convergence
|
||||
**Grounded in:** RFC-001 (MACP/Matrix-native) + RFC-002 (open-source install/config/topology), `~/agent-work/matrix-impl/`
|
||||
|
||||
---
|
||||
|
||||
## 0. READ FIRST — the critical overlap (coherence, not duplication)
|
||||
|
||||
**The wake/heartbeat-efficiency work and the MACP presence/heartbeat model are the SAME problem domain.** RFC-001 §4.5 already defines a `mosaic.presence` heartbeat (fields: `status`, `seq`, `interval_ms`) whose *age vs `dark_threshold`* deterministically drives online/away/offline; §5 makes that same heartbeat the input to coordinator-dark escalation. P1 (PR #888) has this **built and dev-proven** (a hard-killed agent flips to offline within threshold, heartbeat-driven).
|
||||
|
||||
**Recommendation:** do NOT build a second, parallel heartbeat. Aim for **one liveness substrate** where a single heartbeat (a) drives presence, (b) feeds escalation, and (c) is the input to wake-efficiency scheduling. Wake-efficiency then = "schedule the next wake from liveness + pending-work signals" over the *same* heartbeat the presence layer already emits. Two competing heartbeats = drift, double the wasted wakes, and two sources of truth for "is this agent alive." Please align the heartbeat event schema + threshold keys with MACP (RFC-001 §4.5) — reuse `interval_ms` / `dark_threshold` naming so config and reasoning compose.
|
||||
|
||||
## 1. Framework vs product layering (RFC-002 §3)
|
||||
|
||||
- **Boundary rule:** *framework owns the agent/harness contract + anything needed at spin BEFORE product code exists; product owns deployed services/libraries.*
|
||||
- A wake/heartbeat scheduler is **agent-runtime-level → FRAMEWORK** (`~/.config/mosaic/tools/` + a guide). It must run without `/src/<product>` present.
|
||||
- If it reads/writes *shared fleet* liveness, split cleanly: the framework tool operates on a **framework-file layer** by default, with an **optional product-DB override** when the product is reachable (see §3).
|
||||
|
||||
## 2. State location
|
||||
|
||||
- **Framework/per-agent state → `~/.config/mosaic/`** (the established convention: tokens under `~/.config/mosaic/secrets/`, tool state under `~/.config/mosaic/`). Per-agent state that must survive a non-persistent shell goes on-disk here (mirrors the `git config mosaic.gitIdentity` persisted-per-worktree pattern from the identity patches).
|
||||
- **Fleet-shared liveness → the product DB (Postgres)**, when present.
|
||||
- **Do not invent a third store.** Framework file-plane + product DB-plane only.
|
||||
|
||||
## 3. Config schema conventions (RFC-002 §5)
|
||||
|
||||
- **Precedence:** `install-time → DB-override → compiled-default`, with **sane defaults compiled in** so a bare install works.
|
||||
- **Two config planes (state this explicitly):** a framework tool runs before the product DB exists, so it needs a **file-based framework config** (`~/.config/mosaic/*.json`, consistent with `~/.claude/hooks-config.json` / `settings.json` patterns) **plus** the product DB as authoritative override when reachable.
|
||||
- **Classify install-immutable vs runtime-tunable.** Heartbeat cadence + thresholds (`interval_ms`, `miss_tolerance`, `dark_threshold`, wake-min/max) are **runtime-tunable** — and should share keys with MACP's escalation thresholds (RFC-001 §5) so they're not defined twice.
|
||||
|
||||
## 4. Installer patterns (RFC-002 §6) — if it ships as an installable suite
|
||||
|
||||
- Guided installer: **detect existing state → suggest (never silent-default) → immutable-vs-tunable gate → validate BEFORE declaring success.**
|
||||
- **systemd timers are the sharp edge:** any drop-in that overrides cadence MUST emit the `OnUnitActiveSec=` **blank-reset** line on every override (this is literally batch item (4) — the ~88-wasted-wakes/day bug from a missing reset registering both timers). A *wake-efficiency* tool that gets this wrong recreates the exact bug it exists to solve. Treat the blank-reset as a hard invariant + a test.
|
||||
|
||||
## 5. #869 publish-gate + fail-closed discipline
|
||||
|
||||
- If the wake tool touches **enforcement paths** (lease/activation/timers that gate fleet behavior), the #869 publish-gate discipline applies: **fail-closed, no silent fallthrough** (cf. Patch 2b's fail-loud fix — an absent expected value must error, not silently degrade), and release/activation stays **non-autonomous**.
|
||||
|
||||
## 6. Coherence with tmux-P0
|
||||
|
||||
- Preserve the existing layering: **tmux = P0 fast-path**, Matrix/durable above it. Wake-efficiency should **reduce wasted wakes** without starving the presence heartbeat (same signal — §0). The win is fewer, better-timed wakes over one liveness model — not a new scheduling silo.
|
||||
|
||||
---
|
||||
|
||||
**The prize:** one coherent liveness/wake substrate — a single heartbeat that presence, escalation, and wake-efficiency all read — living in the framework layer, config in two planes (file + DB-override), thresholds shared with MACP, systemd blank-reset as a hard invariant. Happy to review the converging design against this and against RFC-001/002 directly.
|
||||
@@ -0,0 +1,180 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Enforcement-side version-coupling gate (issue #869, Point-1 card C4).
|
||||
|
||||
Root cause this exists to guard against (#828 version skew, restated from
|
||||
the C1 activation probe in ``lease-activation-probe.ts``): the lease
|
||||
broker's ENFORCEMENT half (this toolkit — ``launch-runtime.py``,
|
||||
``mutator-gate.py``, ``revoke-lease.py``) and its ACTIVATION half
|
||||
(``execLeaseGatedRuntime()`` in ``launch.ts``, which chains the gated
|
||||
runtime through ``launch-runtime.py`` and injects ``MOSAIC_LEASE_*``) ship
|
||||
on different channels — an npm package and a framework/CLI reseed. C1 gave
|
||||
the activation half a versioned, machine-checkable identity
|
||||
(``LEASE_ACTIVATION_CAPABILITY``, printed by the CLI's hidden
|
||||
``mosaic __lease-capability`` subcommand). That identity is inert on its
|
||||
own: nothing yet asserted that ENFORCEMENT actually requires the version
|
||||
ACTIVATION advertises. This module is that assertion, owned by the
|
||||
enforcement side.
|
||||
|
||||
``EXPECTED_ACTIVATION_CAPABILITY`` below is this toolkit's own contract
|
||||
declaration — bump it only when this toolkit's launch/gate seam starts
|
||||
requiring a different activation contract (new env vars it depends on,
|
||||
changed chaining behavior, etc.), independent of any package semver, for
|
||||
the same reason C1's constant is: #828 happened precisely because a
|
||||
version number that should have moved did not.
|
||||
|
||||
This module never talks to a real broker or a real installed CLI in its
|
||||
own tests — both the probe's command resolution and its ``run`` transport
|
||||
are injectable so tests can drive every branch with fakes/stubs (see
|
||||
``version_coupling_unittest.py``).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import shlex
|
||||
import shutil
|
||||
import subprocess
|
||||
from collections.abc import Callable, Mapping
|
||||
from typing import Final, TypedDict
|
||||
|
||||
|
||||
class ActivationCapability(TypedDict):
|
||||
name: str
|
||||
version: int
|
||||
|
||||
|
||||
# ENFORCEMENT-side expected activation contract. OWNED by this toolkit (the
|
||||
# enforcement half). Mirrors — but is deliberately a SEPARATE constant from
|
||||
# — `LEASE_ACTIVATION_CAPABILITY` in
|
||||
# `packages/mosaic/src/commands/lease-activation-probe.ts` (the activation
|
||||
# half's own declaration of what it implements). The two are compared at
|
||||
# runtime by `assert_activation_capability_matches()`; drift between them is
|
||||
# exactly the version-skew failure mode #828/#869 exist to catch, and must
|
||||
# FAIL LOUD, never a silent pass and never a dead (always-true) gate.
|
||||
EXPECTED_ACTIVATION_CAPABILITY: Final[ActivationCapability] = {
|
||||
"name": "lease-runtime-activation",
|
||||
"version": 1,
|
||||
}
|
||||
|
||||
# Matches `LEASE_CAPABILITY_PROBE_COMMAND` in lease-activation-probe.ts —
|
||||
# the hidden CLI subcommand that prints the activation half's advertised
|
||||
# capability as compact JSON.
|
||||
LEASE_CAPABILITY_PROBE_COMMAND: Final = "__lease-capability"
|
||||
|
||||
PROBE_TIMEOUT_SECONDS: Final = 2.0
|
||||
|
||||
# Override hook: a full shell-style command line (parsed with `shlex.split`)
|
||||
# to run INSTEAD of resolving `mosaic` on PATH and appending the probe
|
||||
# subcommand. Real deployments should never need this — `mosaic` is on PATH
|
||||
# whenever a runtime was launched via `mosaic <cmd>` in the first place, the
|
||||
# only real caller of this seam. It exists for integration tests that spawn
|
||||
# `launch-runtime.py` directly (never through the real CLI) to supply a
|
||||
# fake/stub CLI probe, matching the existing convention of those tests
|
||||
# supplying a fake broker and a fake runtime binary rather than depending on
|
||||
# host state.
|
||||
MOSAIC_COMMAND_OVERRIDE_VAR: Final = "MOSAIC_LEASE_VERSION_PROBE_COMMAND"
|
||||
|
||||
|
||||
class VersionCouplingError(Exception):
|
||||
"""Raised when the activation capability is absent, unreadable, or does
|
||||
not match what enforcement expects. Callers MUST fail loud on this
|
||||
(non-zero exit, clear actionable stderr) — never swallow it into a
|
||||
silent pass, and never let its absence be treated as compatible."""
|
||||
|
||||
|
||||
def _resolve_probe_command(environ: Mapping[str, str]) -> list[str] | None:
|
||||
override = environ.get(MOSAIC_COMMAND_OVERRIDE_VAR)
|
||||
if override:
|
||||
parsed = shlex.split(override)
|
||||
return parsed or None
|
||||
resolved = shutil.which("mosaic")
|
||||
if resolved is None:
|
||||
return None
|
||||
return [resolved, LEASE_CAPABILITY_PROBE_COMMAND]
|
||||
|
||||
|
||||
def default_probe_activation_capability(
|
||||
environ: Mapping[str, str] | None = None,
|
||||
*,
|
||||
run: Callable[..., subprocess.CompletedProcess[str]] = subprocess.run,
|
||||
) -> ActivationCapability | None:
|
||||
"""Real capability lookup: resolves and executes the CLI's hidden
|
||||
``__lease-capability`` probe subcommand out-of-process (the same
|
||||
mechanism `defaultCapabilityProbe()` in lease-activation-probe.ts uses
|
||||
from the activation side) and parses its JSON stdout. Any failure to
|
||||
resolve a command, spawn it, have it exit zero, or produce a well-shaped
|
||||
``{name, version}`` JSON object is treated as NO capability (``None``)
|
||||
— fail-closed, never a fabricated/guessed capability.
|
||||
"""
|
||||
source_environment = os.environ if environ is None else environ
|
||||
command = _resolve_probe_command(source_environment)
|
||||
if command is None:
|
||||
return None
|
||||
try:
|
||||
completed = run(
|
||||
command,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=PROBE_TIMEOUT_SECONDS,
|
||||
check=False,
|
||||
)
|
||||
except (OSError, subprocess.TimeoutExpired, ValueError):
|
||||
return None
|
||||
if completed.returncode != 0:
|
||||
return None
|
||||
try:
|
||||
parsed = json.loads(completed.stdout)
|
||||
except json.JSONDecodeError:
|
||||
return None
|
||||
if (
|
||||
not isinstance(parsed, dict)
|
||||
or not isinstance(parsed.get("name"), str)
|
||||
or not isinstance(parsed.get("version"), int)
|
||||
or isinstance(parsed.get("version"), bool)
|
||||
):
|
||||
return None
|
||||
return {"name": parsed["name"], "version": parsed["version"]}
|
||||
|
||||
|
||||
def format_mismatch_message(
|
||||
activation: ActivationCapability | None,
|
||||
expected: ActivationCapability,
|
||||
) -> str:
|
||||
"""Actionable, non-silent remediation message for either failure shape:
|
||||
absent/unreadable capability, or a present-but-incompatible one."""
|
||||
if activation is None:
|
||||
return (
|
||||
"Mosaic lease activation capability unreadable: enforcement "
|
||||
f"expects '{expected['name']}' v{expected['version']} but the "
|
||||
f"CLI's `mosaic {LEASE_CAPABILITY_PROBE_COMMAND}` probe produced "
|
||||
"no usable result (mosaic not on PATH, non-zero exit, or "
|
||||
"malformed output) — framework/CLI version skew; upgrade both "
|
||||
"as one unit; see #869."
|
||||
)
|
||||
if activation["name"] != expected["name"]:
|
||||
return (
|
||||
f"activation capability name '{activation['name']}' != "
|
||||
f"enforcement expects '{expected['name']}' — framework/CLI "
|
||||
"version skew; upgrade both as one unit; see #869"
|
||||
)
|
||||
return (
|
||||
f"activation capability v{activation['version']} != enforcement "
|
||||
f"expects v{expected['version']} — framework/CLI version skew; "
|
||||
"upgrade both as one unit; see #869"
|
||||
)
|
||||
|
||||
|
||||
def assert_activation_capability_matches(
|
||||
activation: ActivationCapability | None,
|
||||
expected: ActivationCapability = EXPECTED_ACTIVATION_CAPABILITY,
|
||||
) -> None:
|
||||
"""Raise `VersionCouplingError` unless `activation` is present AND its
|
||||
`name`/`version` exactly match `expected`. Absence is treated the same
|
||||
as a mismatch — never a silent pass."""
|
||||
if (
|
||||
activation is None
|
||||
or activation.get("name") != expected["name"]
|
||||
or activation.get("version") != expected["version"]
|
||||
):
|
||||
raise VersionCouplingError(format_mismatch_message(activation, expected))
|
||||
@@ -12,11 +12,24 @@ from collections.abc import Callable, Mapping, Sequence
|
||||
from pathlib import Path
|
||||
from typing import Final
|
||||
|
||||
from activation_version_gate import (
|
||||
EXPECTED_ACTIVATION_CAPABILITY,
|
||||
ActivationCapability,
|
||||
VersionCouplingError,
|
||||
assert_activation_capability_matches,
|
||||
default_probe_activation_capability,
|
||||
)
|
||||
from lease_generation import initialize_runtime_generation
|
||||
|
||||
MAX_FRAME: Final = 64 * 1024
|
||||
BROKER_TIMEOUT_SECONDS: Final = 1.5
|
||||
CLAUDE_DANGEROUS_FLAG: Final = "--dangerously-skip-permissions"
|
||||
# Distinct, non-overlapping exit code for the C4 version-coupling gate (see
|
||||
# `activation_version_gate.py`) — deliberately different from the `1`
|
||||
# (broker registration failed closed) and `64` (usage error) codes already
|
||||
# owned by this script, so a version-skew denial is unambiguous in caller
|
||||
# logs/tests and is never confused with a broker-availability failure.
|
||||
EXIT_VERSION_SKEW: Final = 65
|
||||
|
||||
|
||||
def broker_request(socket_path: Path, request: dict[str, object]) -> dict[str, object]:
|
||||
@@ -47,6 +60,10 @@ def main(
|
||||
request: Callable[[Path, dict[str, object]], dict[str, object]] = broker_request,
|
||||
execute: Callable[[str, list[str], dict[str, str]], object] = os.execvpe,
|
||||
initialize_generation: Callable[[Path, int], None] = initialize_runtime_generation,
|
||||
probe_activation_capability: Callable[
|
||||
[Mapping[str, str]], ActivationCapability | None
|
||||
] = default_probe_activation_capability,
|
||||
expected_activation_capability: ActivationCapability = EXPECTED_ACTIVATION_CAPABILITY,
|
||||
) -> int:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--runtime", required=True, choices=("claude", "pi"))
|
||||
@@ -66,6 +83,25 @@ def main(
|
||||
command = [command[0], CLAUDE_DANGEROUS_FLAG, *command[1:]]
|
||||
|
||||
source_environment = os.environ if environ is None else environ
|
||||
|
||||
# C4 version-coupling gate (#869 Point-1): before this ENFORCEMENT half
|
||||
# chains into anything, assert that the ACTIVATION contract it is about
|
||||
# to rely on (MOSAIC_LEASE_* injection, broker chaining) matches what
|
||||
# this enforcement build expects. This is a build/deploy-defect check,
|
||||
# not a broker-availability question, so it runs before — and
|
||||
# independently of — broker registration below, and it FAILS LOUD: a
|
||||
# clear stderr message plus a dedicated non-zero exit code, never a
|
||||
# silent pass and never folded into the generic registration-failure
|
||||
# branch.
|
||||
try:
|
||||
assert_activation_capability_matches(
|
||||
probe_activation_capability(source_environment),
|
||||
expected_activation_capability,
|
||||
)
|
||||
except VersionCouplingError as version_error:
|
||||
print(str(version_error), file=sys.stderr)
|
||||
return EXIT_VERSION_SKEW
|
||||
|
||||
try:
|
||||
socket_path = Path(source_environment["MOSAIC_LEASE_BROKER_SOCKET"])
|
||||
generation = int(source_environment.get("MOSAIC_RUNTIME_GENERATION", "1"))
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
"lint": "eslint src",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run --passWithNoTests && pnpm run test:framework-shell",
|
||||
"test:framework-shell": "python3 src/lease-broker/daemon_deadline_unittest.py && python3 src/lease-broker/normative_fragments_unittest.py && python3 src/lease-broker/receipt_challenge_unittest.py && python3 src/lease-broker/context_recovery_unittest.py && python3 src/lease-broker/recovery_runtime_unittest.py && python3 src/lease-broker/recovery_b1_adversarial_unittest.py && python3 src/lease-broker/framework_skill_portability_unittest.py && python3 src/mutator-gate/runtime_tools_unittest.py && python3 src/mutator-gate/runtime_launch_guard_unittest.py && python3 framework/tools/lease-broker/check-runtime-launches.py --root ../.. && bash framework/tools/codex/test-pr-diff-context.sh && bash framework/tools/qa/test-deps-preflight.sh && bash framework/tools/git/test-pr-review-gitea-comment.sh && bash framework/tools/git/test-ci-queue-wait-branch-absent.sh && bash framework/tools/git/test-git-credential-mosaic.sh && bash framework/tools/git/test-gitea-token-identity.sh && bash framework/tools/_scripts/test-install-ordering-guard.sh"
|
||||
"test:framework-shell": "python3 src/lease-broker/daemon_deadline_unittest.py && python3 src/lease-broker/normative_fragments_unittest.py && python3 src/lease-broker/receipt_challenge_unittest.py && python3 src/lease-broker/context_recovery_unittest.py && python3 src/lease-broker/recovery_runtime_unittest.py && python3 src/lease-broker/recovery_b1_adversarial_unittest.py && python3 src/lease-broker/framework_skill_portability_unittest.py && python3 src/mutator-gate/runtime_tools_unittest.py && python3 src/mutator-gate/runtime_launch_guard_unittest.py && python3 src/mutator-gate/version_coupling_unittest.py && python3 framework/tools/lease-broker/check-runtime-launches.py --root ../.. && bash framework/tools/codex/test-pr-diff-context.sh && bash framework/tools/qa/test-deps-preflight.sh && bash framework/tools/git/test-pr-review-gitea-comment.sh && bash framework/tools/git/test-ci-queue-wait-branch-absent.sh && bash framework/tools/git/test-git-credential-mosaic.sh && bash framework/tools/git/test-gitea-token-identity.sh && bash framework/tools/_scripts/test-install-ordering-guard.sh"
|
||||
},
|
||||
"dependencies": {
|
||||
"@mosaicstack/brain": "workspace:*",
|
||||
|
||||
@@ -32,10 +32,7 @@ import {
|
||||
formatAllPackagesTable,
|
||||
getInstallAllCommand,
|
||||
repairFleetCommsTools,
|
||||
runFrameworkReseed,
|
||||
refreshActiveFleetUnits,
|
||||
readRosterAgentNames,
|
||||
buildRelaunchCommands,
|
||||
runUpdateReseedFlow,
|
||||
checkFrameworkDrift,
|
||||
FRAMEWORK_RESEED_PACKAGE,
|
||||
} from './runtime/update-checker.js';
|
||||
@@ -445,12 +442,18 @@ program
|
||||
'--repair-tools',
|
||||
'Restore the supported current-version TOOLS contract and executable fleet helper',
|
||||
)
|
||||
.option(
|
||||
'--allow-inactive-enforcement',
|
||||
'Wire lease-enforcement hooks into settings.json even when activation cannot be confirmed ' +
|
||||
'(explicit, loud, non-default opt-out for the post-reseed install-ordering guard — see #869/#882)',
|
||||
)
|
||||
.action(
|
||||
async (opts: {
|
||||
check?: boolean;
|
||||
reseed?: boolean;
|
||||
relaunch?: boolean;
|
||||
repairTools?: boolean;
|
||||
allowInactiveEnforcement?: boolean;
|
||||
}) => {
|
||||
if (opts.repairTools) {
|
||||
const repair = repairFleetCommsTools();
|
||||
@@ -471,57 +474,24 @@ program
|
||||
// checkForAllUpdates imported statically above
|
||||
const { execSync } = await import('node:child_process');
|
||||
|
||||
// Re-seed the framework from the freshly-installed package, propagate shipped
|
||||
// systemd unit fixes to the active units, and (opt-in) relaunch durable
|
||||
// agents. Shared by the "packages updated" and the "framework drift" paths.
|
||||
// Re-seed the framework from the freshly-installed package, re-apply the
|
||||
// install-ordering guard to settings.json (#882 (b) — closes the
|
||||
// `--sync-only` bypass so `mosaic update` never leaves enforcement-hook
|
||||
// wiring stale/unguarded), propagate shipped systemd unit fixes to the
|
||||
// active units, and (opt-in) relaunch durable agents. Shared by the
|
||||
// "packages updated" and the "framework drift" paths. Extracted to
|
||||
// update-checker.ts (`runUpdateReseedFlow`) for direct unit testability.
|
||||
const reseedFramework = (reason: string): void => {
|
||||
console.log(reason);
|
||||
const reseed = runFrameworkReseed();
|
||||
if (!reseed.ok) {
|
||||
console.error(
|
||||
`\n⚠ Framework re-seed skipped: ${reseed.reason ?? 'unknown'}.\n` +
|
||||
' Activate manually: bash "$(npm root -g)/@mosaicstack/mosaic/framework/install.sh" ' +
|
||||
'(MOSAIC_SYNC_ONLY=1 MOSAIC_INSTALL_MODE=keep)',
|
||||
);
|
||||
return;
|
||||
}
|
||||
console.log('✔ Framework re-seeded.');
|
||||
if (reseed.skillSyncError) {
|
||||
console.error(` ⚠ Claude skill reconciliation skipped: ${reseed.skillSyncError}`);
|
||||
}
|
||||
const skillConflicts = reseed.skillSync?.conflicts ?? [];
|
||||
const skillChanges =
|
||||
(reseed.skillSync?.registered.length ?? 0) + (reseed.skillSync?.repaired.length ?? 0);
|
||||
if (skillChanges > 0) {
|
||||
console.log(`✔ Registered ${skillChanges.toString()} Mosaic skill(s) with Claude Code.`);
|
||||
}
|
||||
for (const conflict of skillConflicts) {
|
||||
console.error(` ⚠ Skill registration skipped for ${conflict.name}: ${conflict.reason}`);
|
||||
}
|
||||
// Propagate shipped systemd unit fixes to the ACTIVE units (re-seed only
|
||||
// touches ~/.config/mosaic/systemd/user; systemd runs ~/.config/systemd/user).
|
||||
const units = refreshActiveFleetUnits();
|
||||
if (units.refreshed.length > 0) {
|
||||
console.log(`✔ Refreshed ${units.refreshed.length} active systemd unit(s).`);
|
||||
}
|
||||
const agents = readRosterAgentNames();
|
||||
if (agents.length === 0) return;
|
||||
if (opts.relaunch) {
|
||||
console.log(`\nRelaunching ${agents.length} fleet agent(s) to pick up the new runtime…`);
|
||||
for (const restart of buildRelaunchCommands(agents)) {
|
||||
try {
|
||||
execSync(restart.join(' '), { stdio: 'inherit', timeout: 30_000 });
|
||||
} catch {
|
||||
console.error(` ⚠ failed to restart agent — run: ${restart.join(' ')}`);
|
||||
}
|
||||
}
|
||||
console.log('✔ Agents relaunched.');
|
||||
} else {
|
||||
console.log(
|
||||
`\nℹ ${agents.length} fleet agent(s) are still running the previous runtime. ` +
|
||||
'Restart them to activate the update:\n mosaic update --relaunch ' +
|
||||
'(or: mosaic fleet restart <agent>)',
|
||||
);
|
||||
const flow = runUpdateReseedFlow(reason, {
|
||||
reseed: opts.reseed,
|
||||
relaunch: opts.relaunch,
|
||||
allowInactiveEnforcement: opts.allowInactiveEnforcement === true,
|
||||
});
|
||||
if (flow.settingsGuard?.ran && flow.settingsGuard.result?.exitCode === 1) {
|
||||
// Fail-loud: enforcement hooks were refused/stripped. Surface this
|
||||
// in the command's own exit status without aborting the rest of
|
||||
// the update (mirrors mosaic-link-runtime-assets' guard_degraded).
|
||||
process.exitCode = 1;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -544,7 +514,7 @@ program
|
||||
// package is reported outdated. Detect that via the framework version and
|
||||
// re-seed so shipped launcher/runtime fixes still activate.
|
||||
const drift = checkFrameworkDrift();
|
||||
if (drift.drifted && opts.reseed !== false) {
|
||||
if (drift.drifted) {
|
||||
reseedFramework(
|
||||
`\nFramework drift detected (on-disk v${drift.installed} < bundled v${drift.bundled}) — ` +
|
||||
'the CLI was updated outside `mosaic update`. Re-seeding framework files into ' +
|
||||
@@ -582,7 +552,7 @@ program
|
||||
(r: { package: string }) => r.package === FRAMEWORK_RESEED_PACKAGE,
|
||||
);
|
||||
const drift = checkFrameworkDrift();
|
||||
if ((mosaicUpdated || drift.drifted) && opts.reseed !== false) {
|
||||
if (mosaicUpdated || drift.drifted) {
|
||||
reseedFramework(
|
||||
'\nRe-seeding framework files into ~/.config/mosaic (data-safe; keeps your edits)…',
|
||||
);
|
||||
|
||||
@@ -28,6 +28,7 @@ import { readRegularFileSecure } from '../fleet/secure-file.js';
|
||||
import { readPersonaContractBlock } from '../fleet/persona-contract.js';
|
||||
import { canonicalizeRoleClass } from './fleet-personas.js';
|
||||
import { launchClaudex, type ClaudexHarnessAdapter } from './claudex.js';
|
||||
import { runLeaseEnforcementDoctorCheck } from './lease-doctor-check.js';
|
||||
|
||||
const MOSAIC_HOME = process.env['MOSAIC_HOME'] ?? join(homedir(), '.config', 'mosaic');
|
||||
const MAX_INSTALLED_TOOLS_BYTES = 256 * 1024;
|
||||
@@ -1237,7 +1238,6 @@ export function registerLaunchCommands(program: Command): void {
|
||||
// Direct framework script delegates
|
||||
const directCommands: Record<string, { desc: string; script: string }> = {
|
||||
init: { desc: 'Generate SOUL.md (agent identity contract)', script: 'mosaic-init' },
|
||||
doctor: { desc: 'Health audit — detect drift and missing files', script: 'mosaic-doctor' },
|
||||
sync: { desc: 'Sync skills from canonical source', script: 'mosaic-sync-skills' },
|
||||
bootstrap: {
|
||||
desc: 'Bootstrap a repo with Mosaic standards',
|
||||
@@ -1256,4 +1256,67 @@ export function registerLaunchCommands(program: Command): void {
|
||||
delegateToScript(fwScript(script), cmd.args);
|
||||
});
|
||||
}
|
||||
|
||||
// `doctor` — the framework drift audit (bash script) PLUS the #869
|
||||
// Point-1 C5 lease-enforcement activation check (TS, reusing C1's
|
||||
// `leaseEnforcementActivatable()` and C3's `checkBrokerSupervisorHealth()`).
|
||||
// Kept out of the generic `directCommands` loop above because this check
|
||||
// must run and report BEFORE the bash script's own exit, and must be able
|
||||
// to force a non-zero exit on its own — a silent pass on "enforcement
|
||||
// hooks wired but activation absent" would leave a bricked host
|
||||
// undiagnosed (see lease-doctor-check.ts docstring).
|
||||
program
|
||||
.command('doctor')
|
||||
.description('Health audit — detect drift, missing files, and #869 lease-activation gaps')
|
||||
.allowUnknownOption(true)
|
||||
.allowExcessArguments(true)
|
||||
.action(async (_opts: unknown, cmd: Command) => {
|
||||
checkMosaicHome();
|
||||
const leaseCheck = await runLeaseEnforcementDoctorCheck();
|
||||
const leaseCheckFailed = printLeaseDoctorCheck(leaseCheck);
|
||||
runDoctorScriptAndExit(fwScript('mosaic-doctor'), cmd.args, leaseCheckFailed);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Print the #869 C5 lease-enforcement doctor result using the same
|
||||
* `[mosaic-doctor]` prefix the bash audit script uses, but with a distinct
|
||||
* `[ERROR]` severity token (louder than the script's own `[WARN]`) — this is
|
||||
* a hard, actionable brick warning, not a soft drift warning, and must never
|
||||
* read as just one more line among the script's routine warnings. Silent on
|
||||
* an `ok` result, matching this file's other pre-flight checks
|
||||
* (`checkMosaicHome`, `checkFile`, `checkRuntime`) which only print on
|
||||
* failure. Returns whether the check failed, so the caller can force a
|
||||
* non-zero exit regardless of the bash script's own exit code.
|
||||
*/
|
||||
function printLeaseDoctorCheck(
|
||||
result: Awaited<ReturnType<typeof runLeaseEnforcementDoctorCheck>>,
|
||||
): boolean {
|
||||
if (result.status === 'error') {
|
||||
console.error(`[mosaic-doctor] [ERROR] ${result.message}`);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run the bash `mosaic-doctor` audit script (inheriting stdio, same as
|
||||
* {@link delegateToScript}) and exit with a non-zero code if EITHER the
|
||||
* script itself reported failure OR the lease-enforcement check above did —
|
||||
* so `--fail-on-warn` and other script-level exit semantics are preserved,
|
||||
* but the lease-enforcement ERROR can never be masked by an otherwise-green
|
||||
* script run.
|
||||
*/
|
||||
function runDoctorScriptAndExit(scriptPath: string, args: string[], forceFailure: boolean): never {
|
||||
if (!existsSync(scriptPath)) {
|
||||
console.error(`[mosaic] Script not found: ${scriptPath}`);
|
||||
process.exit(1);
|
||||
}
|
||||
let scriptExitCode = 0;
|
||||
try {
|
||||
execFileSync('bash', [scriptPath, ...args], { stdio: 'inherit', env: process.env });
|
||||
} catch (err) {
|
||||
scriptExitCode = (err as { status?: number }).status ?? 1;
|
||||
}
|
||||
process.exit(forceFailure ? 1 : scriptExitCode);
|
||||
}
|
||||
|
||||
196
packages/mosaic/src/commands/lease-doctor-check.spec.ts
Normal file
196
packages/mosaic/src/commands/lease-doctor-check.spec.ts
Normal file
@@ -0,0 +1,196 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
detectEnforcementHooksWired,
|
||||
runLeaseEnforcementDoctorCheck,
|
||||
} from './lease-doctor-check.js';
|
||||
|
||||
/**
|
||||
* Red-first tests for issue #869 Point-1 C5 — the `mosaic doctor`
|
||||
* lease-enforcement surfacing check.
|
||||
*
|
||||
* Root cause under test: enforcement hooks (`mutator-gate.py`,
|
||||
* `receipt-observer-client.py`) can be wired into `~/.claude/settings.json`
|
||||
* on a host where C1's `leaseEnforcementActivatable()` is false and/or C3's
|
||||
* `checkBrokerSupervisorHealth()` reports unhealthy. That combination fails
|
||||
* closed correctly, but must be surfaced LOUDLY by `mosaic doctor` rather
|
||||
* than silently passing — this test suite exercises the three primary
|
||||
* branches (wired+not-activatable, wired+healthy, not-wired) plus the
|
||||
* broker-unhealthy variant.
|
||||
*
|
||||
* Every dependency is injected — no real `~/.claude/settings.json` and no
|
||||
* real broker are ever touched.
|
||||
*/
|
||||
|
||||
const WIRED_SETTINGS_JSON = JSON.stringify({
|
||||
hooks: {
|
||||
PreToolUse: [
|
||||
{
|
||||
matcher: '.*',
|
||||
hooks: [
|
||||
{
|
||||
type: 'command',
|
||||
command: 'python3 ~/.config/mosaic/tools/lease-broker/mutator-gate.py --runtime claude',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
Stop: [
|
||||
{
|
||||
hooks: [
|
||||
{
|
||||
type: 'command',
|
||||
command:
|
||||
'python3 ~/.config/mosaic/tools/lease-broker/receipt-observer-client.py --runtime claude --latest-entry',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const UNWIRED_SETTINGS_JSON = JSON.stringify({
|
||||
hooks: {
|
||||
PostToolUse: [
|
||||
{
|
||||
matcher: 'Edit|MultiEdit|Write',
|
||||
hooks: [{ type: 'command', command: '~/.config/mosaic/tools/qa/qa-hook-stdin.sh' }],
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
describe('detectEnforcementHooksWired', () => {
|
||||
it('detects the mutator-gate + receipt-observer markers when wired', () => {
|
||||
const result = detectEnforcementHooksWired(JSON.parse(WIRED_SETTINGS_JSON));
|
||||
expect(result.wired).toBe(true);
|
||||
expect(result.matchedMarkers).toEqual(
|
||||
expect.arrayContaining(['mutator-gate.py', 'receipt-observer-client.py']),
|
||||
);
|
||||
});
|
||||
|
||||
it('reports not wired when no enforcement markers are present', () => {
|
||||
const result = detectEnforcementHooksWired(JSON.parse(UNWIRED_SETTINGS_JSON));
|
||||
expect(result.wired).toBe(false);
|
||||
expect(result.matchedMarkers).toEqual([]);
|
||||
});
|
||||
|
||||
it('reports not wired for an empty settings object', () => {
|
||||
expect(detectEnforcementHooksWired({}).wired).toBe(false);
|
||||
});
|
||||
|
||||
it('detects wiring from just ONE marker (partial wiring is still dangerous)', () => {
|
||||
const onlyMutatorGate = JSON.stringify({
|
||||
hooks: {
|
||||
PreToolUse: [
|
||||
{
|
||||
hooks: [{ type: 'command', command: 'python3 .../mutator-gate.py --runtime claude' }],
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
const result = detectEnforcementHooksWired(JSON.parse(onlyMutatorGate));
|
||||
expect(result.wired).toBe(true);
|
||||
expect(result.matchedMarkers).toEqual(['mutator-gate.py']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('runLeaseEnforcementDoctorCheck', () => {
|
||||
it('RED: wired + not-activatable ⇒ LOUD error (not a silent pass)', async () => {
|
||||
const result = await runLeaseEnforcementDoctorCheck({
|
||||
readSettingsRaw: () => WIRED_SETTINGS_JSON,
|
||||
isActivatable: () => false,
|
||||
isBrokerHealthy: async () => true,
|
||||
});
|
||||
|
||||
expect(result.status).toBe('error');
|
||||
expect(result.wired).toBe(true);
|
||||
expect(result.activatable).toBe(false);
|
||||
expect(result.message).toMatch(/activation absent/);
|
||||
expect(result.message).toMatch(/#869/);
|
||||
expect(result.message.toLowerCase()).toMatch(/brick/);
|
||||
});
|
||||
|
||||
it('wired + activatable + broker-unhealthy ⇒ LOUD error', async () => {
|
||||
const result = await runLeaseEnforcementDoctorCheck({
|
||||
readSettingsRaw: () => WIRED_SETTINGS_JSON,
|
||||
isActivatable: () => true,
|
||||
isBrokerHealthy: async () => false,
|
||||
});
|
||||
|
||||
expect(result.status).toBe('error');
|
||||
expect(result.wired).toBe(true);
|
||||
expect(result.brokerHealthy).toBe(false);
|
||||
expect(result.message).toMatch(/broker not healthy/);
|
||||
});
|
||||
|
||||
it('wired + not-activatable + broker-unhealthy ⇒ LOUD error citing both reasons', async () => {
|
||||
const result = await runLeaseEnforcementDoctorCheck({
|
||||
readSettingsRaw: () => WIRED_SETTINGS_JSON,
|
||||
isActivatable: () => false,
|
||||
isBrokerHealthy: async () => false,
|
||||
});
|
||||
|
||||
expect(result.status).toBe('error');
|
||||
expect(result.message).toMatch(/activation absent/);
|
||||
expect(result.message).toMatch(/broker not healthy/);
|
||||
});
|
||||
|
||||
it('GREEN: wired + activatable + broker-healthy ⇒ ok', async () => {
|
||||
const result = await runLeaseEnforcementDoctorCheck({
|
||||
readSettingsRaw: () => WIRED_SETTINGS_JSON,
|
||||
isActivatable: () => true,
|
||||
isBrokerHealthy: async () => true,
|
||||
});
|
||||
|
||||
expect(result.status).toBe('ok');
|
||||
expect(result.wired).toBe(true);
|
||||
expect(result.activatable).toBe(true);
|
||||
expect(result.brokerHealthy).toBe(true);
|
||||
});
|
||||
|
||||
it('GREEN: not-wired ⇒ ok, no false alarm (activation/broker never probed)', async () => {
|
||||
let activatableCalled = false;
|
||||
let brokerCalled = false;
|
||||
|
||||
const result = await runLeaseEnforcementDoctorCheck({
|
||||
readSettingsRaw: () => UNWIRED_SETTINGS_JSON,
|
||||
isActivatable: () => {
|
||||
activatableCalled = true;
|
||||
return false;
|
||||
},
|
||||
isBrokerHealthy: async () => {
|
||||
brokerCalled = true;
|
||||
return false;
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.status).toBe('ok');
|
||||
expect(result.wired).toBe(false);
|
||||
expect(result.activatable).toBeNull();
|
||||
expect(result.brokerHealthy).toBeNull();
|
||||
// Not wired must short-circuit — never even consult activation/broker.
|
||||
expect(activatableCalled).toBe(false);
|
||||
expect(brokerCalled).toBe(false);
|
||||
});
|
||||
|
||||
it('GREEN: settings.json absent ⇒ ok (never touches a real file — readSettingsRaw is injected)', async () => {
|
||||
const result = await runLeaseEnforcementDoctorCheck({
|
||||
readSettingsRaw: () => null,
|
||||
isActivatable: () => false,
|
||||
isBrokerHealthy: async () => false,
|
||||
});
|
||||
|
||||
expect(result.status).toBe('ok');
|
||||
expect(result.wired).toBe(false);
|
||||
});
|
||||
|
||||
it('GREEN: malformed settings.json ⇒ ok (parse errors are not this card’s failure class)', async () => {
|
||||
const result = await runLeaseEnforcementDoctorCheck({
|
||||
readSettingsRaw: () => '{ not valid json',
|
||||
isActivatable: () => false,
|
||||
isBrokerHealthy: async () => false,
|
||||
});
|
||||
|
||||
expect(result.status).toBe('ok');
|
||||
});
|
||||
});
|
||||
210
packages/mosaic/src/commands/lease-doctor-check.ts
Normal file
210
packages/mosaic/src/commands/lease-doctor-check.ts
Normal file
@@ -0,0 +1,210 @@
|
||||
/**
|
||||
* Lease-enforcement doctor check (issue #869, Point-1 card C5).
|
||||
*
|
||||
* Root cause this guards against (#828 version skew, the same one C1/C3
|
||||
* exist for): the Claude Code enforcement hooks (`mutator-gate.py` gating
|
||||
* PreToolUse, `receipt-observer-client.py` observing Stop) can be WIRED into
|
||||
* `~/.claude/settings.json` on a host where the ACTIVATION half is absent —
|
||||
* no compatible CLI build (C1's `leaseEnforcementActivatable()`), or no
|
||||
* healthy broker supervisor (C3's `checkBrokerSupervisorHealth()`). That
|
||||
* combination is a silent brick: every gated tool call denies with
|
||||
* GATE_UNAVAILABLE, and the fail-closed behavior is *correct* — but nothing
|
||||
* surfaces it to an operator running `mosaic doctor` on an already-bricked
|
||||
* host.
|
||||
*
|
||||
* This module answers one question — "if I ran right now, would I be
|
||||
* bricked?" — by combining:
|
||||
*
|
||||
* 1. wiring detection: does `~/.claude/settings.json` reference either
|
||||
* enforcement-hook marker (`mutator-gate.py` / `receipt-observer-client.py`)?
|
||||
* 2. C1's `leaseEnforcementActivatable()` — could activation satisfy
|
||||
* enforcement if it were exercised right now?
|
||||
* 3. C3's `checkBrokerSupervisorHealth()` — is the broker supervisor
|
||||
* actually healthy?
|
||||
*
|
||||
* Not wired ⇒ ok (nothing to activate, no false alarm). Wired AND activatable
|
||||
* AND broker-healthy ⇒ ok. Wired AND (NOT activatable OR broker unhealthy) ⇒
|
||||
* a LOUD, actionable error — this module never silently passes that state.
|
||||
*
|
||||
* Every dependency (settings read, activation probe, broker-health check) is
|
||||
* injectable so tests can drive every branch without ever touching a real
|
||||
* `~/.claude/settings.json` or a real broker.
|
||||
*/
|
||||
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { homedir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { leaseEnforcementActivatable, type ActivationProbeDeps } from './lease-activation-probe.js';
|
||||
import {
|
||||
checkBrokerSupervisorHealth,
|
||||
resolveBrokerSupervisorPaths,
|
||||
} from '../lease-broker/broker-supervisor.js';
|
||||
import { DEFAULT_MOSAIC_HOME } from '../constants.js';
|
||||
|
||||
/** Markers identifying the two enforcement-hook halves wired via the
|
||||
* framework reseed. Either marker's presence in `settings.json` means
|
||||
* enforcement is wired — a host can be bricked with just one half present. */
|
||||
const ENFORCEMENT_HOOK_MARKERS = ['mutator-gate.py', 'receipt-observer-client.py'] as const;
|
||||
|
||||
export interface EnforcementHooksWiredResult {
|
||||
readonly wired: boolean;
|
||||
readonly matchedMarkers: readonly string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Detect whether the Claude Code enforcement hooks (mutator-gate /
|
||||
* receipt-observer) are wired into an already-parsed `settings.json`.
|
||||
* Pure/testable — takes parsed JSON, never touches the filesystem itself.
|
||||
*/
|
||||
export function detectEnforcementHooksWired(settings: unknown): EnforcementHooksWiredResult {
|
||||
const serialized = JSON.stringify(settings ?? {});
|
||||
const matchedMarkers = ENFORCEMENT_HOOK_MARKERS.filter((marker) => serialized.includes(marker));
|
||||
return { wired: matchedMarkers.length > 0, matchedMarkers };
|
||||
}
|
||||
|
||||
export interface LeaseDoctorCheckDeps {
|
||||
/**
|
||||
* Read raw `settings.json` text; return `null` if the file is absent.
|
||||
* Defaults to reading the real `~/.claude/settings.json`. ALWAYS inject a
|
||||
* fake in tests — never point this at a real host's settings file.
|
||||
*/
|
||||
readSettingsRaw?: () => string | null;
|
||||
/** Defaults to {@link leaseEnforcementActivatable} (C1). Inject for tests. */
|
||||
isActivatable?: (deps?: ActivationProbeDeps) => boolean;
|
||||
/**
|
||||
* Defaults to a real broker-supervisor health check (C3) rooted at
|
||||
* `mosaicHome`. Inject for tests — never point this at a real broker.
|
||||
*/
|
||||
isBrokerHealthy?: () => Promise<boolean>;
|
||||
/** Mosaic home used to resolve default broker-supervisor paths. Defaults to
|
||||
* `$MOSAIC_HOME` or `~/.config/mosaic`. */
|
||||
mosaicHome?: string;
|
||||
}
|
||||
|
||||
export type LeaseDoctorCheckStatus = 'ok' | 'error';
|
||||
|
||||
export interface LeaseDoctorCheckResult {
|
||||
readonly status: LeaseDoctorCheckStatus;
|
||||
readonly wired: boolean;
|
||||
/** `null` when hooks are not wired (activation/broker were never probed). */
|
||||
readonly activatable: boolean | null;
|
||||
/** `null` when hooks are not wired (activation/broker were never probed). */
|
||||
readonly brokerHealthy: boolean | null;
|
||||
readonly message: string;
|
||||
}
|
||||
|
||||
function defaultReadSettingsRaw(): string | null {
|
||||
const settingsPath = join(homedir(), '.claude', 'settings.json');
|
||||
try {
|
||||
return readFileSync(settingsPath, 'utf8');
|
||||
} catch (error) {
|
||||
if (isEnoent(error)) return null;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function isEnoent(error: unknown): boolean {
|
||||
return (
|
||||
typeof error === 'object' &&
|
||||
error !== null &&
|
||||
'code' in error &&
|
||||
(error as NodeJS.ErrnoException).code === 'ENOENT'
|
||||
);
|
||||
}
|
||||
|
||||
function defaultMosaicHome(): string {
|
||||
return process.env['MOSAIC_HOME'] ?? DEFAULT_MOSAIC_HOME;
|
||||
}
|
||||
|
||||
async function defaultIsBrokerHealthy(mosaicHome: string): Promise<boolean> {
|
||||
// `frameworkRoot` only feeds SOURCE paths (unit/wrapper/daemon file
|
||||
// locations for `applyBrokerSupervisor`); the health check only reads
|
||||
// TARGET paths (`unitTargetPath`, `socketPath`), both derived from
|
||||
// `mosaicHome`/`homeDir`/`env` alone. Passing `mosaicHome` again here is
|
||||
// therefore safe and never resolves or touches a framework checkout.
|
||||
const paths = resolveBrokerSupervisorPaths({ mosaicHome, frameworkRoot: mosaicHome });
|
||||
return (await checkBrokerSupervisorHealth(paths)).healthy;
|
||||
}
|
||||
|
||||
/**
|
||||
* Surface the #869 fail-closed brick scenario as a LOUD `mosaic doctor`
|
||||
* error. See module docstring for the full decision table.
|
||||
*/
|
||||
export async function runLeaseEnforcementDoctorCheck(
|
||||
deps: LeaseDoctorCheckDeps = {},
|
||||
): Promise<LeaseDoctorCheckResult> {
|
||||
const readSettingsRaw = deps.readSettingsRaw ?? defaultReadSettingsRaw;
|
||||
const mosaicHome = deps.mosaicHome ?? defaultMosaicHome();
|
||||
const isActivatable = deps.isActivatable ?? leaseEnforcementActivatable;
|
||||
const isBrokerHealthy = deps.isBrokerHealthy ?? (() => defaultIsBrokerHealthy(mosaicHome));
|
||||
|
||||
const raw = readSettingsRaw();
|
||||
if (raw === null) {
|
||||
return {
|
||||
status: 'ok',
|
||||
wired: false,
|
||||
activatable: null,
|
||||
brokerHealthy: null,
|
||||
message: 'Claude Code settings.json not found — lease-enforcement hooks not wired.',
|
||||
};
|
||||
}
|
||||
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(raw);
|
||||
} catch {
|
||||
// Malformed settings.json is a different failure class than this card
|
||||
// owns (C2 guards install-time writes); report ok rather than
|
||||
// misattributing a parse error to the #869 activation gap.
|
||||
return {
|
||||
status: 'ok',
|
||||
wired: false,
|
||||
activatable: null,
|
||||
brokerHealthy: null,
|
||||
message:
|
||||
'Claude Code settings.json could not be parsed — skipping lease-enforcement wiring check.',
|
||||
};
|
||||
}
|
||||
|
||||
const { wired, matchedMarkers } = detectEnforcementHooksWired(parsed);
|
||||
if (!wired) {
|
||||
return {
|
||||
status: 'ok',
|
||||
wired: false,
|
||||
activatable: null,
|
||||
brokerHealthy: null,
|
||||
message:
|
||||
'Lease-enforcement hooks not wired in ~/.claude/settings.json — nothing to activate.',
|
||||
};
|
||||
}
|
||||
|
||||
const activatable = isActivatable();
|
||||
const brokerHealthy = await isBrokerHealthy();
|
||||
|
||||
if (activatable && brokerHealthy) {
|
||||
return {
|
||||
status: 'ok',
|
||||
wired: true,
|
||||
activatable,
|
||||
brokerHealthy,
|
||||
message: `Lease-enforcement hooks wired (${matchedMarkers.join(', ')}) — activation capability present and broker healthy.`,
|
||||
};
|
||||
}
|
||||
|
||||
const reasons: string[] = [];
|
||||
if (!activatable) reasons.push('activation absent (leaseEnforcementActivatable() is false)');
|
||||
if (!brokerHealthy) {
|
||||
reasons.push('broker not healthy (checkBrokerSupervisorHealth() reports unhealthy)');
|
||||
}
|
||||
|
||||
return {
|
||||
status: 'error',
|
||||
wired: true,
|
||||
activatable,
|
||||
brokerHealthy,
|
||||
message:
|
||||
`Lease-enforcement hooks (${matchedMarkers.join(', ')}) are wired in ~/.claude/settings.json, but ${reasons.join(' and ')}. ` +
|
||||
'Every gated tool call will fail closed and BRICK this agent (see #869). ' +
|
||||
'Remediate by activating the lease-broker supervisor (systemd unit + socket) or by removing the enforcement hooks from ~/.claude/settings.json.',
|
||||
};
|
||||
}
|
||||
@@ -47,6 +47,22 @@ const piLifecyclePath = join(frameworkRoot, 'runtime/pi/lease-lifecycle.ts');
|
||||
const prdyInitPath = join(frameworkRoot, 'tools/prdy/prdy-init.sh');
|
||||
const prdyUpdatePath = join(frameworkRoot, 'tools/prdy/prdy-update.sh');
|
||||
const remediationHandlerPath = join(frameworkRoot, 'tools/qa/remediation-hook-handler.sh');
|
||||
|
||||
// C4 (#869 Point-1): launch-runtime.py now asserts, before anything else,
|
||||
// that the CLI's advertised lease-activation capability (normally read via
|
||||
// the hidden `mosaic __lease-capability` subcommand) matches what
|
||||
// enforcement expects — see framework/tools/lease-broker/
|
||||
// activation_version_gate.py. This suite drives launch-runtime.py directly
|
||||
// as a subprocess (never through the real `mosaic` CLI), so — exactly like
|
||||
// the fake broker (daemon.py) and fake `claude` binaries already used
|
||||
// below — it must supply a fake activation-capability probe rather than
|
||||
// depend on a real `mosaic` binary being on PATH. `MOSAIC_LEASE_VERSION_PROBE_COMMAND`
|
||||
// is launch-runtime.py's injection point for that fake; this literal
|
||||
// {name, version} pair must be kept in sync with
|
||||
// `EXPECTED_ACTIVATION_CAPABILITY` (activation_version_gate.py) and
|
||||
// `LEASE_ACTIVATION_CAPABILITY` (lease-activation-probe.ts) — all three
|
||||
// currently agree on v1.
|
||||
const leaseCapabilityProbeStub = `python3 -c "import json; print(json.dumps({'name': 'lease-runtime-activation', 'version': 1}))"`;
|
||||
const children: ChildProcess[] = [];
|
||||
const temporaryRoots: string[] = [];
|
||||
|
||||
@@ -184,6 +200,7 @@ raise SystemExit(0 if len(session_id) == 64 and denied else 1)
|
||||
MOSAIC_PRDY_RUNTIME: 'claude',
|
||||
MOSAIC_LEASE_BROKER_SOCKET: socket,
|
||||
MOSAIC_RUNTIME_GENERATION: '1',
|
||||
MOSAIC_LEASE_VERSION_PROBE_COMMAND: leaseCapabilityProbeStub,
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -743,6 +760,7 @@ describe('whole mutator-class lease gate', () => {
|
||||
...process.env,
|
||||
MOSAIC_LEASE_BROKER_SOCKET: socket,
|
||||
MOSAIC_RUNTIME_GENERATION: '1',
|
||||
MOSAIC_LEASE_VERSION_PROBE_COMMAND: leaseCapabilityProbeStub,
|
||||
},
|
||||
},
|
||||
);
|
||||
@@ -761,6 +779,7 @@ describe('whole mutator-class lease gate', () => {
|
||||
...process.env,
|
||||
MOSAIC_LEASE_BROKER_SOCKET: join(tmpdir(), 'missing-mosaic-broker.sock'),
|
||||
MOSAIC_RUNTIME_GENERATION: '1',
|
||||
MOSAIC_LEASE_VERSION_PROBE_COMMAND: leaseCapabilityProbeStub,
|
||||
},
|
||||
},
|
||||
);
|
||||
@@ -878,6 +897,7 @@ raise SystemExit(0 if len(session_id) == 64 and hook_present and observers_prese
|
||||
PATH: `${binDir}:${process.env.PATH ?? ''}`,
|
||||
MOSAIC_LEASE_BROKER_SOCKET: socket,
|
||||
MOSAIC_RUNTIME_GENERATION: '1',
|
||||
MOSAIC_LEASE_VERSION_PROBE_COMMAND: leaseCapabilityProbeStub,
|
||||
},
|
||||
proxyGate: () =>
|
||||
Promise.resolve({
|
||||
|
||||
@@ -39,6 +39,18 @@ LAUNCHER = load_tool("lease_runtime_launcher", "launch-runtime.py")
|
||||
GATE = load_tool("lease_mutator_gate", "mutator-gate.py")
|
||||
|
||||
|
||||
def matching_activation_probe(*_args: object, **_kwargs: object) -> dict[str, object]:
|
||||
"""Fake activation-capability probe matching what enforcement expects
|
||||
(C4, #869 Point-1). Injected into `LAUNCHER.main()` calls below that are
|
||||
exercising OTHER branches (registration, exec, generation init, ...) so
|
||||
the new version-coupling gate — which runs before those — never blocks
|
||||
on host state (no real `mosaic` CLI on PATH in a test sandbox). The
|
||||
version-coupling gate's OWN behavior (match/mismatch/absent) is covered
|
||||
by its dedicated red-first tests in `version_coupling_unittest.py`."""
|
||||
|
||||
return dict(LAUNCHER.EXPECTED_ACTIVATION_CAPABILITY)
|
||||
|
||||
|
||||
class FakeSocket:
|
||||
def __init__(self, *chunks: bytes):
|
||||
self.chunks = list(chunks)
|
||||
@@ -95,6 +107,7 @@ class LaunchRuntimeTest(unittest.TestCase):
|
||||
request=request,
|
||||
execute=execute,
|
||||
initialize_generation=initialize_generation,
|
||||
probe_activation_capability=matching_activation_probe,
|
||||
)
|
||||
|
||||
self.assertEqual(result, 0)
|
||||
@@ -127,6 +140,7 @@ class LaunchRuntimeTest(unittest.TestCase):
|
||||
request=lambda *_args: {"ok": True, "session_id": "e" * 64},
|
||||
execute=lambda *args: executed.append(args),
|
||||
initialize_generation=lambda *_args: None,
|
||||
probe_activation_capability=matching_activation_probe,
|
||||
)
|
||||
self.assertEqual(result, 0)
|
||||
self.assertEqual(
|
||||
@@ -153,6 +167,7 @@ class LaunchRuntimeTest(unittest.TestCase):
|
||||
request=lambda *_args: {"ok": True, "session_id": "f" * 64},
|
||||
execute=lambda *args: executed.append(args),
|
||||
initialize_generation=lambda *_args: None,
|
||||
probe_activation_capability=matching_activation_probe,
|
||||
)
|
||||
self.assertEqual(result, 0)
|
||||
self.assertEqual(executed[0][0:2], ("pi", ["pi", "--print", "hello"]))
|
||||
@@ -188,6 +203,7 @@ class LaunchRuntimeTest(unittest.TestCase):
|
||||
environ=environment,
|
||||
request=lambda *_args, value=reply: value,
|
||||
execute=lambda *args: executed.append(args),
|
||||
probe_activation_capability=matching_activation_probe,
|
||||
)
|
||||
self.assertEqual(result, 1)
|
||||
self.assertEqual(executed, [])
|
||||
@@ -203,6 +219,7 @@ class LaunchRuntimeTest(unittest.TestCase):
|
||||
initialize_generation=lambda *_args: (_ for _ in ()).throw(
|
||||
OSError("unsafe state")
|
||||
),
|
||||
probe_activation_capability=matching_activation_probe,
|
||||
),
|
||||
1,
|
||||
)
|
||||
@@ -220,6 +237,7 @@ class LaunchRuntimeTest(unittest.TestCase):
|
||||
environ={"MOSAIC_LEASE_BROKER_SOCKET": "/x"},
|
||||
request=request,
|
||||
execute=lambda *_args: self.fail("must not execute"),
|
||||
probe_activation_capability=matching_activation_probe,
|
||||
),
|
||||
1,
|
||||
)
|
||||
@@ -233,6 +251,7 @@ class LaunchRuntimeTest(unittest.TestCase):
|
||||
request=lambda *_args: {"ok": True, "session_id": "c" * 64},
|
||||
execute=lambda *_args: (_ for _ in ()).throw(OSError("missing")),
|
||||
initialize_generation=lambda *_args: None,
|
||||
probe_activation_capability=matching_activation_probe,
|
||||
),
|
||||
1,
|
||||
)
|
||||
|
||||
287
packages/mosaic/src/mutator-gate/version_coupling_unittest.py
Normal file
287
packages/mosaic/src/mutator-gate/version_coupling_unittest.py
Normal file
@@ -0,0 +1,287 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Red-first tests for issue #869 Point-1 C4 — the enforcement/activation
|
||||
version-coupling assertion at the `launch-runtime.py` seam.
|
||||
|
||||
Root cause under test (#828 restated): the lease broker's ENFORCEMENT half
|
||||
(this toolkit) and its ACTIVATION half (`execLeaseGatedRuntime()` in
|
||||
`launch.ts`, chained through `launch-runtime.py`) shipped on different
|
||||
channels and drifted. C1 (`lease-activation-probe.ts`) gave the activation
|
||||
half a versioned, machine-checkable identity
|
||||
(`LEASE_ACTIVATION_CAPABILITY`, printed via the hidden CLI subcommand
|
||||
`mosaic __lease-capability`). C4 (this module + `activation_version_gate.py`)
|
||||
is the assertion that actually USES that identity: enforcement must refuse
|
||||
to proceed — loudly, with an actionable remediation message, never a
|
||||
silent pass — unless the activation capability it observes exactly matches
|
||||
what enforcement expects.
|
||||
|
||||
Every case here drives the seam with injected fakes/stubs (a fake
|
||||
`probe_activation_capability` callable at the `launch-runtime.py` level, or
|
||||
a fake `run` transport at the `activation_version_gate` level) — never a
|
||||
real broker, a real installed CLI, or a real `mosaic` binary on PATH.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import io
|
||||
import subprocess
|
||||
import sys
|
||||
import unittest
|
||||
from contextlib import redirect_stderr
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
TOOLS_DIR = Path(__file__).parents[2] / "framework/tools/lease-broker"
|
||||
if str(TOOLS_DIR) not in sys.path:
|
||||
sys.path.insert(0, str(TOOLS_DIR))
|
||||
|
||||
|
||||
def load_tool(module_name: str, filename: str):
|
||||
spec = importlib.util.spec_from_file_location(module_name, TOOLS_DIR / filename)
|
||||
if spec is None or spec.loader is None:
|
||||
raise RuntimeError(f"unable to load {filename}")
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
# Loaded under distinct module names from runtime_tools_unittest.py's own
|
||||
# LAUNCHER/GATE loads — importlib.util.module_from_spec() gives each load a
|
||||
# fresh module object regardless of name collisions, but distinct names keep
|
||||
# tracebacks/debugging unambiguous when both files run in the same process.
|
||||
LAUNCHER = load_tool("lease_runtime_launcher_version_coupling", "launch-runtime.py")
|
||||
VERSION_GATE = load_tool("lease_activation_version_gate_test", "activation_version_gate.py")
|
||||
|
||||
|
||||
def matching_capability() -> dict[str, object]:
|
||||
return dict(VERSION_GATE.EXPECTED_ACTIVATION_CAPABILITY)
|
||||
|
||||
|
||||
class AssertActivationCapabilityMatchesTest(unittest.TestCase):
|
||||
"""Unit-level coverage of `activation_version_gate.py`'s own assertion,
|
||||
isolated from the launch-runtime.py seam it is wired into below."""
|
||||
|
||||
def test_matching_capability_passes_silently(self) -> None:
|
||||
VERSION_GATE.assert_activation_capability_matches(matching_capability())
|
||||
# No exception is the assertion; nothing further to check.
|
||||
|
||||
def test_absent_capability_fails_closed_not_silent_pass(self) -> None:
|
||||
with self.assertRaises(VERSION_GATE.VersionCouplingError) as raised:
|
||||
VERSION_GATE.assert_activation_capability_matches(None)
|
||||
message = str(raised.exception)
|
||||
self.assertIn("#869", message)
|
||||
self.assertIn("upgrade", message.lower())
|
||||
|
||||
def test_version_mismatch_message_is_actionable(self) -> None:
|
||||
expected = {"name": "lease-runtime-activation", "version": 1}
|
||||
mismatched = {"name": "lease-runtime-activation", "version": 2}
|
||||
with self.assertRaises(VERSION_GATE.VersionCouplingError) as raised:
|
||||
VERSION_GATE.assert_activation_capability_matches(mismatched, expected)
|
||||
message = str(raised.exception)
|
||||
self.assertIn("v2", message)
|
||||
self.assertIn("v1", message)
|
||||
self.assertIn("#869", message)
|
||||
self.assertIn("upgrade", message.lower())
|
||||
self.assertIn("version skew", message.lower())
|
||||
|
||||
def test_name_mismatch_fails_loud(self) -> None:
|
||||
expected = {"name": "lease-runtime-activation", "version": 1}
|
||||
mismatched = {"name": "some-other-capability", "version": 1}
|
||||
with self.assertRaises(VERSION_GATE.VersionCouplingError) as raised:
|
||||
VERSION_GATE.assert_activation_capability_matches(mismatched, expected)
|
||||
message = str(raised.exception)
|
||||
self.assertIn("some-other-capability", message)
|
||||
self.assertIn("lease-runtime-activation", message)
|
||||
self.assertIn("#869", message)
|
||||
|
||||
def test_reversed_drift_newer_activation_than_enforcement_expects_also_fails(self) -> None:
|
||||
# A build/deploy where ACTIVATION shipped ahead of ENFORCEMENT is
|
||||
# exactly as much version skew as the reverse (#828's actual shape
|
||||
# was enforcement ahead of activation) — the assertion must not special
|
||||
# case direction.
|
||||
expected = {"name": "lease-runtime-activation", "version": 1}
|
||||
newer_activation = {"name": "lease-runtime-activation", "version": 2}
|
||||
with self.assertRaises(VERSION_GATE.VersionCouplingError):
|
||||
VERSION_GATE.assert_activation_capability_matches(newer_activation, expected)
|
||||
|
||||
|
||||
class ProbeActivationCapabilityTest(unittest.TestCase):
|
||||
"""Coverage of the probe's command resolution and fail-closed transport
|
||||
handling — never spawns a real `mosaic` process."""
|
||||
|
||||
def test_returns_none_when_mosaic_is_not_resolvable_on_path(self) -> None:
|
||||
result = VERSION_GATE.default_probe_activation_capability(
|
||||
{"PATH": "/nonexistent-bin-dir-for-869-c4-test"}
|
||||
)
|
||||
self.assertIsNone(result)
|
||||
|
||||
def test_override_command_is_parsed_and_the_probe_subcommand_is_not_double_appended(
|
||||
self,
|
||||
) -> None:
|
||||
captured: list[list[str]] = []
|
||||
|
||||
class FakeCompleted:
|
||||
returncode = 0
|
||||
stdout = '{"name": "lease-runtime-activation", "version": 1}'
|
||||
|
||||
def fake_run(argv: list[str], **_kwargs: object) -> FakeCompleted:
|
||||
captured.append(argv)
|
||||
return FakeCompleted()
|
||||
|
||||
result = VERSION_GATE.default_probe_activation_capability(
|
||||
{VERSION_GATE.MOSAIC_COMMAND_OVERRIDE_VAR: "/fake/mosaic __lease-capability"},
|
||||
run=fake_run,
|
||||
)
|
||||
self.assertEqual(result, {"name": "lease-runtime-activation", "version": 1})
|
||||
self.assertEqual(captured, [["/fake/mosaic", "__lease-capability"]])
|
||||
|
||||
def test_fails_closed_on_nonzero_exit_malformed_json_and_missing_fields(self) -> None:
|
||||
class NonZeroExit:
|
||||
returncode = 1
|
||||
stdout = '{"name": "lease-runtime-activation", "version": 1}'
|
||||
|
||||
class MalformedOutput:
|
||||
returncode = 0
|
||||
stdout = "not-json"
|
||||
|
||||
class MissingVersion:
|
||||
returncode = 0
|
||||
stdout = '{"name": "lease-runtime-activation"}'
|
||||
|
||||
class WrongShapeVersion:
|
||||
returncode = 0
|
||||
stdout = '{"name": "lease-runtime-activation", "version": "1"}'
|
||||
|
||||
class BooleanVersion:
|
||||
# bool is a subclass of int in Python; must not be accepted as
|
||||
# a version number.
|
||||
returncode = 0
|
||||
stdout = '{"name": "lease-runtime-activation", "version": true}'
|
||||
|
||||
for fake in (
|
||||
NonZeroExit(),
|
||||
MalformedOutput(),
|
||||
MissingVersion(),
|
||||
WrongShapeVersion(),
|
||||
BooleanVersion(),
|
||||
):
|
||||
with self.subTest(stdout=fake.stdout, returncode=fake.returncode):
|
||||
result = VERSION_GATE.default_probe_activation_capability(
|
||||
{VERSION_GATE.MOSAIC_COMMAND_OVERRIDE_VAR: "/fake/mosaic"},
|
||||
run=lambda *_a, fake=fake, **_kw: fake,
|
||||
)
|
||||
self.assertIsNone(result)
|
||||
|
||||
def test_fails_closed_on_timeout_and_transport_error(self) -> None:
|
||||
def timeout_run(*_args: object, **_kwargs: object) -> None:
|
||||
raise subprocess.TimeoutExpired(cmd="mosaic", timeout=2.0)
|
||||
|
||||
def oserror_run(*_args: object, **_kwargs: object) -> None:
|
||||
raise OSError("no such file or directory")
|
||||
|
||||
for run_fake in (timeout_run, oserror_run):
|
||||
with self.subTest(run=run_fake.__name__):
|
||||
result = VERSION_GATE.default_probe_activation_capability(
|
||||
{VERSION_GATE.MOSAIC_COMMAND_OVERRIDE_VAR: "/fake/mosaic"},
|
||||
run=run_fake,
|
||||
)
|
||||
self.assertIsNone(result)
|
||||
|
||||
|
||||
class LaunchRuntimeVersionCouplingSeamTest(unittest.TestCase):
|
||||
"""End-to-end (still fully faked) coverage of the seam as wired into
|
||||
`launch-runtime.py`'s `main()` — the strongest natural enforcement point
|
||||
per the C4 card, run before any broker registration."""
|
||||
|
||||
def _run(self, *, probe):
|
||||
calls: dict[str, object] = {}
|
||||
|
||||
def request(_path: Path, payload: dict[str, object]) -> dict[str, object]:
|
||||
calls["registered"] = True
|
||||
calls["request"] = payload
|
||||
return {"ok": True, "session_id": "a" * 64}
|
||||
|
||||
def execute(command: str, argv: list[str], environment: dict[str, str]) -> None:
|
||||
calls["executed"] = (command, argv, environment)
|
||||
|
||||
def initialize_generation(_path: Path, _generation: int) -> None:
|
||||
calls["generation_initialized"] = True
|
||||
|
||||
stderr = io.StringIO()
|
||||
with redirect_stderr(stderr):
|
||||
result = LAUNCHER.main(
|
||||
["--runtime", "claude", "--", "claude", "--print", "hello"],
|
||||
environ={"MOSAIC_LEASE_BROKER_SOCKET": "/run/test/broker.sock"},
|
||||
request=request,
|
||||
execute=execute,
|
||||
initialize_generation=initialize_generation,
|
||||
probe_activation_capability=probe,
|
||||
)
|
||||
return result, stderr.getvalue(), calls
|
||||
|
||||
def test_matching_activation_version_passes_and_the_gate_proceeds(self) -> None:
|
||||
result, stderr_text, calls = self._run(probe=lambda *_a, **_kw: matching_capability())
|
||||
self.assertEqual(result, 0)
|
||||
self.assertEqual(stderr_text, "")
|
||||
self.assertTrue(calls.get("registered"))
|
||||
self.assertIn("executed", calls)
|
||||
|
||||
def test_version_mismatch_fails_loud_denies_and_never_registers_or_execs(self) -> None:
|
||||
expected = LAUNCHER.EXPECTED_ACTIVATION_CAPABILITY
|
||||
mismatched = {"name": expected["name"], "version": expected["version"] + 1}
|
||||
result, stderr_text, calls = self._run(probe=lambda *_a, **_kw: mismatched)
|
||||
|
||||
self.assertEqual(result, LAUNCHER.EXIT_VERSION_SKEW)
|
||||
self.assertNotEqual(result, 0)
|
||||
self.assertIn("#869", stderr_text)
|
||||
self.assertIn(f"v{mismatched['version']}", stderr_text)
|
||||
self.assertIn(f"v{expected['version']}", stderr_text)
|
||||
self.assertIn("upgrade", stderr_text.lower())
|
||||
# Never reaches broker registration or exec — the version gate is a
|
||||
# hard stop, not advisory.
|
||||
self.assertNotIn("registered", calls)
|
||||
self.assertNotIn("executed", calls)
|
||||
|
||||
def test_name_mismatch_fails_loud(self) -> None:
|
||||
expected = LAUNCHER.EXPECTED_ACTIVATION_CAPABILITY
|
||||
mismatched = {"name": "some-other-capability", "version": expected["version"]}
|
||||
result, stderr_text, calls = self._run(probe=lambda *_a, **_kw: mismatched)
|
||||
|
||||
self.assertEqual(result, LAUNCHER.EXIT_VERSION_SKEW)
|
||||
self.assertIn("#869", stderr_text)
|
||||
self.assertIn("some-other-capability", stderr_text)
|
||||
self.assertNotIn("registered", calls)
|
||||
self.assertNotIn("executed", calls)
|
||||
|
||||
def test_absent_activation_capability_fails_closed_not_a_silent_pass(self) -> None:
|
||||
result, stderr_text, calls = self._run(probe=lambda *_a, **_kw: None)
|
||||
|
||||
self.assertEqual(result, LAUNCHER.EXIT_VERSION_SKEW)
|
||||
self.assertNotEqual(result, 0)
|
||||
self.assertIn("#869", stderr_text)
|
||||
self.assertNotIn("registered", calls)
|
||||
self.assertNotIn("executed", calls)
|
||||
|
||||
def test_version_gate_runs_before_and_independently_of_broker_registration(self) -> None:
|
||||
def request_must_not_be_called(*_args: object, **_kwargs: object) -> dict[str, object]:
|
||||
self.fail("broker must not be contacted when activation version is mismatched")
|
||||
|
||||
stderr = io.StringIO()
|
||||
with redirect_stderr(stderr):
|
||||
result = LAUNCHER.main(
|
||||
["--runtime", "claude", "--", "claude"],
|
||||
environ={"MOSAIC_LEASE_BROKER_SOCKET": "/run/test/broker.sock"},
|
||||
request=request_must_not_be_called,
|
||||
probe_activation_capability=lambda *_a, **_kw: None,
|
||||
)
|
||||
self.assertEqual(result, LAUNCHER.EXIT_VERSION_SKEW)
|
||||
|
||||
def test_dedicated_exit_code_never_collides_with_usage_or_registration_codes(self) -> None:
|
||||
# Distinctness guard: a version-skew denial must never be mistaken
|
||||
# for the pre-existing usage error (64) or registration/exec
|
||||
# fail-closed code (1) this script already owns.
|
||||
self.assertNotIn(LAUNCHER.EXIT_VERSION_SKEW, (0, 1, 64))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,424 @@
|
||||
import { describe, it, expect, afterEach, vi } from 'vitest';
|
||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import {
|
||||
ENFORCEMENT_HOOK_MARKERS,
|
||||
FAIL_LOUD_MESSAGE,
|
||||
settingsHasEnforcementHooks,
|
||||
} from '../commands/install-ordering-guard.js';
|
||||
import {
|
||||
runUpdatePathSettingsGuard,
|
||||
runUpdateReseedFlow,
|
||||
type FrameworkReseedResult,
|
||||
} from './update-checker.js';
|
||||
|
||||
/**
|
||||
* Red-first tests for issue #882 (b) — the `mosaic update --sync-only`
|
||||
* install-ordering-guard bypass (Mos-ruled "Option C").
|
||||
*
|
||||
* Root cause under test: `runFrameworkReseed()` runs the package's
|
||||
* install.sh with MOSAIC_SYNC_ONLY=1, which exits after the file-system
|
||||
* phase, BEFORE the "Post-install tasks" step that would otherwise run
|
||||
* `mosaic-link-runtime-assets` — the only place the #869 Point-1 C2
|
||||
* install-ordering guard evaluated whether the lease-enforcement hooks
|
||||
* (PreToolUse mutator-gate.py / Stop receipt-observer-client.py) may be
|
||||
* wired into `~/.claude/settings.json`. A plain `mosaic update` therefore
|
||||
* never re-evaluated that decision. These tests prove the post-reseed step
|
||||
* added to close that gap (`runUpdatePathSettingsGuard`, wired into the
|
||||
* `mosaic update` reseed flow via `runUpdateReseedFlow`) reuses the EXACT
|
||||
* C2 guard — no forked logic — and is skipped only when `--no-reseed` means
|
||||
* there was nothing to re-seed/re-link in the first place.
|
||||
*
|
||||
* All fixtures use temp directories — this suite never reads or writes the
|
||||
* real `~/.claude/settings.json` or `~/.config/mosaic`.
|
||||
*/
|
||||
|
||||
const FIXTURE_SETTINGS = {
|
||||
model: 'opus',
|
||||
hooks: {
|
||||
PreToolUse: [
|
||||
{
|
||||
matcher: '.*',
|
||||
hooks: [
|
||||
{
|
||||
type: 'command',
|
||||
command: 'python3 ~/.config/mosaic/tools/lease-broker/mutator-gate.py --runtime claude',
|
||||
timeout: 3,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
Stop: [
|
||||
{
|
||||
hooks: [
|
||||
{
|
||||
type: 'command',
|
||||
command:
|
||||
'python3 ~/.config/mosaic/tools/lease-broker/receipt-observer-client.py --runtime claude',
|
||||
timeout: 3,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
function fixtureJson(): string {
|
||||
return JSON.stringify(FIXTURE_SETTINGS, null, 2) + '\n';
|
||||
}
|
||||
|
||||
describe('runUpdatePathSettingsGuard', () => {
|
||||
let root: string;
|
||||
let mosaicHome: string;
|
||||
let claudeHome: string;
|
||||
|
||||
afterEach(() => {
|
||||
if (root) rmSync(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
function makeTemplate(): void {
|
||||
root = mkdtempSync(join(tmpdir(), 'mosaic-update-settings-guard-'));
|
||||
mosaicHome = join(root, 'mosaic-home');
|
||||
claudeHome = join(root, 'claude-home');
|
||||
mkdirSync(join(mosaicHome, 'runtime', 'claude'), { recursive: true });
|
||||
writeFileSync(join(mosaicHome, 'runtime', 'claude', 'settings.json'), fixtureJson());
|
||||
}
|
||||
|
||||
it('does not run when there is no settings.json template to re-link', () => {
|
||||
root = mkdtempSync(join(tmpdir(), 'mosaic-update-settings-guard-'));
|
||||
mosaicHome = join(root, 'mosaic-home');
|
||||
claudeHome = join(root, 'claude-home');
|
||||
// Deliberately no runtime/claude/settings.json under mosaicHome.
|
||||
|
||||
const outcome = runUpdatePathSettingsGuard(mosaicHome, claudeHome);
|
||||
|
||||
expect(outcome.ran).toBe(false);
|
||||
expect(outcome.result).toBeUndefined();
|
||||
expect(existsSync(join(claudeHome, 'settings.json'))).toBe(false);
|
||||
});
|
||||
|
||||
it('activatable=false (default, no opt-out): strips enforcement hooks and fails loud, exactly as install-time', () => {
|
||||
makeTemplate();
|
||||
|
||||
const outcome = runUpdatePathSettingsGuard(
|
||||
mosaicHome,
|
||||
claudeHome,
|
||||
{},
|
||||
{ activatable: () => false },
|
||||
);
|
||||
|
||||
expect(outcome.ran).toBe(true);
|
||||
expect(outcome.result?.exitCode).toBe(1);
|
||||
expect(outcome.result?.wired).toBe(false);
|
||||
expect(outcome.result?.logs).toHaveLength(1);
|
||||
expect(outcome.result?.logs[0]?.level).toBe('error');
|
||||
expect(outcome.result?.logs[0]?.message).toBe(FAIL_LOUD_MESSAGE);
|
||||
|
||||
const written = JSON.parse(readFileSync(join(claudeHome, 'settings.json'), 'utf-8')) as Record<
|
||||
string,
|
||||
unknown
|
||||
>;
|
||||
expect(settingsHasEnforcementHooks(written)).toBe(false);
|
||||
});
|
||||
|
||||
it('activatable=true: wires hooks normally, no strip, no logs', () => {
|
||||
makeTemplate();
|
||||
|
||||
const outcome = runUpdatePathSettingsGuard(
|
||||
mosaicHome,
|
||||
claudeHome,
|
||||
{},
|
||||
{ activatable: () => true },
|
||||
);
|
||||
|
||||
expect(outcome.ran).toBe(true);
|
||||
expect(outcome.result?.exitCode).toBe(0);
|
||||
expect(outcome.result?.wired).toBe(true);
|
||||
expect(outcome.result?.logs).toHaveLength(0);
|
||||
|
||||
const written = JSON.parse(readFileSync(join(claudeHome, 'settings.json'), 'utf-8')) as Record<
|
||||
string,
|
||||
unknown
|
||||
>;
|
||||
expect(settingsHasEnforcementHooks(written)).toBe(true);
|
||||
expect(written).toEqual(FIXTURE_SETTINGS);
|
||||
});
|
||||
|
||||
it('activatable=false + --allow-inactive-enforcement: wires hooks anyway with a loud warning', () => {
|
||||
makeTemplate();
|
||||
|
||||
const outcome = runUpdatePathSettingsGuard(
|
||||
mosaicHome,
|
||||
claudeHome,
|
||||
{ allowInactiveEnforcement: true },
|
||||
{ activatable: () => false },
|
||||
);
|
||||
|
||||
expect(outcome.ran).toBe(true);
|
||||
expect(outcome.result?.exitCode).toBe(0);
|
||||
expect(outcome.result?.wired).toBe(true);
|
||||
expect(outcome.result?.logs).toHaveLength(1);
|
||||
expect(outcome.result?.logs[0]?.level).toBe('warn');
|
||||
expect(outcome.result?.logs[0]?.message).toMatch(/WITHOUT confirmed activation/);
|
||||
|
||||
const written = JSON.parse(readFileSync(join(claudeHome, 'settings.json'), 'utf-8')) as Record<
|
||||
string,
|
||||
unknown
|
||||
>;
|
||||
expect(settingsHasEnforcementHooks(written)).toBe(true);
|
||||
});
|
||||
|
||||
it('never touches the real home directory settings path used by this test file', () => {
|
||||
// Sanity guard for the suite itself.
|
||||
makeTemplate();
|
||||
expect(mosaicHome).toContain('mosaic-update-settings-guard-');
|
||||
expect(claudeHome).toContain('mosaic-update-settings-guard-');
|
||||
});
|
||||
});
|
||||
|
||||
describe('runUpdateReseedFlow (the `mosaic update` post-reseed guard wiring, #882 (b))', () => {
|
||||
const okReseed: FrameworkReseedResult = { ok: true };
|
||||
|
||||
it('--no-reseed: the reseed is never attempted and the settings guard is never invoked', () => {
|
||||
const doReseed = vi.fn(() => okReseed);
|
||||
const doGuard = vi.fn(() => ({ ran: true }));
|
||||
const doRefresh = vi.fn(() => ({ refreshed: [], ok: true }));
|
||||
const doReadRoster = vi.fn(() => []);
|
||||
const log = vi.fn();
|
||||
const warnLog = vi.fn();
|
||||
const errorLog = vi.fn();
|
||||
|
||||
const result = runUpdateReseedFlow(
|
||||
'should never be printed',
|
||||
{ reseed: false },
|
||||
{
|
||||
runFrameworkReseed: doReseed,
|
||||
runUpdatePathSettingsGuard: doGuard,
|
||||
refreshActiveFleetUnits: doRefresh,
|
||||
readRosterAgentNames: doReadRoster,
|
||||
log,
|
||||
warnLog,
|
||||
errorLog,
|
||||
},
|
||||
);
|
||||
|
||||
expect(result.attempted).toBe(false);
|
||||
expect(doReseed).not.toHaveBeenCalled();
|
||||
expect(doGuard).not.toHaveBeenCalled();
|
||||
expect(log).not.toHaveBeenCalled();
|
||||
expect(errorLog).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reseed ran + activatable=false: the guard fires (hooks stripped) and the fail-loud message is surfaced, not swallowed', () => {
|
||||
const doReseed = vi.fn(() => okReseed);
|
||||
const doGuard = vi.fn(() => ({
|
||||
ran: true,
|
||||
result: {
|
||||
json: '{}',
|
||||
wired: false,
|
||||
exitCode: 1 as const,
|
||||
logs: [{ level: 'error' as const, message: FAIL_LOUD_MESSAGE }],
|
||||
destWritten: true,
|
||||
},
|
||||
}));
|
||||
const doRefresh = vi.fn(() => ({ refreshed: [], ok: true }));
|
||||
const doReadRoster = vi.fn(() => []);
|
||||
const log = vi.fn();
|
||||
const warnLog = vi.fn();
|
||||
const errorLog = vi.fn();
|
||||
|
||||
const result = runUpdateReseedFlow(
|
||||
'Re-seeding…',
|
||||
{ reseed: true },
|
||||
{
|
||||
runFrameworkReseed: doReseed,
|
||||
runUpdatePathSettingsGuard: doGuard,
|
||||
refreshActiveFleetUnits: doRefresh,
|
||||
readRosterAgentNames: doReadRoster,
|
||||
log,
|
||||
warnLog,
|
||||
errorLog,
|
||||
},
|
||||
);
|
||||
|
||||
expect(result.attempted).toBe(true);
|
||||
expect(doReseed).toHaveBeenCalledTimes(1);
|
||||
expect(doGuard).toHaveBeenCalledTimes(1);
|
||||
expect(result.settingsGuard?.result?.exitCode).toBe(1);
|
||||
// The guard's fail-loud message must reach the operator (stderr), never swallowed.
|
||||
expect(errorLog).toHaveBeenCalledWith(FAIL_LOUD_MESSAGE);
|
||||
});
|
||||
|
||||
it('reseed ran + activatable=true: the guard wires hooks with no error output', () => {
|
||||
const doReseed = vi.fn(() => okReseed);
|
||||
const doGuard = vi.fn(() => ({
|
||||
ran: true,
|
||||
result: {
|
||||
json: '{}',
|
||||
wired: true,
|
||||
exitCode: 0 as const,
|
||||
logs: [],
|
||||
destWritten: true,
|
||||
},
|
||||
}));
|
||||
const doRefresh = vi.fn(() => ({ refreshed: [], ok: true }));
|
||||
const doReadRoster = vi.fn(() => []);
|
||||
const log = vi.fn();
|
||||
const warnLog = vi.fn();
|
||||
const errorLog = vi.fn();
|
||||
|
||||
const result = runUpdateReseedFlow(
|
||||
'Re-seeding…',
|
||||
{ reseed: true },
|
||||
{
|
||||
runFrameworkReseed: doReseed,
|
||||
runUpdatePathSettingsGuard: doGuard,
|
||||
refreshActiveFleetUnits: doRefresh,
|
||||
readRosterAgentNames: doReadRoster,
|
||||
log,
|
||||
warnLog,
|
||||
errorLog,
|
||||
},
|
||||
);
|
||||
|
||||
expect(result.attempted).toBe(true);
|
||||
expect(result.settingsGuard?.result?.exitCode).toBe(0);
|
||||
expect(errorLog).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('threads --allow-inactive-enforcement through to the settings guard', () => {
|
||||
const doReseed = vi.fn(() => okReseed);
|
||||
const doGuard = vi.fn(() => ({
|
||||
ran: true,
|
||||
result: {
|
||||
json: '{}',
|
||||
wired: true,
|
||||
exitCode: 0 as const,
|
||||
logs: [{ level: 'warn' as const, message: 'opt-out warning' }],
|
||||
destWritten: true,
|
||||
},
|
||||
}));
|
||||
const doRefresh = vi.fn(() => ({ refreshed: [], ok: true }));
|
||||
const doReadRoster = vi.fn(() => []);
|
||||
const warnLog = vi.fn();
|
||||
|
||||
runUpdateReseedFlow(
|
||||
'Re-seeding…',
|
||||
{ reseed: true, allowInactiveEnforcement: true },
|
||||
{
|
||||
runFrameworkReseed: doReseed,
|
||||
runUpdatePathSettingsGuard: doGuard,
|
||||
refreshActiveFleetUnits: doRefresh,
|
||||
readRosterAgentNames: doReadRoster,
|
||||
log: vi.fn(),
|
||||
warnLog,
|
||||
errorLog: vi.fn(),
|
||||
},
|
||||
);
|
||||
|
||||
expect(doGuard).toHaveBeenCalledWith(undefined, undefined, {
|
||||
allowInactiveEnforcement: true,
|
||||
});
|
||||
expect(warnLog).toHaveBeenCalledWith('opt-out warning');
|
||||
});
|
||||
|
||||
it('reseed failure: the settings guard is not invoked (nothing was re-seeded to re-link)', () => {
|
||||
const doReseed = vi.fn(
|
||||
() => ({ ok: false, reason: 'installer not found' }) as FrameworkReseedResult,
|
||||
);
|
||||
const doGuard = vi.fn(() => ({ ran: true }));
|
||||
const doRefresh = vi.fn(() => ({ refreshed: [], ok: true }));
|
||||
const doReadRoster = vi.fn(() => []);
|
||||
const errorLog = vi.fn();
|
||||
|
||||
const result = runUpdateReseedFlow(
|
||||
'Re-seeding…',
|
||||
{ reseed: true },
|
||||
{
|
||||
runFrameworkReseed: doReseed,
|
||||
runUpdatePathSettingsGuard: doGuard,
|
||||
refreshActiveFleetUnits: doRefresh,
|
||||
readRosterAgentNames: doReadRoster,
|
||||
log: vi.fn(),
|
||||
warnLog: vi.fn(),
|
||||
errorLog,
|
||||
},
|
||||
);
|
||||
|
||||
expect(result.attempted).toBe(true);
|
||||
expect(result.settingsGuard).toBeUndefined();
|
||||
expect(doGuard).not.toHaveBeenCalled();
|
||||
expect(errorLog).toHaveBeenCalledWith(expect.stringContaining('Framework re-seed skipped'));
|
||||
});
|
||||
|
||||
it('end-to-end (real runUpdatePathSettingsGuard, real temp files): reseed ok + activatable=false strips hooks in the live settings.json path', () => {
|
||||
const root = mkdtempSync(join(tmpdir(), 'mosaic-update-reseed-flow-e2e-'));
|
||||
try {
|
||||
const mosaicHome = join(root, 'mosaic-home');
|
||||
const claudeHome = join(root, 'claude-home');
|
||||
mkdirSync(join(mosaicHome, 'runtime', 'claude'), { recursive: true });
|
||||
writeFileSync(join(mosaicHome, 'runtime', 'claude', 'settings.json'), fixtureJson());
|
||||
// Pre-existing (stale, install-time) settings.json still carrying the
|
||||
// enforcement hooks — this is the exact state #882 (b) left behind.
|
||||
mkdirSync(claudeHome, { recursive: true });
|
||||
writeFileSync(join(claudeHome, 'settings.json'), fixtureJson());
|
||||
|
||||
const errorLog = vi.fn();
|
||||
const result = runUpdateReseedFlow(
|
||||
'Re-seeding…',
|
||||
{ reseed: true },
|
||||
{
|
||||
runFrameworkReseed: () => okReseed,
|
||||
runUpdatePathSettingsGuard: (mh, ch, options, deps) =>
|
||||
// Exercise the REAL function (imported above), pointed at temp dirs,
|
||||
// with the activation probe faked to prove this is not a live-host test.
|
||||
runUpdatePathSettingsGuardWithFakeActivation(
|
||||
mh ?? mosaicHome,
|
||||
ch ?? claudeHome,
|
||||
options,
|
||||
deps,
|
||||
),
|
||||
refreshActiveFleetUnits: () => ({ refreshed: [], ok: true }),
|
||||
readRosterAgentNames: () => [],
|
||||
log: vi.fn(),
|
||||
warnLog: vi.fn(),
|
||||
errorLog,
|
||||
},
|
||||
);
|
||||
|
||||
expect(result.settingsGuard?.result?.exitCode).toBe(1);
|
||||
const written = JSON.parse(
|
||||
readFileSync(join(claudeHome, 'settings.json'), 'utf-8'),
|
||||
) as Record<string, unknown>;
|
||||
expect(settingsHasEnforcementHooks(written)).toBe(false);
|
||||
expect(errorLog).toHaveBeenCalledWith(FAIL_LOUD_MESSAGE);
|
||||
} finally {
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
function runUpdatePathSettingsGuardWithFakeActivation(
|
||||
mosaicHome: string,
|
||||
claudeHome: string,
|
||||
options: Parameters<typeof runUpdatePathSettingsGuard>[2],
|
||||
_deps: Parameters<typeof runUpdatePathSettingsGuard>[3],
|
||||
): ReturnType<typeof runUpdatePathSettingsGuard> {
|
||||
return runUpdatePathSettingsGuard(mosaicHome, claudeHome, options, { activatable: () => false });
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanity check: the enforcement markers this suite exercises must match the
|
||||
* ones the C2 guard (`install-ordering-guard.ts`) actually looks for, so a
|
||||
* drift in either module's marker strings would fail this suite loudly
|
||||
* rather than silently passing on the wrong hooks.
|
||||
*/
|
||||
describe('marker parity with the C2 guard', () => {
|
||||
it('the fixture uses the same marker commands the guard matches on', () => {
|
||||
const preToolUse = FIXTURE_SETTINGS.hooks.PreToolUse[0]?.hooks[0]?.command ?? '';
|
||||
const stop = FIXTURE_SETTINGS.hooks.Stop[0]?.hooks[0]?.command ?? '';
|
||||
expect(preToolUse).toContain(ENFORCEMENT_HOOK_MARKERS.preToolUse);
|
||||
expect(stop).toContain(ENFORCEMENT_HOOK_MARKERS.stop);
|
||||
});
|
||||
});
|
||||
@@ -44,6 +44,12 @@ import {
|
||||
readRegularFileSecure,
|
||||
} from '../fleet/secure-file.js';
|
||||
import { getDefaultSkillPaths, syncClaudeSkills, type SkillSyncResult } from '../commands/skill.js';
|
||||
import {
|
||||
runInstallOrderingGuard,
|
||||
type InstallOrderingGuardDeps,
|
||||
type InstallOrderingGuardOptions,
|
||||
type RunInstallOrderingGuardResult,
|
||||
} from '../commands/install-ordering-guard.js';
|
||||
|
||||
// ─── Types ──────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -908,6 +914,175 @@ export function runFrameworkReseed(
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Post-reseed install-ordering guard (#882, Point-2 precondition) ────────
|
||||
//
|
||||
// Root cause (restated): `runFrameworkReseed` above runs the package's
|
||||
// install.sh with MOSAIC_SYNC_ONLY=1, which — by design (see install.sh) —
|
||||
// exits after the file-system phase, BEFORE the "Post-install tasks" step
|
||||
// that runs `mosaic-link-runtime-assets`. That script is where the #869
|
||||
// Point-1 C2 install-ordering guard (`runInstallOrderingGuard`,
|
||||
// `packages/mosaic/src/commands/install-ordering-guard.ts`) decides whether
|
||||
// the lease-enforcement hooks (PreToolUse mutator-gate.py / Stop
|
||||
// receipt-observer-client.py) get wired into `~/.claude/settings.json`. A
|
||||
// plain `mosaic update` reseed therefore never re-evaluated that wiring
|
||||
// decision against current activation state — the bypass this closes.
|
||||
//
|
||||
// `runUpdatePathSettingsGuard` re-applies the EXACT SAME guard (no forked
|
||||
// logic) against the MANAGED settings.json template the reseed just
|
||||
// refreshed (`<mosaicHome>/runtime/claude/settings.json`) and the live
|
||||
// `<claudeHome>/settings.json` — mirroring `copy_claude_settings_guarded`'s
|
||||
// src/dest pair in `mosaic-link-runtime-assets`.
|
||||
|
||||
export interface UpdatePathSettingsGuardResult {
|
||||
/** False when there is no settings.json template on disk to re-link (e.g. a
|
||||
* framework layout that predates runtime/claude/settings.json) — nothing to
|
||||
* guard, so the guard did not run. */
|
||||
ran: boolean;
|
||||
result?: RunInstallOrderingGuardResult;
|
||||
}
|
||||
|
||||
export function runUpdatePathSettingsGuard(
|
||||
mosaicHome = join(homedir(), '.config', 'mosaic'),
|
||||
claudeHome = process.env['CLAUDE_HOME'] ?? join(homedir(), '.claude'),
|
||||
options: InstallOrderingGuardOptions = {},
|
||||
deps: InstallOrderingGuardDeps = {},
|
||||
): UpdatePathSettingsGuardResult {
|
||||
const src = join(mosaicHome, 'runtime', 'claude', 'settings.json');
|
||||
if (!existsSync(src)) {
|
||||
return { ran: false };
|
||||
}
|
||||
const dest = join(claudeHome, 'settings.json');
|
||||
return { ran: true, result: runInstallOrderingGuard(src, dest, options, deps) };
|
||||
}
|
||||
|
||||
// ─── update-reseed flow (extracted for testability; called from cli.ts) ────
|
||||
//
|
||||
// Everything `mosaic update`'s `.action()` does once it has decided a reseed
|
||||
// should happen (both call sites already gate on `opts.reseed !== false`
|
||||
// before invoking this). Extracted out of cli.ts so the post-reseed guard
|
||||
// wiring (#882 (b)) — and the `--no-reseed` short-circuit — are directly unit
|
||||
// testable with injected fakes, matching the existing update-checker
|
||||
// conventions (see update-checker.reseed.spec.ts).
|
||||
|
||||
export interface UpdateReseedFlowOptions {
|
||||
/** Mirrors the CLI's `--no-reseed` flag (commander sets `reseed: false`
|
||||
* when passed). `false` is a pure no-op: nothing is reseeded and the
|
||||
* post-reseed settings guard is not invoked either — there is nothing to
|
||||
* re-link. */
|
||||
reseed?: boolean;
|
||||
relaunch?: boolean;
|
||||
/** Threads `--allow-inactive-enforcement` to the post-reseed settings
|
||||
* guard, identically to the install path (see install-ordering-guard.ts).
|
||||
* Never sourced from an environment variable — explicit per-invocation
|
||||
* opt-out only. */
|
||||
allowInactiveEnforcement?: boolean;
|
||||
}
|
||||
|
||||
export interface UpdateReseedFlowDeps {
|
||||
runFrameworkReseed?: typeof runFrameworkReseed;
|
||||
runUpdatePathSettingsGuard?: typeof runUpdatePathSettingsGuard;
|
||||
refreshActiveFleetUnits?: typeof refreshActiveFleetUnits;
|
||||
readRosterAgentNames?: typeof readRosterAgentNames;
|
||||
execSync?: typeof execSync;
|
||||
log?: (message: string) => void;
|
||||
warnLog?: (message: string) => void;
|
||||
errorLog?: (message: string) => void;
|
||||
}
|
||||
|
||||
export interface UpdateReseedFlowResult {
|
||||
/** Whether a reseed was actually attempted (false only for `--no-reseed`). */
|
||||
attempted: boolean;
|
||||
reseed?: FrameworkReseedResult;
|
||||
settingsGuard?: UpdatePathSettingsGuardResult;
|
||||
}
|
||||
|
||||
export function runUpdateReseedFlow(
|
||||
reason: string,
|
||||
options: UpdateReseedFlowOptions = {},
|
||||
deps: UpdateReseedFlowDeps = {},
|
||||
): UpdateReseedFlowResult {
|
||||
if (options.reseed === false) {
|
||||
// Nothing to re-seed, and therefore nothing to re-link/guard either.
|
||||
return { attempted: false };
|
||||
}
|
||||
|
||||
const log = deps.log ?? console.log;
|
||||
const warnLog = deps.warnLog ?? console.warn;
|
||||
const errorLog = deps.errorLog ?? console.error;
|
||||
const doReseed = deps.runFrameworkReseed ?? runFrameworkReseed;
|
||||
const doGuard = deps.runUpdatePathSettingsGuard ?? runUpdatePathSettingsGuard;
|
||||
const doRefresh = deps.refreshActiveFleetUnits ?? refreshActiveFleetUnits;
|
||||
const doReadRoster = deps.readRosterAgentNames ?? readRosterAgentNames;
|
||||
const exec = deps.execSync ?? execSync;
|
||||
|
||||
log(reason);
|
||||
const reseed = doReseed();
|
||||
if (!reseed.ok) {
|
||||
errorLog(
|
||||
`\n⚠ Framework re-seed skipped: ${reseed.reason ?? 'unknown'}.\n` +
|
||||
' Activate manually: bash "$(npm root -g)/@mosaicstack/mosaic/framework/install.sh" ' +
|
||||
'(MOSAIC_SYNC_ONLY=1 MOSAIC_INSTALL_MODE=keep)',
|
||||
);
|
||||
return { attempted: true, reseed };
|
||||
}
|
||||
log('✔ Framework re-seeded.');
|
||||
if (reseed.skillSyncError) {
|
||||
errorLog(` ⚠ Claude skill reconciliation skipped: ${reseed.skillSyncError}`);
|
||||
}
|
||||
const skillConflicts = reseed.skillSync?.conflicts ?? [];
|
||||
const skillChanges =
|
||||
(reseed.skillSync?.registered.length ?? 0) + (reseed.skillSync?.repaired.length ?? 0);
|
||||
if (skillChanges > 0) {
|
||||
log(`✔ Registered ${skillChanges.toString()} Mosaic skill(s) with Claude Code.`);
|
||||
}
|
||||
for (const conflict of skillConflicts) {
|
||||
errorLog(` ⚠ Skill registration skipped for ${conflict.name}: ${conflict.reason}`);
|
||||
}
|
||||
|
||||
// #882 (b): re-apply the install-ordering guard (C2) to the MANAGED
|
||||
// settings.json the reseed just refreshed. install.sh's sync-only mode
|
||||
// never reaches the post-install step that would otherwise do this, so
|
||||
// `mosaic update` must do it itself — closing the bypass for every update
|
||||
// path. Never swallow the guard's fail-loud/opt-out output on this path.
|
||||
const settingsGuard = doGuard(undefined, undefined, {
|
||||
allowInactiveEnforcement: options.allowInactiveEnforcement === true,
|
||||
});
|
||||
if (settingsGuard.ran && settingsGuard.result) {
|
||||
for (const line of settingsGuard.result.logs) {
|
||||
(line.level === 'error' ? errorLog : warnLog)(line.message);
|
||||
}
|
||||
}
|
||||
|
||||
// Propagate shipped systemd unit fixes to the ACTIVE units (re-seed only
|
||||
// touches ~/.config/mosaic/systemd/user; systemd runs ~/.config/systemd/user).
|
||||
const units = doRefresh();
|
||||
if (units.refreshed.length > 0) {
|
||||
log(`✔ Refreshed ${units.refreshed.length} active systemd unit(s).`);
|
||||
}
|
||||
const agents = doReadRoster();
|
||||
if (agents.length > 0) {
|
||||
if (options.relaunch) {
|
||||
log(`\nRelaunching ${agents.length} fleet agent(s) to pick up the new runtime…`);
|
||||
for (const restart of buildRelaunchCommands(agents)) {
|
||||
try {
|
||||
exec(restart.join(' '), { stdio: 'inherit', timeout: 30_000 });
|
||||
} catch {
|
||||
errorLog(` ⚠ failed to restart agent — run: ${restart.join(' ')}`);
|
||||
}
|
||||
}
|
||||
log('✔ Agents relaunched.');
|
||||
} else {
|
||||
log(
|
||||
`\nℹ ${agents.length} fleet agent(s) are still running the previous runtime. ` +
|
||||
'Restart them to activate the update:\n mosaic update --relaunch ' +
|
||||
'(or: mosaic fleet restart <agent>)',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return { attempted: true, reseed, settingsGuard };
|
||||
}
|
||||
|
||||
// ─── Framework drift detection (#642) ────────────────────────────────────────
|
||||
//
|
||||
// `mosaic update` only re-seeds the framework when the @mosaicstack/mosaic
|
||||
|
||||
Reference in New Issue
Block a user