Compare commits

..

3 Commits

Author SHA1 Message Date
mosaic-coder
84d802cafe fix(framework): detect-platform get_gitea_token fail-loud on absent per-slot token (Patch 2b)
All checks were successful
ci/woodpecker/pr/ci Pipeline was successful
The per-agent identity resolution added to get_gitea_token() (Patch 2 /
#873) resolves an explicit identity (MOSAIC_GIT_IDENTITY env, or git
config mosaic.gitIdentity) and returns that identity's per-slot Gitea
token when present. Gap: when the identity resolves but its per-slot
token file is ABSENT for a recognized Gitea host, the function fell
through to the shared/default credential-loader token instead of
failing. API tooling (pr-create.sh, issue-create.sh, pr-review.sh) then
silently posted the PR/issue/review as the WRONG agent — e.g. a
reviewer seat's Gate-16 review getting attributed to the shared/default
identity — corrupting author≠reviewer separation while also masking
the missing-token misconfiguration. This surfaced most often on the
tea-stale API-fallback path, which is exactly when tooling leans on
get_gitea_token.

Fix: in the step-0 explicit-identity branch, when the per-slot token
for that identity is absent on a recognized Gitea host, print a stderr
diagnostic naming the identity, its source (env vs git config), the
host, and the expected token path, then return 1 instead of falling
through. All three callers already `return 1` on a nonzero
get_gitea_token, so fail-loud propagates with zero caller edits.

Scope (deliberate, minimal blast radius): explicit-identity-only. Plain
`git config user.name` is not an identity trigger — only
MOSAIC_GIT_IDENTITY / git config mosaic.gitIdentity count, so ordinary
shared/human repo usage is unaffected. Recognized-Gitea-hosts-only:
unrecognized hosts have no per-slot token scheme, so identity-set +
unknown-host still falls through unchanged (no fail-loud). The
MOSAIC_STRICT_IDENTITY opt-in discussed as a possible future extension
(gating the full `... > git username` chain) is deliberately NOT part
of this patch — deferred per spec as a later, separate proposal.

Red-first: stashed the source fix, ran the extended
test-gitea-token-identity.sh — 16 assertions failed exactly as
expected (shared token leaked, no fail-loud diagnostic). Restored the
fix — all green, full test:framework-shell chain passes. Backward
compat verified: the no-identity-requested case still returns the
shared token unchanged.

Extends test-gitea-token-identity.sh: the no-per-slot-token case (both
identity sources: env and git config) on a recognized host now asserts
nonzero return + empty stdout + stderr diagnostic naming
identity/source/host/expected path, instead of asserting a shared-token
fallback. Adds a same-identity cross-host case (token exists for one
host, absent for another → fail-loud on the host lacking it, no
cross-host token leak) and a scope-containment case (identity set +
unrecognized host → existing fall-through behavior unchanged, fail-loud
diagnostic does not fire).

Gates: shellcheck clean on both changed files, sanitization gate
(verify-sanitized.sh) passes, full test:framework-shell chain green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0158NZqN2n2ymKFeJAZ4GUCb
2026-07-25 12:29:08 -05:00
529c177830 fix(update): mosaic update runs the install-ordering guard post-reseed (#882 --sync-only bypass) (#883)
All checks were successful
ci/woodpecker/push/publish Pipeline was successful
ci/woodpecker/push/ci Pipeline was successful
Co-authored-by: jason.woltje <jason@diversecanvas.com>
Co-committed-by: jason.woltje <jason@diversecanvas.com>
2026-07-23 22:18:34 +00:00
a32ce4c8f9 feat(869-c4): activation version-coupling assertion (Part of #869)
All checks were successful
ci/woodpecker/push/publish Pipeline was successful
ci/woodpecker/push/ci Pipeline was successful
Part of #869

Mos (id-11) Gate-16 merge: independent APPROVE @90eb48fa (fail-closed identity locks byte-unchanged verified), author id2 != approver id11, clean mosaic-coder author, CI green wp1992. #869 Point-1 CODE COMPLETE (C1/C3/C5/C2/C4).

Co-authored-by: jason.woltje <jason@diversecanvas.com>
Co-committed-by: jason.woltje <jason@diversecanvas.com>
2026-07-23 19:07:27 +00:00
5 changed files with 746 additions and 69 deletions

View File

@@ -511,7 +511,11 @@ get_gitea_token() {
# (pr-create, issue-create, …) authors under the right identity — matching the # (pr-create, issue-create, …) authors under the right identity — matching the
# git credential helper. Backward-compatible: nothing resolvable → shared logic below. # git credential helper. Backward-compatible: nothing resolvable → shared logic below.
local _ident="${MOSAIC_GIT_IDENTITY:-}" local _ident="${MOSAIC_GIT_IDENTITY:-}"
[[ -z "$_ident" ]] && _ident="$(git config --get mosaic.gitIdentity 2>/dev/null || true)" local _ident_src="MOSAIC_GIT_IDENTITY"
if [[ -z "$_ident" ]]; then
_ident="$(git config --get mosaic.gitIdentity 2>/dev/null || true)"
_ident_src="git config mosaic.gitIdentity"
fi
if [[ -n "$_ident" ]]; then if [[ -n "$_ident" ]]; then
local _idpfx="" local _idpfx=""
case "$host" in case "$host" in
@@ -524,6 +528,15 @@ get_gitea_token() {
cat "$_idtok" cat "$_idtok"
return 0 return 0
fi fi
# FAIL LOUD: an explicit git identity was requested for a recognized Gitea host,
# but no per-slot token exists for THAT identity. Refuse to fall through to the
# shared/default credential loader below — silently borrowing another slot's token
# would post PRs/issues/reviews under the WRONG agent (e.g. rev2's review attributed
# to coder3), corrupting Gate-16 author≠reviewer separation. Hard-stop instead so the
# caller aborts loudly rather than acting as the wrong identity.
echo "Error: git identity '$_ident' requested (via $_ident_src) for host '$host', but no per-slot token at $_idtok." >&2
echo " Refusing to borrow another slot's token. Provision the per-slot token, or unset the identity to use shared credentials." >&2
return 1
fi fi
fi fi

View File

@@ -10,10 +10,19 @@
# 2. Correct per-slot token file path chosen per host # 2. Correct per-slot token file path chosen per host
# (gitea-usc-<id>.token vs gitea-mosaicstack-<id>.token). # (gitea-usc-<id>.token vs gitea-mosaicstack-<id>.token).
# 3. Per-slot token present -> that token is returned (agent-authored calls). # 3. Per-slot token present -> that token is returned (agent-authored calls).
# 4. Per-slot token absent -> falls back to the shared credential-loader # 4. No identity requested -> shared credential-loader token (backward
# token (backward-compat / no-op for hosts without per-slot tokens). # compat, unchanged).
# 5. Unrelated host with no shared credentials configured -> failure # 5. Patch 2b — explicit identity + recognized Gitea host + ABSENT per-slot
# (unchanged, existing behavior). # token for that identity -> FAIL LOUD (nonzero return, empty stdout, a
# stderr diagnostic naming identity/source/host/expected path). Must NOT
# fall through to the shared/default token (Gate-16 author≠reviewer
# integrity — never silently borrow another slot's credentials). Covered
# for both identity sources (git config, MOSAIC_GIT_IDENTITY env) and
# for a same-identity cross-host case (token exists for one host, not
# the other).
# 6. Scope containment: identity requested + an UNRECOGNIZED Gitea host (no
# per-slot token scheme) -> Patch 2b does not apply; existing
# fall-through behavior is unchanged.
# #
# Uses a stubbed credentials.json + stubbed per-slot token files under a fake # Uses a stubbed credentials.json + stubbed per-slot token files under a fake
# HOME. NEVER reads real secrets or touches the real ~/.config/mosaic/secrets. # HOME. NEVER reads real secrets or touches the real ~/.config/mosaic/secrets.
@@ -95,24 +104,110 @@ out=$(call_get_gitea_token "git.mosaicstack.dev" MOSAIC_GIT_IDENTITY=agentB)
assert_eq "env beats git-config identity token" "agentB-mosaicstack-token" "$out" assert_eq "env beats git-config identity token" "agentB-mosaicstack-token" "$out"
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# 4. Identity resolves but has no per-slot token for THIS host -> falls back # 4. FAIL LOUD (Patch 2b): an identity is explicitly requested (via git config
# to the shared token (per-agent identity is opt-in per host). # mosaic.gitIdentity, and separately via MOSAIC_GIT_IDENTITY env) for a
# RECOGNIZED Gitea host, but no per-slot token exists for THAT identity.
# Must NOT fall through to the shared/default token — silently borrowing
# another slot's credentials would post PRs/issues/reviews as the WRONG
# agent (Gate-16 author≠reviewer integrity break). Expect: nonzero return,
# EMPTY stdout (no token — shared or otherwise — leaked), and a stderr
# diagnostic naming the identity, its source, the host, and the expected
# per-slot token path.
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
assert_failloud() {
local desc="$1" host="$2" ident="$3" expected_tok_path="$4"; shift 4
local stderr_file="$WORK_DIR/stderr.tmp"
: > "$stderr_file"
set +e
local stdout
stdout=$(call_get_gitea_token "$host" "$@" 2>"$stderr_file")
local rc=$?
set -e
local stderr
stderr=$(cat "$stderr_file")
if [[ "$rc" -eq 0 ]]; then
echo "FAIL: $desc — expected nonzero return, got 0 (stdout='$stdout')" >&2
fail=1
fi
if [[ -n "$stdout" ]]; then
echo "FAIL: $desc — expected empty stdout (no token leaked), got '$stdout'" >&2
fail=1
fi
if [[ "$stderr" != *"$ident"* ]]; then
echo "FAIL: $desc — stderr does not name the requested identity '$ident':" >&2
echo "$stderr" >&2
fail=1
fi
if [[ "$stderr" != *"$host"* ]]; then
echo "FAIL: $desc — stderr does not name the host '$host':" >&2
echo "$stderr" >&2
fail=1
fi
if [[ "$stderr" != *"$expected_tok_path"* ]]; then
echo "FAIL: $desc — stderr does not name the expected per-slot token path '$expected_tok_path':" >&2
echo "$stderr" >&2
fail=1
fi
if [[ "$stderr" == *"shared"*"token"* ]]; then
echo "FAIL: $desc — stderr unexpectedly mentions a shared token value:" >&2
echo "$stderr" >&2
fail=1
fi
}
# 4a. git config mosaic.gitIdentity source, recognized host (mosaicstack),
# shared token IS present but must not be borrowed.
git -C "$REPO_DIR" config mosaic.gitIdentity no-such-agent git -C "$REPO_DIR" config mosaic.gitIdentity no-such-agent
out=$(call_get_gitea_token "git.mosaicstack.dev") assert_failloud "fail-loud via git-config identity (recognized host)" \
assert_eq "no per-slot token falls back to shared" "shared-mosaicstack-token" "$out" "git.mosaicstack.dev" "no-such-agent" \
"$FAKE_HOME/.config/mosaic/secrets/gitea-tokens/gitea-mosaicstack-no-such-agent.token"
git -C "$REPO_DIR" config --unset mosaic.gitIdentity
# 4b. MOSAIC_GIT_IDENTITY env source (takes priority over git config), same
# recognized-host / absent-token scenario -> also fails loud.
assert_failloud "fail-loud via MOSAIC_GIT_IDENTITY env (recognized host)" \
"git.mosaicstack.dev" "no-such-agent-env" \
"$FAKE_HOME/.config/mosaic/secrets/gitea-tokens/gitea-mosaicstack-no-such-agent-env.token" \
MOSAIC_GIT_IDENTITY=no-such-agent-env
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# 5. Correct per-slot token PATH per host: same agent id, only a usc token # 5. Correct per-slot token PATH per host: same agent id, only a usc token
# exists -> usc host returns it, mosaicstack host must NOT leak it and # exists. usc host returns it (happy path, unchanged). mosaicstack host
# instead falls back to the shared mosaicstack token. # has NO per-slot token for this identity -> Patch 2b fail-loud applies
# there too (must NOT fall back to the shared mosaicstack token, and must
# NOT leak the agent's usc token either).
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
echo -n "agentD-usc-token" > "$FAKE_HOME/.config/mosaic/secrets/gitea-tokens/gitea-usc-agentD.token" echo -n "agentD-usc-token" > "$FAKE_HOME/.config/mosaic/secrets/gitea-tokens/gitea-usc-agentD.token"
git -C "$REPO_DIR" config mosaic.gitIdentity agentD git -C "$REPO_DIR" config mosaic.gitIdentity agentD
out=$(call_get_gitea_token "git.uscllc.com") out=$(call_get_gitea_token "git.uscllc.com")
assert_eq "host-scoped token path (usc)" "agentD-usc-token" "$out" assert_eq "host-scoped token path (usc)" "agentD-usc-token" "$out"
out=$(call_get_gitea_token "git.mosaicstack.dev") assert_failloud "fail-loud on cross-host absence (no fallback, no cross-host leak)" \
assert_eq "host-scoped token path (no cross-host leak)" "shared-mosaicstack-token" "$out" "git.mosaicstack.dev" "agentD" \
"$FAKE_HOME/.config/mosaic/secrets/gitea-tokens/gitea-mosaicstack-agentD.token"
git -C "$REPO_DIR" config --unset mosaic.gitIdentity
# ---------------------------------------------------------------------------
# 6. Scope containment: identity explicitly requested, but the host is NOT a
# recognized Gitea host (no per-slot token scheme at all) -> Patch 2b does
# NOT apply; existing fall-through behavior is unchanged (ends in the
# pre-existing generic failure since no shared credentials match either,
# NOT the fail-loud diagnostic path).
# ---------------------------------------------------------------------------
git -C "$REPO_DIR" config mosaic.gitIdentity no-such-agent
set +e
out=$(call_get_gitea_token "github.com" 2>"$WORK_DIR/stderr-scope.tmp")
rc=$?
set -e
err=$(cat "$WORK_DIR/stderr-scope.tmp")
if [[ "$rc" -eq 0 ]]; then
echo "FAIL: unrecognized host + identity — expected nonzero (no credentials configured), got 0" >&2
fail=1
fi
if [[ "$err" == *"no per-slot token at"* ]]; then
echo "FAIL: unrecognized host + identity — fail-loud diagnostic must not fire for a host with no per-slot scheme:" >&2
echo "$err" >&2
fail=1
fi
git -C "$REPO_DIR" config --unset mosaic.gitIdentity git -C "$REPO_DIR" config --unset mosaic.gitIdentity
if [[ "$fail" -eq 0 ]]; then if [[ "$fail" -eq 0 ]]; then

View File

@@ -32,10 +32,7 @@ import {
formatAllPackagesTable, formatAllPackagesTable,
getInstallAllCommand, getInstallAllCommand,
repairFleetCommsTools, repairFleetCommsTools,
runFrameworkReseed, runUpdateReseedFlow,
refreshActiveFleetUnits,
readRosterAgentNames,
buildRelaunchCommands,
checkFrameworkDrift, checkFrameworkDrift,
FRAMEWORK_RESEED_PACKAGE, FRAMEWORK_RESEED_PACKAGE,
} from './runtime/update-checker.js'; } from './runtime/update-checker.js';
@@ -445,12 +442,18 @@ program
'--repair-tools', '--repair-tools',
'Restore the supported current-version TOOLS contract and executable fleet helper', '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( .action(
async (opts: { async (opts: {
check?: boolean; check?: boolean;
reseed?: boolean; reseed?: boolean;
relaunch?: boolean; relaunch?: boolean;
repairTools?: boolean; repairTools?: boolean;
allowInactiveEnforcement?: boolean;
}) => { }) => {
if (opts.repairTools) { if (opts.repairTools) {
const repair = repairFleetCommsTools(); const repair = repairFleetCommsTools();
@@ -471,57 +474,24 @@ program
// checkForAllUpdates imported statically above // checkForAllUpdates imported statically above
const { execSync } = await import('node:child_process'); const { execSync } = await import('node:child_process');
// Re-seed the framework from the freshly-installed package, propagate shipped // Re-seed the framework from the freshly-installed package, re-apply the
// systemd unit fixes to the active units, and (opt-in) relaunch durable // install-ordering guard to settings.json (#882 (b) — closes the
// agents. Shared by the "packages updated" and the "framework drift" paths. // `--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 => { const reseedFramework = (reason: string): void => {
console.log(reason); const flow = runUpdateReseedFlow(reason, {
const reseed = runFrameworkReseed(); reseed: opts.reseed,
if (!reseed.ok) { relaunch: opts.relaunch,
console.error( allowInactiveEnforcement: opts.allowInactiveEnforcement === true,
`\n⚠ Framework re-seed skipped: ${reseed.reason ?? 'unknown'}.\n` + });
' Activate manually: bash "$(npm root -g)/@mosaicstack/mosaic/framework/install.sh" ' + if (flow.settingsGuard?.ran && flow.settingsGuard.result?.exitCode === 1) {
'(MOSAIC_SYNC_ONLY=1 MOSAIC_INSTALL_MODE=keep)', // Fail-loud: enforcement hooks were refused/stripped. Surface this
); // in the command's own exit status without aborting the rest of
return; // the update (mirrors mosaic-link-runtime-assets' guard_degraded).
} process.exitCode = 1;
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>)',
);
} }
}; };
@@ -544,7 +514,7 @@ program
// package is reported outdated. Detect that via the framework version and // package is reported outdated. Detect that via the framework version and
// re-seed so shipped launcher/runtime fixes still activate. // re-seed so shipped launcher/runtime fixes still activate.
const drift = checkFrameworkDrift(); const drift = checkFrameworkDrift();
if (drift.drifted && opts.reseed !== false) { if (drift.drifted) {
reseedFramework( reseedFramework(
`\nFramework drift detected (on-disk v${drift.installed} < bundled v${drift.bundled}) — ` + `\nFramework drift detected (on-disk v${drift.installed} < bundled v${drift.bundled}) — ` +
'the CLI was updated outside `mosaic update`. Re-seeding framework files into ' + '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, (r: { package: string }) => r.package === FRAMEWORK_RESEED_PACKAGE,
); );
const drift = checkFrameworkDrift(); const drift = checkFrameworkDrift();
if ((mosaicUpdated || drift.drifted) && opts.reseed !== false) { if (mosaicUpdated || drift.drifted) {
reseedFramework( reseedFramework(
'\nRe-seeding framework files into ~/.config/mosaic (data-safe; keeps your edits)…', '\nRe-seeding framework files into ~/.config/mosaic (data-safe; keeps your edits)…',
); );

View File

@@ -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);
});
});

View File

@@ -44,6 +44,12 @@ import {
readRegularFileSecure, readRegularFileSecure,
} from '../fleet/secure-file.js'; } from '../fleet/secure-file.js';
import { getDefaultSkillPaths, syncClaudeSkills, type SkillSyncResult } from '../commands/skill.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 ────────────────────────────────────────────────────────────────── // ─── 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) ──────────────────────────────────────── // ─── Framework drift detection (#642) ────────────────────────────────────────
// //
// `mosaic update` only re-seeds the framework when the @mosaicstack/mosaic // `mosaic update` only re-seeds the framework when the @mosaicstack/mosaic