Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6a9b00f969 | ||
|
|
1d84bc3f3d | ||
|
|
6306914965 | ||
|
|
af43a7a63e | ||
|
|
ca97b885b0 | ||
|
|
6db0bead44 | ||
|
|
c671290d77 | ||
|
|
6a9b2cf6c1 | ||
|
|
6bd93a621d | ||
|
|
e9485c3d96 | ||
|
|
d2f0846dcc | ||
|
|
4f22a58041 | ||
|
|
9b6869fab7 | ||
|
|
20ad89c86b | ||
|
|
a55d1a1812 | ||
|
|
9abd7e386f | ||
|
|
9af456c240 | ||
|
|
cb9a0d1642 | ||
|
|
420507da77 | ||
|
|
2508f0aa99 | ||
|
|
d339e8fd21 | ||
|
|
018d96a412 | ||
|
|
b01950e92f | ||
|
|
1bdeed62eb | ||
|
|
840c2b0d96 | ||
|
|
95d5cb32d4 | ||
|
|
d5f3fae896 | ||
|
|
1556982dbc | ||
|
|
1a822493ba | ||
|
|
d2eeb64433 | ||
|
|
5e58597dbe | ||
|
|
fe4fa20309 | ||
|
|
5e93ef70bd | ||
|
|
3884f2de4d | ||
|
|
a3c50d91ca | ||
|
|
2fd102e6af | ||
|
|
efb3c3a10c | ||
|
|
d4d32a80b2 | ||
|
|
c703cc50eb | ||
|
|
3d2b712355 | ||
|
|
245e0c427d | ||
|
|
ff45f7b5d0 | ||
|
|
64350892e7 | ||
|
|
6e9df3c640 | ||
|
|
f5ba042dfa | ||
|
|
7c7dab3898 | ||
|
|
d92de53399 | ||
|
|
d7e303d3c0 | ||
|
|
7102ccb93e | ||
|
|
afdaa6d0e6 | ||
|
|
41749bbd33 | ||
|
|
120af4e193 | ||
|
|
ec260e678f | ||
|
|
b590a5c3d8 | ||
|
|
540ec5b6ef | ||
|
|
563d1ac053 | ||
|
|
4d8ddb9a0a | ||
|
|
722163671f | ||
|
|
f158be8003 | ||
|
|
b0f7d26dd9 | ||
|
|
3a1203b2f8 | ||
|
|
df4c591ab4 | ||
|
|
4fa2768962 | ||
|
|
aa0a7b5fa2 | ||
|
|
42ac19af48 | ||
|
|
f744f32214 | ||
|
|
8ff7aac0ca | ||
|
|
80a45b1e1c | ||
|
|
85d2108e4e | ||
|
|
16f91157a1 | ||
|
|
2fa6bcd576 | ||
|
|
1afe2b36dc | ||
|
|
63e77887a8 | ||
|
|
809ca9a1d9 | ||
|
|
57435bb879 | ||
|
|
8c51bf7575 | ||
|
|
c3d2179ad8 | ||
|
|
b47c4024cc | ||
|
|
74d1cdc7c1 | ||
|
|
8cae9e0883 | ||
|
|
2c524b6da2 | ||
|
|
b4f2019529 | ||
|
|
b1eb1fb2f9 | ||
|
|
dfeb4d9692 | ||
|
|
7ea13332ed | ||
|
|
b032d23889 | ||
|
|
ecde74439c |
@@ -0,0 +1,4 @@
|
|||||||
|
{
|
||||||
|
"integration_trunk": "next",
|
||||||
|
"release_branch": "main"
|
||||||
|
}
|
||||||
+50
-6
@@ -2,16 +2,38 @@
|
|||||||
# node:24-alpine + python3/make/g++/postgresql-client + pnpm + a warm pnpm
|
# node:24-alpine + python3/make/g++/postgresql-client + pnpm + a warm pnpm
|
||||||
# store. The install step resolves from the baked store (--prefer-offline)
|
# store. The install step resolves from the baked store (--prefer-offline)
|
||||||
# instead of paying a ~731s cold fetch + native compile every run.
|
# instead of paying a ~731s cold fetch + native compile every run.
|
||||||
|
#
|
||||||
|
# PINNED to an immutable lock-tag (#1328, brain D27): ci-image.yml pushes
|
||||||
|
# lock-<sha256(pnpm-lock.yaml)[:12]> atomically with :latest, so the two are
|
||||||
|
# byte-identical at push time. A mutable :latest resolves per-pod at pull time
|
||||||
|
# on the k8s backend, which made CI verdicts non-reproducible (same tree, same
|
||||||
|
# config, different images across runs; see #1324 comment 23382/23386). The pin
|
||||||
|
# changes ONLY through reviewed commits; a wrong tag fails loudly at image pull.
|
||||||
|
#
|
||||||
|
# Bump procedure: when a recipe change (pnpm-lock.yaml / Dockerfile.ci) lands on
|
||||||
|
# main, ci-image.yml pushes lock-<new>; a follow-up PR updates this anchor.
|
||||||
|
# Until then pipelines keep the old pin: reproducible, with the documented
|
||||||
|
# network-fallback lag (frozen-lockfile resolves missing packages from network).
|
||||||
|
# Known limitation: lock- addresses the lockfile only, so a Dockerfile-only
|
||||||
|
# change re-pushes the same tag with new content (#1328 follow-up: recipe-hash).
|
||||||
variables:
|
variables:
|
||||||
- &node_image 'git.mosaicstack.dev/mosaicstack/stack/ci-base:latest'
|
- &node_image 'git.mosaicstack.dev/mosaicstack/stack/ci-base:lock-9cb7ffcd8828'
|
||||||
- &enable_pnpm 'corepack enable'
|
- &enable_pnpm 'corepack enable'
|
||||||
|
|
||||||
when:
|
when:
|
||||||
# PR + manual CI run on any branch — the pull_request pipeline is the merge gate.
|
# PR + manual CI run on any branch: the pull_request pipeline is the merge
|
||||||
# push CI is restricted to protected branches (main) so a feature-branch push no
|
# gate (next is protected and the default branch since 2026-08-19).
|
||||||
# longer fires a redundant SECOND pipeline alongside its PR pipeline. This ~halves
|
# Push CI runs on main only. next deliberately runs NO push ci: post-merge
|
||||||
# CI load on the storage-constrained runner with zero loss of gating (branch
|
# verification on next is carried by publish.yml's `verify` step
|
||||||
# protection requires no push/ci status context; main still gets full push CI).
|
# (pnpm verify:release), which mirrors this pipeline's complete mandatory
|
||||||
|
# set step-for-step, enforced by scripts/verify-release.test.mjs. PR CI
|
||||||
|
# tests the PR HEAD tree (refs/pull/N/head, measured 2026-08-19), not a
|
||||||
|
# merge ref, so if next advances before a merge the landed tree differs
|
||||||
|
# from the tested one; publish verify re-runs the full set on the landed
|
||||||
|
# tree (PGlite path). Measured 2026-08-19: the 21 most recent push events
|
||||||
|
# on next each ran exactly one pipeline (publish), zero ci.
|
||||||
|
# Keeping push ci off next also avoids a redundant second full-suite run
|
||||||
|
# per merge on the storage-constrained runner.
|
||||||
- event: [pull_request, manual]
|
- event: [pull_request, manual]
|
||||||
- event: push
|
- event: push
|
||||||
branch: main
|
branch: main
|
||||||
@@ -59,6 +81,28 @@ steps:
|
|||||||
# [0] of the pnpm chain, so severing that chain would silence it together
|
# [0] of the pnpm chain, so severing that chain would silence it together
|
||||||
# with everything it guards; this direct line keeps one instrument running.
|
# with everything it guards; this direct line keeps one instrument running.
|
||||||
- bash packages/mosaic/framework/tools/quality/scripts/check-test-enumeration.sh
|
- bash packages/mosaic/framework/tools/quality/scripts/check-test-enumeration.sh
|
||||||
|
# Tool-index gate: a shipped wrapper that appears in no resident index doc
|
||||||
|
# is undiscoverable from inside a session, and an agent that cannot learn a
|
||||||
|
# wrapper exists reaches for raw curl instead — which is how a Gitea review
|
||||||
|
# got filed PENDING three times. Ships-and-documented is one commit, or red.
|
||||||
|
- bash packages/mosaic/framework/tools/quality/scripts/check-tools-index.sh --self-test
|
||||||
|
- bash packages/mosaic/framework/tools/quality/scripts/check-tools-index.sh
|
||||||
|
# Hermetic regression for issue-close.sh (#1081): mocks tea/curl onto PATH
|
||||||
|
# and sandboxes a throwaway git repo, so it resolves no real credentials and
|
||||||
|
# joins CI directly rather than the exclusions file.
|
||||||
|
- bash packages/mosaic/framework/tools/git/test-issue-close-fail-closed.sh
|
||||||
|
# Hermetic behavioural regression for the PreToolUse wrapper guard: proves
|
||||||
|
# it still blocks the three mistakes AND still lets reads, unwrapped
|
||||||
|
# endpoints and ordinary commands through. Both directions are asserted —
|
||||||
|
# a guard that over-blocks gets routed around, which fails just as hard.
|
||||||
|
- bash packages/mosaic/framework/tools/git/test-wrapper-guard.sh
|
||||||
|
# Hermetic regression for mosaic-worktree.sh at fleet scale: stubs git onto
|
||||||
|
# PATH so `list` faces ~450 KB of porcelain. The defect it pins is invisible
|
||||||
|
# at small size — `git … | awk '…exit'` gives the producer SIGPIPE, which
|
||||||
|
# under `set -euo pipefail` aborts the caller silently with rc=141 and no
|
||||||
|
# output. A repo only reaches that once it has enough worktrees, so the
|
||||||
|
# stub supplies the scale instead of the host's own checkout.
|
||||||
|
- bash packages/mosaic/framework/tools/git/test-mosaic-worktree-large-repo.sh
|
||||||
|
|
||||||
# Canonical verify:release stage `upgrade-guard`.
|
# Canonical verify:release stage `upgrade-guard`.
|
||||||
# Blocking gate (#791): a framework upgrade must never write or delete an
|
# Blocking gate (#791): a framework upgrade must never write or delete an
|
||||||
|
|||||||
@@ -18,7 +18,12 @@
|
|||||||
variables:
|
variables:
|
||||||
# Pre-baked CI base (see .woodpecker/ci-image.yml): node:24-alpine +
|
# Pre-baked CI base (see .woodpecker/ci-image.yml): node:24-alpine +
|
||||||
# toolchain + warm pnpm store. Kills the second cold install publish pays.
|
# toolchain + warm pnpm store. Kills the second cold install publish pays.
|
||||||
- &node_image 'git.mosaicstack.dev/mosaicstack/stack/ci-base:latest'
|
# PINNED to the immutable lock-tag, not :latest (#1328, brain D27): a mutable
|
||||||
|
# tag resolves per-pod at pull time on the k8s backend and made CI verdicts
|
||||||
|
# non-reproducible (#1324). Byte-identical to :latest at pin time (pushed
|
||||||
|
# atomically by the same kaniko run, main 712c770, 2026-07-26). Bump only via
|
||||||
|
# reviewed PR, per the procedure in .woodpecker/ci.yml's header comment.
|
||||||
|
- &node_image 'git.mosaicstack.dev/mosaicstack/stack/ci-base:lock-9cb7ffcd8828'
|
||||||
- &enable_pnpm 'corepack enable'
|
- &enable_pnpm 'corepack enable'
|
||||||
# Heavy kaniko image builds (~25 min) — gate them so a merge that only touches
|
# Heavy kaniko image builds (~25 min) — gate them so a merge that only touches
|
||||||
# the npm-only CLI (@mosaicstack/mosaic) or docs does NOT rebuild the platform
|
# the npm-only CLI (@mosaicstack/mosaic) or docs does NOT rebuild the platform
|
||||||
|
|||||||
@@ -81,6 +81,73 @@ pnpm format:check # Prettier check
|
|||||||
pnpm build # Build all packages and applications
|
pnpm build # Build all packages and applications
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Branch Model and Merge Process — `main` and `next` (CANONICAL)
|
||||||
|
|
||||||
|
**Every contribution targets `next` first. No exceptions.** Features, fixes, tests,
|
||||||
|
docs, and policy changes all take the same route; urgency changes queue priority,
|
||||||
|
never the route. Agents never commit to or merge into `main`.
|
||||||
|
|
||||||
|
| Branch | Role | Who merges into it |
|
||||||
|
| ------ | ---------------------------------------------------------------- | --------------------------------------------------------------------------- |
|
||||||
|
| `next` | Integration trunk — the only PR target for contributions | The designated merge-gate agent, after all gates pass. Never the PR author. |
|
||||||
|
| `main` | Stable/release line — receives promotion merges from `next` only | Jason only (or an agent he explicitly delegates for a named promotion). |
|
||||||
|
|
||||||
|
### Contribution sequencing (in order, no skipping)
|
||||||
|
|
||||||
|
1. **Issue first.** Work is tracked in a Gitea issue before a branch exists. The
|
||||||
|
issue number appears in the branch name and the PR body.
|
||||||
|
2. **Branch from the current `origin/next` head.** Name it
|
||||||
|
`feat/…`, `fix/…`, `docs/…`, or `test/…` with the issue number
|
||||||
|
(e.g. `docs/1214-branch-process`). Record the base SHA in the PR body.
|
||||||
|
3. **Develop with evidence.** Applicable tests accompany the change. Hooks are
|
||||||
|
never bypassed (`--no-verify` is prohibited). Stage explicit paths — never
|
||||||
|
`git add -A`.
|
||||||
|
4. **Open the PR against `next`.** The body states: scope, base SHA,
|
||||||
|
verification commands with results, and any known pre-existing failures on
|
||||||
|
the base — documented, not retried to green and not absorbed silently.
|
||||||
|
5. **CI must be terminal-green on the exact head.** All bounded Woodpecker
|
||||||
|
steps succeed (`verify-terminal-green` contract). Pipelines for fork PRs
|
||||||
|
start `blocked`; a maintainer approves the run — approving CI is not
|
||||||
|
approving the PR.
|
||||||
|
6. **Independent review. Self-merge is prohibited** — for every agent, on every
|
||||||
|
PR, including trivial ones. Where the change touches protected or
|
||||||
|
contract-bearing content, the reviewer verifies the exact head
|
||||||
|
(exact-byte/exact-blob comparison), not a description of it. An `AMEND`
|
||||||
|
verdict returns the PR to its author; the reviewer's gate stays held until
|
||||||
|
a fresh exact head passes.
|
||||||
|
7. **Merge into `next`** happens only after CI green + review pass, pinned to
|
||||||
|
the reviewed head SHA (a post-review push voids the review).
|
||||||
|
8. **Promotion `next` → `main`** is a deliberate, Jason-owned reconciliation
|
||||||
|
merge — not part of any contribution's lifecycle. Contributors are done at
|
||||||
|
step 7.
|
||||||
|
|
||||||
|
### Responsibilities
|
||||||
|
|
||||||
|
- **Contributor** — base pinning, green CI, evidence in the PR body,
|
||||||
|
responding to AMEND verdicts, never merging own work.
|
||||||
|
- **Reviewer / merge gate** — independent verification on the exact head;
|
||||||
|
holds and lifts gates; executes the merge into `next`.
|
||||||
|
- **Orchestrator / adjudicator** — cross-PR sequencing, disposition when PRs
|
||||||
|
collide, conflict adjudication.
|
||||||
|
- **Jason** — `next` → `main` promotions, merge-authority grants, collaborator
|
||||||
|
and token provisioning. Agents cannot grant themselves or each other any of
|
||||||
|
these.
|
||||||
|
|
||||||
|
### Hotfixes and divergence
|
||||||
|
|
||||||
|
- A hotfix follows the same path: branch from `next`, PR to `next`, gates,
|
||||||
|
merge, then an expedited Jason-owned promotion if `main` needs it urgently.
|
||||||
|
Committing the fix to `main` directly is prohibited even under pressure.
|
||||||
|
- **Never land work on `main` that is not on `next`.** This has happened
|
||||||
|
(issue #1152's goal controller reached `main` without reaching `next`) and
|
||||||
|
every later PR paid for it. If it happens anyway: transplant the work onto
|
||||||
|
a `next`-based branch with provenance-preserving commits
|
||||||
|
(`git cherry-pick -x` or explicit SHA references in the messages), PR it
|
||||||
|
through the normal gates, and let promotion re-align `main`. Do not
|
||||||
|
hand-patch `main` to compensate.
|
||||||
|
- Force-pushing a branch you do not own is prohibited; rebasing your own PR
|
||||||
|
branch is fine before review, and voids any review already given.
|
||||||
|
|
||||||
## Database and Local Runtime Safety
|
## Database and Local Runtime Safety
|
||||||
|
|
||||||
- Current local data-layer work uses in-process PGlite; leave `DATABASE_URL` unset.
|
- Current local data-layer work uses in-process PGlite; leave `DATABASE_URL` unset.
|
||||||
|
|||||||
@@ -74,6 +74,14 @@ The launcher verifies your config, checks for `SOUL.md`, injects your `AGENTS.md
|
|||||||
|
|
||||||
Pi launches default to a token-lean skill posture: `mosaic pi` passes `--no-skills` so Pi does not preload every global skill description into the system prompt. Use `MOSAIC_PI_SKILL_MODE=all mosaic pi` for the legacy all-skills catalog, or `MOSAIC_PI_SKILL_MODE=discover mosaic pi` to let Pi use its native settings/project skill discovery.
|
Pi launches default to a token-lean skill posture: `mosaic pi` passes `--no-skills` so Pi does not preload every global skill description into the system prompt. Use `MOSAIC_PI_SKILL_MODE=all mosaic pi` for the legacy all-skills catalog, or `MOSAIC_PI_SKILL_MODE=discover mosaic pi` to let Pi use its native settings/project skill discovery.
|
||||||
|
|
||||||
|
Mosaic also loads its Pi extensions from `~/.config/mosaic/runtime/pi/`. Inside Pi,
|
||||||
|
`/goal set <statement>` starts a bounded persistent loop that checks every turn and successful
|
||||||
|
compaction, requires two evidence-bearing completion reports, and can be inspected or stopped with
|
||||||
|
`/goal status`, `/goal pause`, `/goal resume`, and `/goal cancel`. Controller-owned goal-state
|
||||||
|
entries redact common credential shapes, but Pi's model/tool-call history is separate, so goals and
|
||||||
|
evidence must never contain secrets or raw sensitive output. Mosaic does not install this extension
|
||||||
|
into `~/.pi/agent/extensions/`.
|
||||||
|
|
||||||
### TUI & Gateway
|
### TUI & Gateway
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
@@ -331,7 +339,7 @@ The framework is the bash-based standards layer installed to every developer mac
|
|||||||
├── bin/mosaic ← Unified launcher (claude, codex, opencode, pi, yolo)
|
├── bin/mosaic ← Unified launcher (claude, codex, opencode, pi, yolo)
|
||||||
├── guides/ ← E2E delivery, orchestrator protocol, PRD, etc.
|
├── guides/ ← E2E delivery, orchestrator protocol, PRD, etc.
|
||||||
├── runtime/ ← Per-runtime configs (claude/, codex/, opencode/, pi/)
|
├── runtime/ ← Per-runtime configs (claude/, codex/, opencode/, pi/)
|
||||||
├── skills/ ← Universal skills (synced from agent-skills repo)
|
├── skills/ ← Universal skills (shipped with the framework package)
|
||||||
├── tools/ ← Tool suites (orchestrator, git, quality, prdy, etc.)
|
├── tools/ ← Tool suites (orchestrator, git, quality, prdy, etc.)
|
||||||
└── memory/ ← Persistent agent memory (preserved across upgrades)
|
└── memory/ ← Persistent agent memory (preserved across upgrades)
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -0,0 +1,332 @@
|
|||||||
|
import { type Type } from '@nestjs/common';
|
||||||
|
import { Test, type TestingModule } from '@nestjs/testing';
|
||||||
|
import type { SlashCommandPayload } from '@mosaicstack/types';
|
||||||
|
import { describe, expect, it, vi } from 'vitest';
|
||||||
|
import { AgentService, type AgentSession } from '../agent/agent.service.js';
|
||||||
|
import { ProviderService } from '../agent/provider.service.js';
|
||||||
|
import { AppModule } from '../app.module.js';
|
||||||
|
import { CommandAuthorizationService } from '../commands/command-authorization.service.js';
|
||||||
|
import { CommandExecutorService } from '../commands/command-executor.service.js';
|
||||||
|
import { CommandsModule } from '../commands/commands.module.js';
|
||||||
|
import { CommandRuntimeApprovalVerifier } from '../commands/runtime-approval-verifier.js';
|
||||||
|
import { PreferencesModule } from '../preferences/preferences.module.js';
|
||||||
|
import { SystemOverrideService } from '../preferences/system-override.service.js';
|
||||||
|
|
||||||
|
const fakeDb = {
|
||||||
|
$client: { exec: async (): Promise<void> => {} },
|
||||||
|
execute: async (): Promise<{ rows: unknown[] }> => ({ rows: [] }),
|
||||||
|
select: () => ({
|
||||||
|
from: () => ({
|
||||||
|
where: async (): Promise<Array<{ count: number }>> => [{ count: 1 }],
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
insert: () => ({ values: async (): Promise<void> => {} }),
|
||||||
|
};
|
||||||
|
|
||||||
|
const fakeProviderService = {
|
||||||
|
onModuleInit: async (): Promise<void> => {},
|
||||||
|
onModuleDestroy: (): void => {},
|
||||||
|
getRegistry: () => ({ getAvailable: () => [], getAll: () => [], find: () => undefined }),
|
||||||
|
getDefaultModel: () => undefined,
|
||||||
|
listAvailableModels: () => [],
|
||||||
|
listProviders: () => [],
|
||||||
|
getAdapter: () => undefined,
|
||||||
|
getProvidersHealth: () => [],
|
||||||
|
};
|
||||||
|
|
||||||
|
function compileRealAppGraph(): Promise<TestingModule> {
|
||||||
|
return Test.createTestingModule({ imports: [AppModule] })
|
||||||
|
.overrideProvider('DB_HANDLE')
|
||||||
|
.useValue({ db: fakeDb, close: async (): Promise<void> => {} })
|
||||||
|
.overrideProvider('DB')
|
||||||
|
.useValue(fakeDb)
|
||||||
|
.overrideProvider('STORAGE_ADAPTER')
|
||||||
|
.useValue({
|
||||||
|
name: 'required-security-wiring-test',
|
||||||
|
migrate: async (): Promise<void> => {},
|
||||||
|
close: async (): Promise<void> => {},
|
||||||
|
})
|
||||||
|
.overrideProvider('AUTH')
|
||||||
|
.useValue({})
|
||||||
|
.overrideProvider('BRAIN')
|
||||||
|
.useValue({ conversations: {}, agents: {} })
|
||||||
|
.overrideProvider('LOG_SERVICE')
|
||||||
|
.useValue({})
|
||||||
|
.overrideProvider('MEMORY')
|
||||||
|
.useValue({})
|
||||||
|
.overrideProvider('MEMORY_ADAPTER')
|
||||||
|
.useValue({})
|
||||||
|
.overrideProvider(ProviderService)
|
||||||
|
.useValue(fakeProviderService)
|
||||||
|
.compile();
|
||||||
|
}
|
||||||
|
|
||||||
|
function providerToken(provider: unknown): unknown {
|
||||||
|
return typeof provider === 'function' ? provider : (provider as { provide?: unknown })?.provide;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface MaskingConsumer {
|
||||||
|
moduleType: Type<unknown>;
|
||||||
|
token: Type<unknown>;
|
||||||
|
useValue: object;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function compileWithoutProvider(
|
||||||
|
moduleType: Type<unknown>,
|
||||||
|
missingToken: Type<unknown>,
|
||||||
|
maskingConsumer: MaskingConsumer,
|
||||||
|
): Promise<{ error: unknown; moduleRef: TestingModule | undefined }> {
|
||||||
|
const touchedModules = new Set([moduleType, maskingConsumer.moduleType]);
|
||||||
|
const originals = Array.from(touchedModules, (touchedModule: Type<unknown>) => ({
|
||||||
|
moduleType: touchedModule,
|
||||||
|
providers: (Reflect.getMetadata('providers', touchedModule) ?? []) as unknown[],
|
||||||
|
exports: (Reflect.getMetadata('exports', touchedModule) ?? []) as unknown[],
|
||||||
|
}));
|
||||||
|
|
||||||
|
for (const original of originals) {
|
||||||
|
const providers = original.providers.flatMap((provider: unknown): unknown[] => {
|
||||||
|
const token = providerToken(provider);
|
||||||
|
if (original.moduleType === moduleType && token === missingToken) return [];
|
||||||
|
if (original.moduleType === maskingConsumer.moduleType && token === maskingConsumer.token) {
|
||||||
|
return [{ provide: maskingConsumer.token, useValue: maskingConsumer.useValue }];
|
||||||
|
}
|
||||||
|
return [provider];
|
||||||
|
});
|
||||||
|
const exports = original.exports.filter(
|
||||||
|
(exported: unknown): boolean =>
|
||||||
|
original.moduleType !== moduleType || providerToken(exported) !== missingToken,
|
||||||
|
);
|
||||||
|
Reflect.defineMetadata('providers', providers, original.moduleType);
|
||||||
|
Reflect.defineMetadata('exports', exports, original.moduleType);
|
||||||
|
}
|
||||||
|
|
||||||
|
let moduleRef: TestingModule | undefined;
|
||||||
|
let error: unknown;
|
||||||
|
try {
|
||||||
|
moduleRef = await compileRealAppGraph();
|
||||||
|
} catch (caught: unknown) {
|
||||||
|
error = caught;
|
||||||
|
} finally {
|
||||||
|
for (const original of originals) {
|
||||||
|
Reflect.defineMetadata('providers', original.providers, original.moduleType);
|
||||||
|
Reflect.defineMetadata('exports', original.exports, original.moduleType);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { error, moduleRef };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function closeIfCompiled(moduleRef: TestingModule | undefined): Promise<void> {
|
||||||
|
if (moduleRef) await moduleRef.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('required security wiring — real AppModule startup refusal', () => {
|
||||||
|
it('FL-01 positive control: the real graph compiles when CommandAuthorizationService is bound', async () => {
|
||||||
|
const moduleRef = await compileRealAppGraph();
|
||||||
|
try {
|
||||||
|
expect(moduleRef.get(CommandAuthorizationService, { strict: false })).toBeInstanceOf(
|
||||||
|
CommandAuthorizationService,
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
await moduleRef.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('FL-01 negative control: absence read as permission is refused at module compilation', async () => {
|
||||||
|
const { error, moduleRef } = await compileWithoutProvider(
|
||||||
|
CommandsModule,
|
||||||
|
CommandAuthorizationService,
|
||||||
|
{
|
||||||
|
moduleType: CommandsModule,
|
||||||
|
token: CommandRuntimeApprovalVerifier,
|
||||||
|
useValue: {},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
await closeIfCompiled(moduleRef);
|
||||||
|
|
||||||
|
expect(
|
||||||
|
error,
|
||||||
|
'absence read as permission: AppModule compilation accepted a missing CommandAuthorizationService binding',
|
||||||
|
).toBeInstanceOf(Error);
|
||||||
|
if (!(error instanceof Error)) return;
|
||||||
|
expect(error.message).toContain('CommandExecutorService');
|
||||||
|
expect(error.message).toContain('CommandAuthorizationService');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('FL-11 positive control: the real graph compiles when SystemOverrideService is bound', async () => {
|
||||||
|
const moduleRef = await compileRealAppGraph();
|
||||||
|
try {
|
||||||
|
expect(moduleRef.get(SystemOverrideService, { strict: false })).toBeInstanceOf(
|
||||||
|
SystemOverrideService,
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
await moduleRef.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('FL-11 negative control: absence read as permission is refused at module compilation', async () => {
|
||||||
|
const { error, moduleRef } = await compileWithoutProvider(
|
||||||
|
PreferencesModule,
|
||||||
|
SystemOverrideService,
|
||||||
|
{
|
||||||
|
moduleType: CommandsModule,
|
||||||
|
token: CommandExecutorService,
|
||||||
|
useValue: {},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
await closeIfCompiled(moduleRef);
|
||||||
|
|
||||||
|
expect(
|
||||||
|
error,
|
||||||
|
'absence read as permission: AppModule compilation accepted a missing SystemOverrideService binding',
|
||||||
|
).toBeInstanceOf(Error);
|
||||||
|
if (!(error instanceof Error)) return;
|
||||||
|
expect(error.message).toContain('AgentService');
|
||||||
|
expect(error.message).toContain('SystemOverrideService');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const actorScope = { userId: 'security-user', tenantId: 'security-tenant' };
|
||||||
|
const conversationId = 'security-conversation';
|
||||||
|
|
||||||
|
function directExecutorWithoutAuthorization(systemOverrideSet: ReturnType<typeof vi.fn>) {
|
||||||
|
const registry = {
|
||||||
|
getManifest: vi.fn(() => ({
|
||||||
|
version: 1,
|
||||||
|
commands: [
|
||||||
|
{
|
||||||
|
name: 'system',
|
||||||
|
aliases: [],
|
||||||
|
description: 'Set instruction authority',
|
||||||
|
scope: 'agent' as const,
|
||||||
|
execution: 'socket' as const,
|
||||||
|
available: true,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
skills: [],
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
return new CommandExecutorService(
|
||||||
|
registry as never,
|
||||||
|
{ getSession: vi.fn() } as never,
|
||||||
|
{ set: systemOverrideSet, clear: vi.fn() } as never,
|
||||||
|
{ collect: vi.fn() } as never,
|
||||||
|
null,
|
||||||
|
{ agents: {} } as never,
|
||||||
|
null,
|
||||||
|
null,
|
||||||
|
{ getServerStatuses: vi.fn(() => []), getToolDefinitions: vi.fn(() => []) } as never,
|
||||||
|
undefined as never,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function directAgentWithoutSystemOverride(piPrompt: ReturnType<typeof vi.fn>): {
|
||||||
|
service: AgentService;
|
||||||
|
session: AgentSession;
|
||||||
|
} {
|
||||||
|
const service = new AgentService(
|
||||||
|
{
|
||||||
|
getDefaultModel: vi.fn(() => null),
|
||||||
|
getRegistry: vi.fn(() => ({})),
|
||||||
|
findModel: vi.fn(),
|
||||||
|
listAvailableModels: vi.fn(() => []),
|
||||||
|
} as never,
|
||||||
|
{} as never,
|
||||||
|
{} as never,
|
||||||
|
{ available: false } as never,
|
||||||
|
{} as never,
|
||||||
|
{ getToolDefinitions: vi.fn(() => []) } as never,
|
||||||
|
{ loadForSession: vi.fn(async () => ({ metaTools: [], promptAdditions: [] })) } as never,
|
||||||
|
undefined as never,
|
||||||
|
null,
|
||||||
|
{ collect: vi.fn().mockResolvedValue(undefined) } as never,
|
||||||
|
null,
|
||||||
|
);
|
||||||
|
const session = {
|
||||||
|
id: conversationId,
|
||||||
|
provider: 'test-provider',
|
||||||
|
modelId: 'test-model',
|
||||||
|
piSession: { prompt: piPrompt },
|
||||||
|
listeners: new Set(),
|
||||||
|
unsubscribe: vi.fn(),
|
||||||
|
createdAt: Date.now(),
|
||||||
|
promptCount: 0,
|
||||||
|
channels: new Set(),
|
||||||
|
skillPromptAdditions: [],
|
||||||
|
sandboxDir: process.cwd(),
|
||||||
|
allowedTools: null,
|
||||||
|
userId: actorScope.userId,
|
||||||
|
tenantId: actorScope.tenantId,
|
||||||
|
metrics: {
|
||||||
|
tokens: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
||||||
|
modelSwitches: 0,
|
||||||
|
messageCount: 0,
|
||||||
|
lastActivityAt: new Date(0).toISOString(),
|
||||||
|
},
|
||||||
|
} as unknown as AgentSession;
|
||||||
|
const internals = service as unknown as { sessions: Map<string, AgentSession> };
|
||||||
|
internals.sessions.set(conversationId, session);
|
||||||
|
return { service, session };
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('required security wiring — malformed direct absence has zero effects', () => {
|
||||||
|
it('FL-01 refuses command execution before any command effect when authorization is absent', async () => {
|
||||||
|
const systemOverrideSet = vi.fn().mockResolvedValue(undefined);
|
||||||
|
const executor = directExecutorWithoutAuthorization(systemOverrideSet);
|
||||||
|
const payload: SlashCommandPayload = {
|
||||||
|
command: 'system',
|
||||||
|
args: 'authority that must not be stored',
|
||||||
|
conversationId,
|
||||||
|
};
|
||||||
|
let error: unknown;
|
||||||
|
|
||||||
|
try {
|
||||||
|
await executor.execute(payload, actorScope);
|
||||||
|
} catch (caught: unknown) {
|
||||||
|
error = caught;
|
||||||
|
}
|
||||||
|
|
||||||
|
expect
|
||||||
|
.soft(
|
||||||
|
error,
|
||||||
|
'absence read as permission: direct executor accepted missing command authorization',
|
||||||
|
)
|
||||||
|
.toBeInstanceOf(Error);
|
||||||
|
expect
|
||||||
|
.soft(
|
||||||
|
systemOverrideSet,
|
||||||
|
'absence read as permission: command effect occurred without command authorization',
|
||||||
|
)
|
||||||
|
.not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('FL-11 refuses prompt execution before any provider or session effect when system override authority is absent', async () => {
|
||||||
|
const piPrompt = vi.fn().mockResolvedValue(undefined);
|
||||||
|
const { service, session } = directAgentWithoutSystemOverride(piPrompt);
|
||||||
|
let error: unknown;
|
||||||
|
|
||||||
|
try {
|
||||||
|
await service.prompt(conversationId, 'must not reach provider', actorScope);
|
||||||
|
} catch (caught: unknown) {
|
||||||
|
error = caught;
|
||||||
|
}
|
||||||
|
|
||||||
|
expect
|
||||||
|
.soft(
|
||||||
|
error,
|
||||||
|
'absence read as permission: direct session accepted missing system override authority',
|
||||||
|
)
|
||||||
|
.toBeInstanceOf(Error);
|
||||||
|
expect
|
||||||
|
.soft(
|
||||||
|
piPrompt,
|
||||||
|
'absence read as permission: provider prompt occurred without system override authority',
|
||||||
|
)
|
||||||
|
.not.toHaveBeenCalled();
|
||||||
|
expect
|
||||||
|
.soft(
|
||||||
|
session.promptCount,
|
||||||
|
'absence read as permission: session state changed without system override authority',
|
||||||
|
)
|
||||||
|
.toBe(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -26,7 +26,7 @@ function makeService(operatorMemory: unknown = null): AgentService {
|
|||||||
{} as never,
|
{} as never,
|
||||||
{ getToolDefinitions: vi.fn(() => []) } as never,
|
{ getToolDefinitions: vi.fn(() => []) } as never,
|
||||||
{ loadForSession: vi.fn(async () => ({ metaTools: [], promptAdditions: [] })) } as never,
|
{ loadForSession: vi.fn(async () => ({ metaTools: [], promptAdditions: [] })) } as never,
|
||||||
null,
|
{ get: vi.fn().mockResolvedValue(null), renew: vi.fn().mockResolvedValue(undefined) } as never,
|
||||||
null,
|
null,
|
||||||
{ collect: vi.fn().mockResolvedValue(undefined) } as never,
|
{ collect: vi.fn().mockResolvedValue(undefined) } as never,
|
||||||
operatorMemory as never,
|
operatorMemory as never,
|
||||||
|
|||||||
@@ -132,9 +132,8 @@ export class AgentService implements OnModuleDestroy {
|
|||||||
@Inject(CoordService) private readonly coordService: CoordService,
|
@Inject(CoordService) private readonly coordService: CoordService,
|
||||||
@Inject(McpClientService) private readonly mcpClientService: McpClientService,
|
@Inject(McpClientService) private readonly mcpClientService: McpClientService,
|
||||||
@Inject(SkillLoaderService) private readonly skillLoaderService: SkillLoaderService,
|
@Inject(SkillLoaderService) private readonly skillLoaderService: SkillLoaderService,
|
||||||
@Optional()
|
|
||||||
@Inject(SystemOverrideService)
|
@Inject(SystemOverrideService)
|
||||||
private readonly systemOverride: SystemOverrideService | null,
|
private readonly systemOverride: SystemOverrideService,
|
||||||
@Optional()
|
@Optional()
|
||||||
@Inject(PreferencesService)
|
@Inject(PreferencesService)
|
||||||
private readonly preferencesService: PreferencesService | null,
|
private readonly preferencesService: PreferencesService | null,
|
||||||
@@ -709,23 +708,22 @@ export class AgentService implements OnModuleDestroy {
|
|||||||
throw new Error(`No agent session found: ${sessionId}`);
|
throw new Error(`No agent session found: ${sessionId}`);
|
||||||
}
|
}
|
||||||
this.assertSessionScope(session, scope);
|
this.assertSessionScope(session, scope);
|
||||||
session.promptCount += 1;
|
|
||||||
|
|
||||||
// Channel attachments are untrusted URI references. Preserve exact,
|
// Channel attachments are untrusted URI references. Preserve exact,
|
||||||
// authenticated metadata for the agent without treating it as authority.
|
// authenticated metadata for the agent without treating it as authority.
|
||||||
const attachmentContext = this.attachmentContext(attachments);
|
const attachmentContext = this.attachmentContext(attachments);
|
||||||
|
|
||||||
// Prepend session-scoped system override if present (renew TTL on each turn)
|
// Prepend session-scoped system override if present (renew TTL on each turn).
|
||||||
|
// Required instruction-authority wiring is consulted before session/provider effects.
|
||||||
let effectiveMessage = `${message}${attachmentContext}`;
|
let effectiveMessage = `${message}${attachmentContext}`;
|
||||||
if (this.systemOverride) {
|
const override = await this.systemOverride.get(sessionId, scope);
|
||||||
const override = await this.systemOverride.get(sessionId, scope);
|
if (override) {
|
||||||
if (override) {
|
effectiveMessage = `[System Override]\n${override}\n\n${effectiveMessage}`;
|
||||||
effectiveMessage = `[System Override]\n${override}\n\n${effectiveMessage}`;
|
await this.systemOverride.renew(sessionId, scope);
|
||||||
await this.systemOverride.renew(sessionId, scope);
|
this.logger.debug(`Applied system override for session ${sessionId}`);
|
||||||
this.logger.debug(`Applied system override for session ${sessionId}`);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
session.promptCount += 1;
|
||||||
try {
|
try {
|
||||||
await session.piSession.prompt(effectiveMessage);
|
await session.piSession.prompt(effectiveMessage);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
|||||||
@@ -80,6 +80,10 @@ const mockMcpClient = {
|
|||||||
getToolDefinitions: vi.fn(() => []),
|
getToolDefinitions: vi.fn(() => []),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const allowAuthorization = {
|
||||||
|
authorize: vi.fn().mockResolvedValue({ allowed: true }),
|
||||||
|
};
|
||||||
|
|
||||||
function buildService(
|
function buildService(
|
||||||
redis: typeof mockRedis | null = mockRedis,
|
redis: typeof mockRedis | null = mockRedis,
|
||||||
mcpClient: {
|
mcpClient: {
|
||||||
@@ -98,6 +102,7 @@ function buildService(
|
|||||||
null,
|
null,
|
||||||
mockChatGateway as never,
|
mockChatGateway as never,
|
||||||
mcpClient as never,
|
mcpClient as never,
|
||||||
|
allowAuthorization as never,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -35,9 +35,8 @@ export class CommandExecutorService {
|
|||||||
@Inject(forwardRef(() => ChatGateway))
|
@Inject(forwardRef(() => ChatGateway))
|
||||||
private readonly chatGateway: ChatGateway | null,
|
private readonly chatGateway: ChatGateway | null,
|
||||||
@Inject(McpClientService) private readonly mcpClient: McpClientService,
|
@Inject(McpClientService) private readonly mcpClient: McpClientService,
|
||||||
@Optional()
|
|
||||||
@Inject(CommandAuthorizationService)
|
@Inject(CommandAuthorizationService)
|
||||||
private readonly authorization: CommandAuthorizationService | null = null,
|
private readonly authorization: CommandAuthorizationService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async execute(
|
async execute(
|
||||||
@@ -57,13 +56,13 @@ export class CommandExecutorService {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const authorization = await this.authorization?.authorize(
|
const authorization = await this.authorization.authorize(
|
||||||
def,
|
def,
|
||||||
payload,
|
payload,
|
||||||
userId,
|
userId,
|
||||||
payload.approvalId,
|
payload.approvalId,
|
||||||
);
|
);
|
||||||
if (authorization && !authorization.allowed) {
|
if (!authorization.allowed) {
|
||||||
return { command, conversationId, success: false, message: authorization.reason };
|
return { command, conversationId, success: false, message: authorization.reason };
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -171,7 +170,7 @@ export class CommandExecutorService {
|
|||||||
const def = this.registry
|
const def = this.registry
|
||||||
.getManifest()
|
.getManifest()
|
||||||
.commands.find((command) => command.name === payload.command);
|
.commands.find((command) => command.name === payload.command);
|
||||||
if (!def || !this.authorization) return null;
|
if (!def) return null;
|
||||||
return this.authorization.createApproval(def, payload, scope.userId);
|
return this.authorization.createApproval(def, payload, scope.userId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -55,6 +55,10 @@ const mockMcpClient = {
|
|||||||
reconnectServer: vi.fn().mockResolvedValue(undefined),
|
reconnectServer: vi.fn().mockResolvedValue(undefined),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const allowAuthorization = {
|
||||||
|
authorize: vi.fn().mockResolvedValue({ allowed: true }),
|
||||||
|
};
|
||||||
|
|
||||||
// ─── Helpers ─────────────────────────────────────────────────────────────────
|
// ─── Helpers ─────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
function buildRegistry(): CommandRegistryService {
|
function buildRegistry(): CommandRegistryService {
|
||||||
@@ -74,6 +78,7 @@ function buildExecutor(registry: CommandRegistryService): CommandExecutorService
|
|||||||
null, // reloadService (optional)
|
null, // reloadService (optional)
|
||||||
null, // chatGateway (optional)
|
null, // chatGateway (optional)
|
||||||
mockMcpClient as never,
|
mockMcpClient as never,
|
||||||
|
allowAuthorization as never,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -245,9 +245,21 @@ describe('EnrollmentService.createToken', () => {
|
|||||||
const after = Date.now();
|
const after = Date.now();
|
||||||
|
|
||||||
const expiresMs = new Date(result.expiresAt).getTime();
|
const expiresMs = new Date(result.expiresAt).getTime();
|
||||||
// Should be at most 900s from now
|
|
||||||
expect(expiresMs - before).toBeLessThanOrEqual(900_000 + 100);
|
// The property under test is CLAMPING: a 9999s request must come back as 900s.
|
||||||
|
// The gap between clamped and unclamped is 9_099_000 ms, so the tolerance below
|
||||||
|
// only has to exceed CI scheduling jitter — it does not need to be tight to keep
|
||||||
|
// the assertion discriminating. A 5s allowance consumes 0.05% of that margin and
|
||||||
|
// an unclamped result still misses by three orders of magnitude.
|
||||||
|
//
|
||||||
|
// It was 100ms and failed on a loaded agent at 900_106 — 6ms over (#1090). A
|
||||||
|
// wall-clock budget sized to a fast machine is a flake, not a tighter test.
|
||||||
|
const CI_JITTER_MS = 5_000;
|
||||||
|
expect(expiresMs - before).toBeLessThanOrEqual(900_000 + CI_JITTER_MS);
|
||||||
expect(expiresMs - after).toBeGreaterThanOrEqual(0);
|
expect(expiresMs - after).toBeGreaterThanOrEqual(0);
|
||||||
|
// Explicitly pin the clamp itself, independent of any timing allowance:
|
||||||
|
// unclamped (9999s) would exceed this by ~9_099_000 ms.
|
||||||
|
expect(expiresMs - before).toBeLessThan(1_000_000);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -159,6 +159,7 @@ describe('ReloadService — /reload command sanitizes plugin errors', () => {
|
|||||||
reloadService,
|
reloadService,
|
||||||
mockChatGateway as never,
|
mockChatGateway as never,
|
||||||
mockMcpClient as never,
|
mockMcpClient as never,
|
||||||
|
{ authorize: vi.fn().mockResolvedValue({ allowed: true }) } as never,
|
||||||
);
|
);
|
||||||
|
|
||||||
const payload: SlashCommandPayload = { command: 'reload', conversationId: 'conv-1' };
|
const payload: SlashCommandPayload = { command: 'reload', conversationId: 'conv-1' };
|
||||||
|
|||||||
@@ -0,0 +1,110 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import type { ReactElement } from 'react';
|
||||||
|
import { formatAge, type FreshnessLabel } from '@/lib/freshness/model';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Rendering rules for non-current freshness states (RI-5-001).
|
||||||
|
*
|
||||||
|
* - `unavailable` renders an explicit failure panel — never an empty
|
||||||
|
* healthy collection.
|
||||||
|
* - `stale` may render last-known data, but only under a visible label
|
||||||
|
* carrying source identity, snapshot version, and age.
|
||||||
|
* - `partial` renders the verified parts plus an explicit list of what is
|
||||||
|
* missing.
|
||||||
|
*/
|
||||||
|
|
||||||
|
interface RetryableNoticeProps {
|
||||||
|
readonly onRetry?: () => void;
|
||||||
|
readonly retryLabel?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
function RetryButton({ onRetry, retryLabel }: RetryableNoticeProps): ReactElement | null {
|
||||||
|
if (!onRetry) return null;
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={onRetry}
|
||||||
|
className="mt-2 rounded-lg border border-surface-border px-3 py-1.5 text-xs transition-colors hover:border-gray-500"
|
||||||
|
>
|
||||||
|
{retryLabel ?? 'Retry'}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UnavailableDataNoticeProps extends RetryableNoticeProps {
|
||||||
|
/** What is unavailable, e.g. "Tasks". */
|
||||||
|
readonly title: string;
|
||||||
|
/** Optional underlying failure detail (network message, invalidation reason). */
|
||||||
|
readonly detail?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Explicit `unavailable` state. Never renders as an empty healthy collection. */
|
||||||
|
export function UnavailableDataNotice({
|
||||||
|
title,
|
||||||
|
detail,
|
||||||
|
onRetry,
|
||||||
|
retryLabel,
|
||||||
|
}: UnavailableDataNoticeProps): ReactElement {
|
||||||
|
return (
|
||||||
|
<div role="alert" className="rounded-lg border border-error/40 px-4 py-3 text-sm">
|
||||||
|
<p className="font-medium text-text-primary">{title} are unavailable</p>
|
||||||
|
<p className="mt-1 text-text-muted">
|
||||||
|
This is not an empty result — the data could not be verified from the gateway.
|
||||||
|
{detail ? ` ${detail}` : ''}
|
||||||
|
</p>
|
||||||
|
<RetryButton onRetry={onRetry} retryLabel={retryLabel} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface StaleDataNoticeProps extends RetryableNoticeProps {
|
||||||
|
/** Provenance of the last-known snapshot being displayed. */
|
||||||
|
readonly label: FreshnessLabel;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Situational-awareness banner for `stale` data: last-known data may render,
|
||||||
|
* but visibly labeled with source identity, snapshot version, and age.
|
||||||
|
*/
|
||||||
|
export function StaleDataNotice({
|
||||||
|
label,
|
||||||
|
onRetry,
|
||||||
|
retryLabel,
|
||||||
|
}: StaleDataNoticeProps): ReactElement {
|
||||||
|
return (
|
||||||
|
<div role="status" className="rounded-lg border border-warning/40 px-4 py-3 text-sm">
|
||||||
|
<p className="font-medium text-warning">Showing last-known data — it may be out of date</p>
|
||||||
|
<p className="mt-1 text-xs text-text-muted">
|
||||||
|
Source {label.source} · snapshot v{label.version} · fetched{' '}
|
||||||
|
{formatAge(label.fetchedAt, Date.now())}. Verdicts derived from this data are unknown and
|
||||||
|
changes are disabled until it is revalidated.
|
||||||
|
</p>
|
||||||
|
<RetryButton onRetry={onRetry} retryLabel={retryLabel ?? 'Revalidate'} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PartialDataNoticeProps extends RetryableNoticeProps {
|
||||||
|
/** Display names of the sections whose collections are unavailable. */
|
||||||
|
readonly missing: readonly string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `partial` surface banner: verified parts render, missing parts are explicit. */
|
||||||
|
export function PartialDataNotice({
|
||||||
|
missing,
|
||||||
|
onRetry,
|
||||||
|
retryLabel,
|
||||||
|
}: PartialDataNoticeProps): ReactElement {
|
||||||
|
return (
|
||||||
|
<div role="status" className="rounded-lg border border-warning/40 px-4 py-3 text-sm">
|
||||||
|
<p className="font-medium text-warning">Some data could not be loaded</p>
|
||||||
|
<p className="mt-1 text-xs text-text-muted">
|
||||||
|
{missing.join(', ')} {missing.length === 1 ? 'is' : 'are'} unavailable — sections below show
|
||||||
|
an explicit unavailable state instead of an empty list. Derived verdicts remain unknown
|
||||||
|
until every collection is revalidated.
|
||||||
|
</p>
|
||||||
|
<RetryButton onRetry={onRetry} retryLabel={retryLabel ?? 'Revalidate'} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,324 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import type { Task } from '@/lib/types';
|
||||||
|
import {
|
||||||
|
acceptSnapshot,
|
||||||
|
assertMutable,
|
||||||
|
canMutate,
|
||||||
|
combineFreshness,
|
||||||
|
computeDigest,
|
||||||
|
computeFreshness,
|
||||||
|
DEFAULT_FRESHNESS_POLICY,
|
||||||
|
formatAge,
|
||||||
|
type FreshSnapshot,
|
||||||
|
invalidationReasonLabels,
|
||||||
|
StaleMutationError,
|
||||||
|
UNKNOWN_VERDICT,
|
||||||
|
verdictValue,
|
||||||
|
} from './model';
|
||||||
|
import { validateProjectCollection, validateTaskCollection } from './validators';
|
||||||
|
|
||||||
|
const NOW = 1_800_000_000_000;
|
||||||
|
|
||||||
|
const policy = { ...DEFAULT_FRESHNESS_POLICY, staleAfterMs: 60_000 };
|
||||||
|
|
||||||
|
const taskPayload: Task[] = [
|
||||||
|
{
|
||||||
|
id: 'task-1',
|
||||||
|
title: 'T1',
|
||||||
|
description: null,
|
||||||
|
status: 'not-started',
|
||||||
|
priority: 'high',
|
||||||
|
projectId: 'project-1',
|
||||||
|
missionId: null,
|
||||||
|
assignee: null,
|
||||||
|
tags: null,
|
||||||
|
dueDate: null,
|
||||||
|
metadata: null,
|
||||||
|
createdAt: '2026-08-01T00:00:00.000Z',
|
||||||
|
updatedAt: '2026-08-01T00:00:00.000Z',
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
function acceptedTaskSnapshot(
|
||||||
|
overrides: Partial<FreshSnapshot<typeof taskPayload>> = {},
|
||||||
|
): FreshSnapshot<typeof taskPayload> {
|
||||||
|
const result = acceptSnapshot({
|
||||||
|
value: taskPayload,
|
||||||
|
validate: validateTaskCollection,
|
||||||
|
previous: null,
|
||||||
|
policy,
|
||||||
|
source: 'gateway:/api/tasks',
|
||||||
|
now: NOW,
|
||||||
|
});
|
||||||
|
if (result.outcome !== 'accepted') {
|
||||||
|
throw new Error(`fixture setup failed: ${result.reason}`);
|
||||||
|
}
|
||||||
|
return { ...result.snapshot, ...overrides };
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('computeFreshness', () => {
|
||||||
|
it('treats a missing snapshot as unavailable, never as an empty healthy collection', () => {
|
||||||
|
expect(computeFreshness({ snapshot: null, policy, now: NOW })).toBe('unavailable');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns current for a fresh verified snapshot regardless of data emptiness', () => {
|
||||||
|
const empty = acceptSnapshot({
|
||||||
|
value: [],
|
||||||
|
validate: validateTaskCollection,
|
||||||
|
previous: null,
|
||||||
|
policy,
|
||||||
|
source: 'gateway:/api/tasks',
|
||||||
|
now: NOW,
|
||||||
|
});
|
||||||
|
if (empty.outcome !== 'accepted') throw new Error('expected acceptance');
|
||||||
|
expect(computeFreshness({ snapshot: empty.snapshot, policy, now: NOW })).toBe('current');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('degrades to stale once the snapshot ages past staleAfterMs', () => {
|
||||||
|
const snapshot = acceptedTaskSnapshot();
|
||||||
|
expect(computeFreshness({ snapshot, policy, now: NOW + 60_001 })).toBe('stale');
|
||||||
|
expect(computeFreshness({ snapshot, policy, now: NOW + 59_999 })).toBe('current');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('degrades to stale when the latest revalidation failed', () => {
|
||||||
|
const snapshot = acceptedTaskSnapshot();
|
||||||
|
expect(computeFreshness({ snapshot, policy, now: NOW, degraded: true })).toBe('stale');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('mutation guard', () => {
|
||||||
|
it('permits mutations only on current data', () => {
|
||||||
|
expect(canMutate('current')).toBe(true);
|
||||||
|
for (const state of ['stale', 'partial', 'unknown', 'unavailable'] as const) {
|
||||||
|
expect(canMutate(state)).toBe(false);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('refuses mutations on non-current data via assertMutable', () => {
|
||||||
|
expect(() => assertMutable('current')).not.toThrow();
|
||||||
|
for (const state of ['stale', 'partial', 'unknown', 'unavailable'] as const) {
|
||||||
|
let thrown: unknown;
|
||||||
|
try {
|
||||||
|
assertMutable(state);
|
||||||
|
} catch (caught) {
|
||||||
|
thrown = caught;
|
||||||
|
}
|
||||||
|
expect(thrown).toBeInstanceOf(StaleMutationError);
|
||||||
|
expect(thrown).toBeInstanceOf(Error);
|
||||||
|
if (thrown instanceof StaleMutationError) {
|
||||||
|
expect(thrown.name).toBe('StaleMutationError');
|
||||||
|
expect(thrown.freshness).toBe(state);
|
||||||
|
expect(thrown.message).toContain(state);
|
||||||
|
expect(thrown.message).toContain('revalidat');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('acceptSnapshot', () => {
|
||||||
|
it('accepts a valid payload with provenance', () => {
|
||||||
|
const result = acceptSnapshot({
|
||||||
|
value: taskPayload,
|
||||||
|
validate: validateTaskCollection,
|
||||||
|
previous: null,
|
||||||
|
policy,
|
||||||
|
source: 'gateway:/api/tasks',
|
||||||
|
now: NOW,
|
||||||
|
});
|
||||||
|
expect(result.outcome).toBe('accepted');
|
||||||
|
if (result.outcome !== 'accepted') return;
|
||||||
|
expect(result.snapshot.source).toBe('gateway:/api/tasks');
|
||||||
|
expect(result.snapshot.version).toBe(1);
|
||||||
|
expect(result.snapshot.fetchedAt).toBe(NOW);
|
||||||
|
expect(result.snapshot.data).toEqual(taskPayload);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('invalidates a schema-mismatched payload instead of rendering it', () => {
|
||||||
|
const result = acceptSnapshot({
|
||||||
|
value: { not: 'an array' },
|
||||||
|
validate: validateTaskCollection,
|
||||||
|
previous: acceptedTaskSnapshot(),
|
||||||
|
policy,
|
||||||
|
source: 'gateway:/api/tasks',
|
||||||
|
now: NOW,
|
||||||
|
});
|
||||||
|
expect(result).toEqual({ outcome: 'invalidated', reason: 'schema-mismatch' });
|
||||||
|
expect(invalidationReasonLabels['schema-mismatch']).toContain('schema');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('invalidates cross-workspace payloads', () => {
|
||||||
|
const userOne = acceptSnapshot({
|
||||||
|
value: [
|
||||||
|
{
|
||||||
|
id: 'p1',
|
||||||
|
name: 'P1',
|
||||||
|
description: null,
|
||||||
|
status: 'active',
|
||||||
|
userId: 'user-1',
|
||||||
|
metadata: null,
|
||||||
|
createdAt: '2026-08-01T00:00:00.000Z',
|
||||||
|
updatedAt: '2026-08-01T00:00:00.000Z',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
validate: validateProjectCollection,
|
||||||
|
previous: null,
|
||||||
|
policy,
|
||||||
|
source: 'gateway:/api/projects',
|
||||||
|
now: NOW,
|
||||||
|
});
|
||||||
|
if (userOne.outcome !== 'accepted') throw new Error('expected acceptance');
|
||||||
|
|
||||||
|
const switched = acceptSnapshot({
|
||||||
|
value: [
|
||||||
|
{
|
||||||
|
id: 'p9',
|
||||||
|
name: 'P9',
|
||||||
|
description: null,
|
||||||
|
status: 'active',
|
||||||
|
userId: 'user-2',
|
||||||
|
metadata: null,
|
||||||
|
createdAt: '2026-08-01T00:00:00.000Z',
|
||||||
|
updatedAt: '2026-08-01T00:00:00.000Z',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
validate: validateProjectCollection,
|
||||||
|
previous: userOne.snapshot,
|
||||||
|
policy,
|
||||||
|
source: 'gateway:/api/projects',
|
||||||
|
now: NOW,
|
||||||
|
});
|
||||||
|
expect(switched).toEqual({ outcome: 'invalidated', reason: 'cross-workspace' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps the previous workspace for collections with no intrinsic identity', () => {
|
||||||
|
const userOne = acceptSnapshot({
|
||||||
|
value: [
|
||||||
|
{
|
||||||
|
id: 'p1',
|
||||||
|
name: 'P1',
|
||||||
|
description: null,
|
||||||
|
status: 'active',
|
||||||
|
userId: 'user-1',
|
||||||
|
metadata: null,
|
||||||
|
createdAt: '2026-08-01T00:00:00.000Z',
|
||||||
|
updatedAt: '2026-08-01T00:00:00.000Z',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
validate: validateProjectCollection,
|
||||||
|
previous: null,
|
||||||
|
policy,
|
||||||
|
source: 'gateway:/api/projects',
|
||||||
|
now: NOW,
|
||||||
|
});
|
||||||
|
if (userOne.outcome !== 'accepted') throw new Error('expected acceptance');
|
||||||
|
|
||||||
|
// Empty list after the user deleted every project: no identity to check,
|
||||||
|
// so the verified scope is retained and the empty state stays healthy.
|
||||||
|
const emptied = acceptSnapshot({
|
||||||
|
value: [],
|
||||||
|
validate: validateProjectCollection,
|
||||||
|
previous: userOne.snapshot,
|
||||||
|
policy,
|
||||||
|
source: 'gateway:/api/projects',
|
||||||
|
now: NOW,
|
||||||
|
});
|
||||||
|
expect(emptied.outcome).toBe('accepted');
|
||||||
|
if (emptied.outcome === 'accepted') {
|
||||||
|
expect(emptied.snapshot.data).toEqual([]);
|
||||||
|
expect(emptied.snapshot.workspace).toBe('user-1');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('invalidates version regressions', () => {
|
||||||
|
const previous = acceptedTaskSnapshot({ version: 7 });
|
||||||
|
const regressed = acceptSnapshot({
|
||||||
|
value: taskPayload,
|
||||||
|
validate: validateTaskCollection,
|
||||||
|
previous,
|
||||||
|
policy,
|
||||||
|
source: 'gateway:/api/tasks',
|
||||||
|
now: NOW,
|
||||||
|
incomingVersion: 3,
|
||||||
|
});
|
||||||
|
expect(regressed).toEqual({ outcome: 'invalidated', reason: 'version-regression' });
|
||||||
|
|
||||||
|
const newerSchema = acceptedTaskSnapshot({ schemaVersion: 4 });
|
||||||
|
const downgradedClient = acceptSnapshot({
|
||||||
|
value: taskPayload,
|
||||||
|
validate: validateTaskCollection,
|
||||||
|
previous: newerSchema,
|
||||||
|
policy: { ...policy, schemaVersion: 2 },
|
||||||
|
source: 'gateway:/api/tasks',
|
||||||
|
now: NOW,
|
||||||
|
});
|
||||||
|
expect(downgradedClient).toEqual({ outcome: 'invalidated', reason: 'version-regression' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('increments the version monotonically across accepted snapshots', () => {
|
||||||
|
const first = acceptedTaskSnapshot();
|
||||||
|
const second = acceptSnapshot({
|
||||||
|
value: taskPayload,
|
||||||
|
validate: validateTaskCollection,
|
||||||
|
previous: first,
|
||||||
|
policy,
|
||||||
|
source: 'gateway:/api/tasks',
|
||||||
|
now: NOW,
|
||||||
|
});
|
||||||
|
expect(second.outcome).toBe('accepted');
|
||||||
|
if (second.outcome === 'accepted') {
|
||||||
|
expect(second.snapshot.version).toBe(first.version + 1);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('combineFreshness', () => {
|
||||||
|
it('gates the surface on the primary collection', () => {
|
||||||
|
expect(combineFreshness('unavailable', ['current'])).toBe('unavailable');
|
||||||
|
expect(combineFreshness('unknown', ['current'])).toBe('unknown');
|
||||||
|
expect(combineFreshness('current', [])).toBe('current');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('degrades to partial when a secondary is unavailable', () => {
|
||||||
|
expect(combineFreshness('current', ['current', 'unavailable'])).toBe('partial');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('degrades to unknown while a secondary is still loading', () => {
|
||||||
|
expect(combineFreshness('current', ['unknown'])).toBe('unknown');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('degrades to stale when any collection is stale', () => {
|
||||||
|
expect(combineFreshness('current', ['stale'])).toBe('stale');
|
||||||
|
expect(combineFreshness('stale', ['current'])).toBe('stale');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('propagates partial secondaries', () => {
|
||||||
|
expect(combineFreshness('current', ['partial'])).toBe('partial');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('computeDigest', () => {
|
||||||
|
it('is stable across key order and changes with data', () => {
|
||||||
|
const a = computeDigest({ x: 1, y: [1, 2] });
|
||||||
|
const b = computeDigest({ y: [1, 2], x: 1 });
|
||||||
|
expect(a).toBe(b);
|
||||||
|
expect(computeDigest({ x: 1, y: [1, 3] })).not.toBe(a);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('verdictValue', () => {
|
||||||
|
it('returns the value only for verified inputs', () => {
|
||||||
|
expect(verdictValue(true, '5')).toBe('5');
|
||||||
|
expect(verdictValue(false, '5')).toBe(UNKNOWN_VERDICT);
|
||||||
|
expect(verdictValue(false, '5')).not.toBe('5');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('formatAge', () => {
|
||||||
|
it('labels age in human terms', () => {
|
||||||
|
expect(formatAge(NOW, NOW)).toBe('just now');
|
||||||
|
expect(formatAge(NOW, NOW + 15_000)).toBe('under a minute ago');
|
||||||
|
expect(formatAge(NOW, NOW + 120_000)).toBe('2m ago');
|
||||||
|
expect(formatAge(NOW, NOW + 3 * 3_600_000)).toBe('3h ago');
|
||||||
|
expect(formatAge(NOW, NOW + 2 * 86_400_000)).toBe('2d ago');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,261 @@
|
|||||||
|
/**
|
||||||
|
* Typed freshness model for gateway-fetched collections (RI-5-001).
|
||||||
|
*
|
||||||
|
* A failed or stale fetch must never be indistinguishable from an empty
|
||||||
|
* healthy collection. Every fetched surface carries an explicit freshness
|
||||||
|
* state, a verified snapshot identity (source, workspace, version, age), and
|
||||||
|
* a mutation guard that refuses state-changing operations unless the data is
|
||||||
|
* verified current.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** Freshness states for fetched data. Never inferred from emptiness. */
|
||||||
|
export type FreshnessState = 'current' | 'stale' | 'partial' | 'unknown' | 'unavailable';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reasons a snapshot is invalidated. An invalidated snapshot is treated as
|
||||||
|
* unavailable and is never rendered as current.
|
||||||
|
*/
|
||||||
|
export type InvalidationReason =
|
||||||
|
| 'cache-corruption'
|
||||||
|
| 'cross-workspace'
|
||||||
|
| 'schema-mismatch'
|
||||||
|
| 'version-regression';
|
||||||
|
|
||||||
|
/** Human-readable labels for invalidation reasons (UI + error messages). */
|
||||||
|
export const invalidationReasonLabels: Record<InvalidationReason, string> = {
|
||||||
|
'cache-corruption': 'cached snapshot failed integrity checks',
|
||||||
|
'cross-workspace': 'data belongs to a different workspace',
|
||||||
|
'schema-mismatch': 'response did not match the expected schema',
|
||||||
|
'version-regression': 'snapshot version regressed below the accepted version',
|
||||||
|
};
|
||||||
|
|
||||||
|
/** A verified snapshot of fetched data with full provenance. */
|
||||||
|
export interface FreshSnapshot<T> {
|
||||||
|
readonly data: T;
|
||||||
|
/** Source identity of the fetch, e.g. `gateway:/api/tasks`. */
|
||||||
|
readonly source: string;
|
||||||
|
/** Workspace scope the data belongs to. */
|
||||||
|
readonly workspace: string;
|
||||||
|
/** Monotonic snapshot sequence number for this surface. */
|
||||||
|
readonly version: number;
|
||||||
|
/** Schema version of the validator that accepted this snapshot. */
|
||||||
|
readonly schemaVersion: number;
|
||||||
|
/** Epoch ms at which the data was verified. */
|
||||||
|
readonly fetchedAt: number;
|
||||||
|
/** Integrity digest of `data`, used to detect cache corruption. */
|
||||||
|
readonly digest: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Provenance label rendered next to last-known data. */
|
||||||
|
export interface FreshnessLabel {
|
||||||
|
readonly source: string;
|
||||||
|
readonly version: number;
|
||||||
|
readonly fetchedAt: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Policy governing freshness for a surface. */
|
||||||
|
export interface FreshnessPolicy {
|
||||||
|
/** Active workspace scope. Snapshots from other scopes are invalidated. */
|
||||||
|
readonly workspace: string;
|
||||||
|
/** Schema version of the current validator. */
|
||||||
|
readonly schemaVersion: number;
|
||||||
|
/** Age after which a verified snapshot degrades from current to stale. */
|
||||||
|
readonly staleAfterMs: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const DEFAULT_FRESHNESS_POLICY: FreshnessPolicy = {
|
||||||
|
workspace: 'default',
|
||||||
|
schemaVersion: 1,
|
||||||
|
staleAfterMs: 60_000,
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Payload returned by a successful schema validation. */
|
||||||
|
export interface FreshPayload<T> {
|
||||||
|
readonly data: T;
|
||||||
|
/**
|
||||||
|
* Workspace identity extracted from the payload itself when the collection
|
||||||
|
* carries one (e.g. a uniform `userId` on projects). `null` when the
|
||||||
|
* collection has no intrinsic workspace identity.
|
||||||
|
*/
|
||||||
|
readonly workspace: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Error thrown when a mutation is attempted on non-current data. */
|
||||||
|
export class StaleMutationError extends Error {
|
||||||
|
readonly freshness: FreshnessState;
|
||||||
|
|
||||||
|
constructor(freshness: FreshnessState) {
|
||||||
|
super(`Refused mutation on ${freshness} data: revalidation is required before mutating.`);
|
||||||
|
this.name = 'StaleMutationError';
|
||||||
|
this.freshness = freshness;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Stable JSON digest used for snapshot integrity checks. */
|
||||||
|
export function computeDigest(value: unknown): string {
|
||||||
|
// FNV-1a 32-bit over the stable JSON serialization. This is an integrity
|
||||||
|
// check against corruption, not a cryptographic guarantee.
|
||||||
|
let hash = 0x811c9dc5;
|
||||||
|
for (const byte of stableStringify(value)) {
|
||||||
|
hash ^= byte.charCodeAt(0);
|
||||||
|
hash = Math.imul(hash, 0x01000193) >>> 0;
|
||||||
|
}
|
||||||
|
return hash.toString(16).padStart(8, '0');
|
||||||
|
}
|
||||||
|
|
||||||
|
function stableStringify(value: unknown): string {
|
||||||
|
return serialize(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function serialize(value: unknown): string {
|
||||||
|
if (value === null || typeof value !== 'object') return JSON.stringify(value) ?? 'null';
|
||||||
|
if (Array.isArray(value)) return `[${value.map(serialize).join(',')}]`;
|
||||||
|
const entries = Object.entries(value as Record<string, unknown>)
|
||||||
|
.filter(([, item]) => item !== undefined)
|
||||||
|
.sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
|
||||||
|
.map(([key, item]) => `${JSON.stringify(key)}:${serialize(item)}`);
|
||||||
|
return `{${entries.join(',')}}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type AcceptSnapshotResult<T> =
|
||||||
|
| { readonly outcome: 'accepted'; readonly snapshot: FreshSnapshot<T> }
|
||||||
|
| { readonly outcome: 'invalidated'; readonly reason: InvalidationReason };
|
||||||
|
|
||||||
|
export interface AcceptSnapshotOptions<T> {
|
||||||
|
/** Raw fetched value (untrusted JSON). */
|
||||||
|
readonly value: unknown;
|
||||||
|
/** Schema validator; returns `null` when the value does not match. */
|
||||||
|
readonly validate: (value: unknown) => FreshPayload<T> | null;
|
||||||
|
/** Previously accepted snapshot for this surface, if any. */
|
||||||
|
readonly previous: FreshSnapshot<T> | null;
|
||||||
|
readonly policy: FreshnessPolicy;
|
||||||
|
readonly source: string;
|
||||||
|
/**
|
||||||
|
* Version carried by the incoming payload when the transport exposes one.
|
||||||
|
* Must not regress below the accepted snapshot's version.
|
||||||
|
*/
|
||||||
|
readonly incomingVersion?: number;
|
||||||
|
readonly now: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validate and accept a fetched value as a snapshot, or invalidate it.
|
||||||
|
*
|
||||||
|
* Invalidation rules (each treated as unavailable, never rendered current):
|
||||||
|
* - schema mismatch: the payload fails validation
|
||||||
|
* - cross-workspace: the payload's workspace differs from the verified one
|
||||||
|
* - version regression: payload/schema version is below the accepted one
|
||||||
|
*/
|
||||||
|
export function acceptSnapshot<T>(options: AcceptSnapshotOptions<T>): AcceptSnapshotResult<T> {
|
||||||
|
const payload = options.validate(options.value);
|
||||||
|
if (payload === null) {
|
||||||
|
return { outcome: 'invalidated', reason: 'schema-mismatch' };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Workspace identity: the payload's own scope wins; a collection with no
|
||||||
|
// intrinsic identity (e.g. an empty list after every project was deleted)
|
||||||
|
// keeps the previously verified scope rather than resetting to the policy
|
||||||
|
// default, so a legitimately empty response is not mistaken for a scope
|
||||||
|
// change.
|
||||||
|
const workspace = payload.workspace ?? options.previous?.workspace ?? options.policy.workspace;
|
||||||
|
if (options.previous !== null && options.previous.workspace !== workspace) {
|
||||||
|
return { outcome: 'invalidated', reason: 'cross-workspace' };
|
||||||
|
}
|
||||||
|
if (options.previous !== null && options.policy.schemaVersion < options.previous.schemaVersion) {
|
||||||
|
return { outcome: 'invalidated', reason: 'version-regression' };
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
options.incomingVersion !== undefined &&
|
||||||
|
options.previous !== null &&
|
||||||
|
options.incomingVersion < options.previous.version
|
||||||
|
) {
|
||||||
|
return { outcome: 'invalidated', reason: 'version-regression' };
|
||||||
|
}
|
||||||
|
|
||||||
|
const snapshot: FreshSnapshot<T> = {
|
||||||
|
data: payload.data,
|
||||||
|
source: options.source,
|
||||||
|
workspace,
|
||||||
|
version: options.incomingVersion ?? (options.previous?.version ?? 0) + 1,
|
||||||
|
schemaVersion: options.policy.schemaVersion,
|
||||||
|
fetchedAt: options.now,
|
||||||
|
digest: computeDigest(payload.data),
|
||||||
|
};
|
||||||
|
return { outcome: 'accepted', snapshot };
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ComputeFreshnessOptions {
|
||||||
|
readonly snapshot: FreshSnapshot<unknown> | null;
|
||||||
|
readonly policy: FreshnessPolicy;
|
||||||
|
readonly now: number;
|
||||||
|
/**
|
||||||
|
* True when the snapshot cannot be trusted as current regardless of age:
|
||||||
|
* the latest revalidation failed, or the snapshot was restored from cache
|
||||||
|
* and has not been verified by a fetch in this session.
|
||||||
|
*/
|
||||||
|
readonly degraded?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Compute the freshness state of a snapshot. A missing snapshot is
|
||||||
|
* `unavailable` (never "empty and healthy"); a degraded or aged snapshot is
|
||||||
|
* `stale` (situational awareness only).
|
||||||
|
*/
|
||||||
|
export function computeFreshness(options: ComputeFreshnessOptions): FreshnessState {
|
||||||
|
const { snapshot, policy, now, degraded = false } = options;
|
||||||
|
if (snapshot === null) return 'unavailable';
|
||||||
|
if (degraded) return 'stale';
|
||||||
|
if (now - snapshot.fetchedAt > policy.staleAfterMs) return 'stale';
|
||||||
|
return 'current';
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Only verified-current data may back a state-changing action. */
|
||||||
|
export function canMutate(state: FreshnessState): boolean {
|
||||||
|
return state === 'current';
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Defense in depth: reject the mutation call itself on non-current data. */
|
||||||
|
export function assertMutable(state: FreshnessState): void {
|
||||||
|
if (!canMutate(state)) {
|
||||||
|
throw new StaleMutationError(state);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Combine freshness across a multi-collection surface (primary + secondaries).
|
||||||
|
* The primary collection gates the surface: unknown while it loads,
|
||||||
|
* unavailable when it fails. Missing secondaries degrade the surface to
|
||||||
|
* `partial`; aged collections degrade it to `stale`.
|
||||||
|
*/
|
||||||
|
export function combineFreshness(
|
||||||
|
primary: FreshnessState,
|
||||||
|
secondaries: readonly FreshnessState[],
|
||||||
|
): FreshnessState {
|
||||||
|
if (primary === 'unavailable') return 'unavailable';
|
||||||
|
if (primary === 'unknown') return 'unknown';
|
||||||
|
if (secondaries.includes('unavailable')) return 'partial';
|
||||||
|
if (secondaries.includes('unknown')) return 'unknown';
|
||||||
|
if (secondaries.includes('stale') || primary === 'stale') return 'stale';
|
||||||
|
if (secondaries.includes('partial')) return 'partial';
|
||||||
|
return 'current';
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Render-safe age label for snapshot provenance. */
|
||||||
|
export function formatAge(fetchedAt: number, now: number): string {
|
||||||
|
const ageMs = Math.max(0, now - fetchedAt);
|
||||||
|
if (ageMs < 10_000) return 'just now';
|
||||||
|
const minutes = Math.floor(ageMs / 60_000);
|
||||||
|
if (minutes < 1) return 'under a minute ago';
|
||||||
|
if (minutes < 60) return `${minutes}m ago`;
|
||||||
|
const hours = Math.floor(minutes / 60);
|
||||||
|
if (hours < 24) return `${hours}h ago`;
|
||||||
|
const days = Math.floor(hours / 24);
|
||||||
|
return `${days}d ago`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Derived verdict placeholder for non-current inputs — never a green value. */
|
||||||
|
export const UNKNOWN_VERDICT = '?';
|
||||||
|
|
||||||
|
export function verdictValue(verified: boolean, value: string): string {
|
||||||
|
return verified ? value : UNKNOWN_VERDICT;
|
||||||
|
}
|
||||||
@@ -0,0 +1,197 @@
|
|||||||
|
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||||
|
import { acceptSnapshot, DEFAULT_FRESHNESS_POLICY } from './model';
|
||||||
|
import { clearSnapshotCache, readSnapshotCache, writeSnapshotCache } from './snapshot-cache';
|
||||||
|
import { validateProjectCollection, validateTaskCollection } from './validators';
|
||||||
|
import { projectFixtures, taskFixtures } from '@/spa/pages/page-fixtures';
|
||||||
|
import type { Project, Task } from '@/lib/types';
|
||||||
|
|
||||||
|
const KEY = 'test:tasks';
|
||||||
|
const NOW = 1_800_000_000_000;
|
||||||
|
const policy = { ...DEFAULT_FRESHNESS_POLICY, staleAfterMs: 60_000 };
|
||||||
|
|
||||||
|
function storedTaskSnapshot() {
|
||||||
|
const result = acceptSnapshot({
|
||||||
|
value: taskFixtures,
|
||||||
|
validate: validateTaskCollection,
|
||||||
|
previous: null,
|
||||||
|
policy,
|
||||||
|
source: 'gateway:/api/tasks',
|
||||||
|
now: NOW,
|
||||||
|
});
|
||||||
|
if (result.outcome !== 'accepted') throw new Error('fixture setup failed');
|
||||||
|
return result.snapshot;
|
||||||
|
}
|
||||||
|
|
||||||
|
function storedProjectSnapshot() {
|
||||||
|
const result = acceptSnapshot({
|
||||||
|
value: projectFixtures,
|
||||||
|
validate: validateProjectCollection,
|
||||||
|
previous: null,
|
||||||
|
policy,
|
||||||
|
source: 'gateway:/api/projects',
|
||||||
|
now: NOW,
|
||||||
|
});
|
||||||
|
if (result.outcome !== 'accepted') throw new Error('fixture setup failed');
|
||||||
|
return result.snapshot;
|
||||||
|
}
|
||||||
|
|
||||||
|
function readTasks() {
|
||||||
|
return readSnapshotCache({
|
||||||
|
key: KEY,
|
||||||
|
workspace: policy.workspace,
|
||||||
|
policy,
|
||||||
|
validate: validateTaskCollection,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Write an arbitrary value directly at the raw cache slot. */
|
||||||
|
function writeRaw(key: string, value: unknown): void {
|
||||||
|
sessionStorage.setItem(`mosaic:freshness:v1:${key}`, JSON.stringify(value));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Parse and re-write the stored entry (for tampering with internals). */
|
||||||
|
function tamperStored<T>(key: string, mutate: (stored: T) => void): void {
|
||||||
|
const parsed = JSON.parse(sessionStorage.getItem(`mosaic:freshness:v1:${key}`) ?? '{}') as T;
|
||||||
|
mutate(parsed);
|
||||||
|
writeRaw(key, parsed);
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
sessionStorage.clear();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
sessionStorage.clear();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('readSnapshotCache', () => {
|
||||||
|
it('misses when nothing is stored', () => {
|
||||||
|
expect(readTasks()).toEqual({ outcome: 'miss' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('hits for a well-formed entry and preserves provenance', () => {
|
||||||
|
const snapshot = storedTaskSnapshot();
|
||||||
|
writeSnapshotCache(KEY, snapshot);
|
||||||
|
|
||||||
|
const result = readTasks();
|
||||||
|
expect(result.outcome).toBe('hit');
|
||||||
|
if (result.outcome === 'hit') {
|
||||||
|
expect(result.snapshot.data).toEqual(taskFixtures);
|
||||||
|
expect(result.snapshot.source).toBe('gateway:/api/tasks');
|
||||||
|
expect(result.snapshot.version).toBe(snapshot.version);
|
||||||
|
expect(result.snapshot.fetchedAt).toBe(snapshot.fetchedAt);
|
||||||
|
expect(result.snapshot.workspace).toBe(snapshot.workspace);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('invalidates unparsable entries as cache corruption', () => {
|
||||||
|
sessionStorage.setItem(`mosaic:freshness:v1:${KEY}`, '{not json');
|
||||||
|
expect(readTasks()).toEqual({ outcome: 'invalidated', reason: 'cache-corruption' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('invalidates structurally wrong entries as cache corruption', () => {
|
||||||
|
const malformed: unknown[] = [
|
||||||
|
'nested but not a snapshot',
|
||||||
|
{ data: taskFixtures }, // missing provenance fields
|
||||||
|
{
|
||||||
|
data: taskFixtures,
|
||||||
|
source: 1,
|
||||||
|
workspace: 'w',
|
||||||
|
version: 1,
|
||||||
|
schemaVersion: 1,
|
||||||
|
fetchedAt: 1,
|
||||||
|
digest: 'x',
|
||||||
|
},
|
||||||
|
null,
|
||||||
|
17,
|
||||||
|
];
|
||||||
|
for (const entry of malformed) {
|
||||||
|
writeRaw(KEY, entry);
|
||||||
|
expect(readTasks()).toEqual({ outcome: 'invalidated', reason: 'cache-corruption' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('invalidates digest mismatches as cache corruption (tampered data)', () => {
|
||||||
|
writeSnapshotCache(KEY, storedTaskSnapshot());
|
||||||
|
tamperStored<{ data: Task[] }>(KEY, (stored) => {
|
||||||
|
stored.data = [...stored.data, { ...stored.data[0]!, id: 'injected-task' }];
|
||||||
|
});
|
||||||
|
expect(readTasks()).toEqual({ outcome: 'invalidated', reason: 'cache-corruption' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('invalidates entries scoped to another workspace', () => {
|
||||||
|
const snapshot = storedTaskSnapshot();
|
||||||
|
writeSnapshotCache(KEY, { ...snapshot, workspace: 'someone-else' });
|
||||||
|
expect(readTasks()).toEqual({ outcome: 'invalidated', reason: 'cross-workspace' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('invalidates entries written by a newer schema as a version regression', () => {
|
||||||
|
const snapshot = storedTaskSnapshot();
|
||||||
|
writeSnapshotCache(KEY, { ...snapshot, schemaVersion: policy.schemaVersion + 1 });
|
||||||
|
expect(readTasks()).toEqual({ outcome: 'invalidated', reason: 'version-regression' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('invalidates entries whose data no longer validates (schema mismatch)', () => {
|
||||||
|
writeSnapshotCache(KEY, storedTaskSnapshot());
|
||||||
|
tamperStored<{ data: unknown }>(KEY, (stored) => {
|
||||||
|
stored.data = { malformed: true };
|
||||||
|
});
|
||||||
|
expect(readTasks()).toEqual({ outcome: 'invalidated', reason: 'schema-mismatch' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('never reports a corrupted raw entry as a hit (negative control)', () => {
|
||||||
|
for (const raw of ['{oops', 'null', '"string"', '[]', '12']) {
|
||||||
|
sessionStorage.setItem(`mosaic:freshness:v1:${KEY}`, raw);
|
||||||
|
const result = readTasks();
|
||||||
|
expect(result.outcome).not.toBe('hit');
|
||||||
|
expect(result.outcome).toBe('invalidated');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('scopes project collections by their workspace identity', () => {
|
||||||
|
const snapshot = storedProjectSnapshot();
|
||||||
|
writeSnapshotCache('test:projects', snapshot);
|
||||||
|
|
||||||
|
const sameScope = readSnapshotCache({
|
||||||
|
key: 'test:projects',
|
||||||
|
workspace: 'user-1',
|
||||||
|
policy,
|
||||||
|
validate: validateProjectCollection,
|
||||||
|
});
|
||||||
|
expect(sameScope.outcome).toBe('hit');
|
||||||
|
|
||||||
|
const foreignScope = readSnapshotCache({
|
||||||
|
key: 'test:projects',
|
||||||
|
workspace: 'user-2',
|
||||||
|
policy,
|
||||||
|
validate: validateProjectCollection,
|
||||||
|
});
|
||||||
|
expect(foreignScope).toEqual({ outcome: 'invalidated', reason: 'cross-workspace' });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('writeSnapshotCache round-trip', () => {
|
||||||
|
it('round-trips an accepted project snapshot', () => {
|
||||||
|
const snapshot = storedProjectSnapshot();
|
||||||
|
writeSnapshotCache('test:projects', snapshot);
|
||||||
|
const result = readSnapshotCache({
|
||||||
|
key: 'test:projects',
|
||||||
|
workspace: snapshot.workspace,
|
||||||
|
policy,
|
||||||
|
validate: validateProjectCollection,
|
||||||
|
});
|
||||||
|
expect(result.outcome).toBe('hit');
|
||||||
|
if (result.outcome === 'hit') {
|
||||||
|
expect(result.snapshot.data).toEqual(projectFixtures as Project[]);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('clearSnapshotCache', () => {
|
||||||
|
it('drops the entry so the next read misses', () => {
|
||||||
|
writeSnapshotCache(KEY, storedTaskSnapshot());
|
||||||
|
expect(readTasks().outcome).toBe('hit');
|
||||||
|
clearSnapshotCache(KEY);
|
||||||
|
expect(readTasks()).toEqual({ outcome: 'miss' });
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,154 @@
|
|||||||
|
import {
|
||||||
|
computeDigest,
|
||||||
|
type FreshPayload,
|
||||||
|
type FreshSnapshot,
|
||||||
|
type FreshnessPolicy,
|
||||||
|
type InvalidationReason,
|
||||||
|
} from './model';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Session-scoped last-known snapshot cache (RI-5-001).
|
||||||
|
*
|
||||||
|
* Restored snapshots are situational awareness only: they surface as `stale`
|
||||||
|
* until a fetch re-verifies them. A cache entry that is corrupted, belongs to
|
||||||
|
* another workspace, was written by a newer schema, or no longer validates is
|
||||||
|
* invalidated (treated as unavailable, never rendered as current).
|
||||||
|
*/
|
||||||
|
|
||||||
|
const CACHE_PREFIX = 'mosaic:freshness:v1';
|
||||||
|
|
||||||
|
interface StoredSnapshot {
|
||||||
|
data: unknown;
|
||||||
|
source: string;
|
||||||
|
workspace: string;
|
||||||
|
version: number;
|
||||||
|
schemaVersion: number;
|
||||||
|
fetchedAt: number;
|
||||||
|
digest: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type SnapshotCacheRead<T> =
|
||||||
|
| { readonly outcome: 'hit'; readonly snapshot: FreshSnapshot<T> }
|
||||||
|
| { readonly outcome: 'miss' }
|
||||||
|
| { readonly outcome: 'invalidated'; readonly reason: InvalidationReason };
|
||||||
|
|
||||||
|
export interface ReadSnapshotCacheOptions<T> {
|
||||||
|
readonly key: string;
|
||||||
|
readonly workspace: string;
|
||||||
|
readonly policy: FreshnessPolicy;
|
||||||
|
readonly validate: (value: unknown) => FreshPayload<T> | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function cacheKey(key: string): string {
|
||||||
|
return `${CACHE_PREFIX}:${key}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isStoredSnapshot(value: unknown): value is StoredSnapshot {
|
||||||
|
if (typeof value !== 'object' || value === null) return false;
|
||||||
|
const candidate = value as Record<string, unknown>;
|
||||||
|
return (
|
||||||
|
typeof candidate['data'] === 'object' &&
|
||||||
|
candidate['data'] !== null &&
|
||||||
|
typeof candidate['source'] === 'string' &&
|
||||||
|
typeof candidate['workspace'] === 'string' &&
|
||||||
|
typeof candidate['version'] === 'number' &&
|
||||||
|
typeof candidate['schemaVersion'] === 'number' &&
|
||||||
|
typeof candidate['fetchedAt'] === 'number' &&
|
||||||
|
typeof candidate['digest'] === 'string'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function getStorage(): Storage | null {
|
||||||
|
try {
|
||||||
|
return globalThis.sessionStorage ?? null;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Restore a cached snapshot under the active workspace scope. Every failure
|
||||||
|
* mode maps to an explicit invalidation reason or a miss — never to data
|
||||||
|
* that renders as current.
|
||||||
|
*/
|
||||||
|
export function readSnapshotCache<T>(options: ReadSnapshotCacheOptions<T>): SnapshotCacheRead<T> {
|
||||||
|
const storage = getStorage();
|
||||||
|
if (storage === null) return { outcome: 'miss' };
|
||||||
|
|
||||||
|
let raw: string | null;
|
||||||
|
try {
|
||||||
|
raw = storage.getItem(cacheKey(options.key));
|
||||||
|
} catch {
|
||||||
|
return { outcome: 'miss' };
|
||||||
|
}
|
||||||
|
if (raw === null) return { outcome: 'miss' };
|
||||||
|
|
||||||
|
let parsed: unknown;
|
||||||
|
try {
|
||||||
|
parsed = JSON.parse(raw);
|
||||||
|
} catch {
|
||||||
|
return { outcome: 'invalidated', reason: 'cache-corruption' };
|
||||||
|
}
|
||||||
|
if (!isStoredSnapshot(parsed)) {
|
||||||
|
return { outcome: 'invalidated', reason: 'cache-corruption' };
|
||||||
|
}
|
||||||
|
if (parsed.workspace !== options.workspace) {
|
||||||
|
return { outcome: 'invalidated', reason: 'cross-workspace' };
|
||||||
|
}
|
||||||
|
if (parsed.schemaVersion > options.policy.schemaVersion) {
|
||||||
|
// Written by a newer build than the running client: version regression.
|
||||||
|
return { outcome: 'invalidated', reason: 'version-regression' };
|
||||||
|
}
|
||||||
|
|
||||||
|
const payload = options.validate(parsed.data);
|
||||||
|
if (payload === null) {
|
||||||
|
return { outcome: 'invalidated', reason: 'schema-mismatch' };
|
||||||
|
}
|
||||||
|
if (computeDigest(payload.data) !== parsed.digest) {
|
||||||
|
return { outcome: 'invalidated', reason: 'cache-corruption' };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
outcome: 'hit',
|
||||||
|
snapshot: {
|
||||||
|
data: payload.data,
|
||||||
|
source: parsed.source,
|
||||||
|
workspace: parsed.workspace,
|
||||||
|
version: parsed.version,
|
||||||
|
schemaVersion: parsed.schemaVersion,
|
||||||
|
fetchedAt: parsed.fetchedAt,
|
||||||
|
digest: parsed.digest,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Persist a verified snapshot. Failures are non-fatal (cache is best-effort). */
|
||||||
|
export function writeSnapshotCache<T>(key: string, snapshot: FreshSnapshot<T>): void {
|
||||||
|
const storage = getStorage();
|
||||||
|
if (storage === null) return;
|
||||||
|
const stored: StoredSnapshot = {
|
||||||
|
data: snapshot.data,
|
||||||
|
source: snapshot.source,
|
||||||
|
workspace: snapshot.workspace,
|
||||||
|
version: snapshot.version,
|
||||||
|
schemaVersion: snapshot.schemaVersion,
|
||||||
|
fetchedAt: snapshot.fetchedAt,
|
||||||
|
digest: snapshot.digest,
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
storage.setItem(cacheKey(key), JSON.stringify(stored));
|
||||||
|
} catch {
|
||||||
|
// Quota or serialization failures simply skip caching.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Drop a cached snapshot (used when a surface invalidates its cache entry). */
|
||||||
|
export function clearSnapshotCache(key: string): void {
|
||||||
|
const storage = getStorage();
|
||||||
|
if (storage === null) return;
|
||||||
|
try {
|
||||||
|
storage.removeItem(cacheKey(key));
|
||||||
|
} catch {
|
||||||
|
// Ignorable: a wedged storage entry is detected as corruption on read.
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,372 @@
|
|||||||
|
import { act } from 'react';
|
||||||
|
import { createRoot, type Root } from 'react-dom/client';
|
||||||
|
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
import type { Task } from '@/lib/types';
|
||||||
|
import { acceptSnapshot, StaleMutationError, DEFAULT_FRESHNESS_POLICY } from './model';
|
||||||
|
import type { FreshnessFailure } from './use-fresh-collection';
|
||||||
|
import {
|
||||||
|
describeFailure,
|
||||||
|
useFreshCollection,
|
||||||
|
type FreshCollection,
|
||||||
|
type UseFreshCollectionOptions,
|
||||||
|
} from './use-fresh-collection';
|
||||||
|
import { validateProjectCollection, validateTaskCollection } from './validators';
|
||||||
|
import { projectFixtures, taskFixtures } from '@/spa/pages/page-fixtures';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Failure-matrix coverage for the freshness seam (RI-5-001): network failure,
|
||||||
|
* auth failure, malformed response, cache corruption, stale age, schema
|
||||||
|
* mismatch, cross-workspace, recovery, and stale-action rejection — with
|
||||||
|
* negative controls proving no case yields current data or an enabled
|
||||||
|
* mutation.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const NOW = 1_800_000_000_000;
|
||||||
|
|
||||||
|
interface Deferred<T> {
|
||||||
|
promise: Promise<T>;
|
||||||
|
resolve: (value: T) => void;
|
||||||
|
reject: (reason?: unknown) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
function createDeferred<T>(): Deferred<T> {
|
||||||
|
let resolve!: (value: T) => void;
|
||||||
|
let reject!: (reason?: unknown) => void;
|
||||||
|
const promise = new Promise<T>((res, rej) => {
|
||||||
|
resolve = res;
|
||||||
|
reject = rej;
|
||||||
|
});
|
||||||
|
return { promise, resolve, reject };
|
||||||
|
}
|
||||||
|
|
||||||
|
let root: Root | null = null;
|
||||||
|
let container: HTMLDivElement;
|
||||||
|
let latest: FreshCollection<Task[]> | null = null;
|
||||||
|
|
||||||
|
function Probe({
|
||||||
|
options,
|
||||||
|
}: {
|
||||||
|
options: UseFreshCollectionOptions<Task[]>;
|
||||||
|
}): React.ReactElement | null {
|
||||||
|
latest = useFreshCollection<Task[]>(options);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeAll(() => {
|
||||||
|
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', {
|
||||||
|
configurable: true,
|
||||||
|
value: true,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
sessionStorage.clear();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(async () => {
|
||||||
|
await act(async () => {
|
||||||
|
root?.unmount();
|
||||||
|
});
|
||||||
|
document.body.replaceChildren();
|
||||||
|
root = null;
|
||||||
|
latest = null;
|
||||||
|
sessionStorage.clear();
|
||||||
|
vi.restoreAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
async function renderCollection(
|
||||||
|
options: UseFreshCollectionOptions<Task[]>,
|
||||||
|
): Promise<FreshCollection<Task[]>> {
|
||||||
|
container = document.createElement('div');
|
||||||
|
document.body.append(container);
|
||||||
|
root = createRoot(container);
|
||||||
|
await act(async () => {
|
||||||
|
root?.render(<Probe options={options} />);
|
||||||
|
});
|
||||||
|
if (latest === null) throw new Error('hook did not run');
|
||||||
|
return latest;
|
||||||
|
}
|
||||||
|
|
||||||
|
function taskOptions(
|
||||||
|
overrides: Partial<UseFreshCollectionOptions<Task[]>> = {},
|
||||||
|
): UseFreshCollectionOptions<Task[]> {
|
||||||
|
return {
|
||||||
|
source: 'gateway:/api/tasks',
|
||||||
|
fetcher: () => Promise.resolve(taskFixtures),
|
||||||
|
validate: validateTaskCollection,
|
||||||
|
cacheKey: 'tasks',
|
||||||
|
clock: () => NOW,
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function authError(statusCode: number): Error & { statusCode: number } {
|
||||||
|
return Object.assign(new Error(`Request failed with ${statusCode}`), { statusCode });
|
||||||
|
}
|
||||||
|
|
||||||
|
function seedCache(key: string): number {
|
||||||
|
const result = acceptSnapshot({
|
||||||
|
value: taskFixtures,
|
||||||
|
validate: validateTaskCollection,
|
||||||
|
previous: null,
|
||||||
|
policy: DEFAULT_FRESHNESS_POLICY,
|
||||||
|
source: 'gateway:/api/tasks',
|
||||||
|
now: NOW,
|
||||||
|
});
|
||||||
|
if (result.outcome !== 'accepted') throw new Error('fixture setup failed');
|
||||||
|
sessionStorage.setItem(`mosaic:freshness:v1:${key}`, JSON.stringify({ ...result.snapshot }));
|
||||||
|
return result.snapshot.version;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('useFreshCollection failure matrix', () => {
|
||||||
|
it('is unknown (not empty) while the first validation is in flight', async () => {
|
||||||
|
const deferred = createDeferred<Task[]>();
|
||||||
|
const collection = await renderCollection(taskOptions({ fetcher: () => deferred.promise }));
|
||||||
|
|
||||||
|
expect(collection.freshness).toBe('unknown');
|
||||||
|
expect(collection.validating).toBe(true);
|
||||||
|
expect(collection.data).toBeNull();
|
||||||
|
expect(collection.canMutate).toBe(false);
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
deferred.resolve(taskFixtures);
|
||||||
|
await deferred.promise;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('becomes current with provenance after a verified fetch', async () => {
|
||||||
|
const collection = await renderCollection(taskOptions());
|
||||||
|
|
||||||
|
expect(collection.freshness).toBe('current');
|
||||||
|
expect(collection.data).toEqual(taskFixtures);
|
||||||
|
expect(collection.snapshot?.source).toBe('gateway:/api/tasks');
|
||||||
|
expect(collection.snapshot?.version).toBe(1);
|
||||||
|
expect(collection.failure).toBeNull();
|
||||||
|
expect(collection.canMutate).toBe(true);
|
||||||
|
// Verified snapshot is persisted for last-known restore.
|
||||||
|
expect(sessionStorage.getItem('mosaic:freshness:v1:tasks')).toBeTruthy();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('treats a network failure as unavailable — never an empty healthy collection', async () => {
|
||||||
|
const collection = await renderCollection(
|
||||||
|
taskOptions({ fetcher: () => Promise.reject(new Error('network down')) }),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(collection.freshness).toBe('unavailable');
|
||||||
|
expect(collection.data).toBeNull();
|
||||||
|
expect(collection.failure).toEqual({ kind: 'fetch', message: 'network down' });
|
||||||
|
expect(collection.canMutate).toBe(false);
|
||||||
|
expect(describeFailure(collection.failure)).toBe('network down');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('treats an auth failure as unavailable and drops the last-known snapshot', async () => {
|
||||||
|
let call = 0;
|
||||||
|
const collection = await renderCollection(
|
||||||
|
taskOptions({
|
||||||
|
fetcher: () => {
|
||||||
|
call += 1;
|
||||||
|
return call === 1 ? Promise.resolve(taskFixtures) : Promise.reject(authError(401));
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(collection.freshness).toBe('current');
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
await collection.revalidate();
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(latest?.freshness).toBe('unavailable');
|
||||||
|
expect(latest?.data).toBeNull();
|
||||||
|
expect(latest?.failure?.kind).toBe('fetch');
|
||||||
|
// The previous user's data must not linger in the session cache.
|
||||||
|
expect(sessionStorage.getItem('mosaic:freshness:v1:tasks')).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('invalidates a malformed response as a schema mismatch', async () => {
|
||||||
|
const collection = await renderCollection(
|
||||||
|
taskOptions({ fetcher: () => Promise.resolve({ malformed: true }) }),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(collection.freshness).toBe('unavailable');
|
||||||
|
expect(collection.data).toBeNull();
|
||||||
|
expect(collection.failure).toEqual({ kind: 'invalidated', reason: 'schema-mismatch' });
|
||||||
|
expect(collection.canMutate).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps the previous snapshot as labeled stale when a later payload mismatches', async () => {
|
||||||
|
let call = 0;
|
||||||
|
const collection = await renderCollection(
|
||||||
|
taskOptions({
|
||||||
|
fetcher: () => {
|
||||||
|
call += 1;
|
||||||
|
return call === 1 ? Promise.resolve(taskFixtures) : Promise.resolve('garbage');
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(collection.freshness).toBe('current');
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
await collection.revalidate();
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(latest?.freshness).toBe('stale');
|
||||||
|
expect(latest?.data).toEqual(taskFixtures);
|
||||||
|
expect(latest?.failure).toEqual({ kind: 'invalidated', reason: 'schema-mismatch' });
|
||||||
|
expect(latest?.canMutate).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('drops the snapshot when the workspace changes under it (cross-workspace)', async () => {
|
||||||
|
let call = 0;
|
||||||
|
const collection = await renderCollection(
|
||||||
|
taskOptions({
|
||||||
|
fetcher: () => {
|
||||||
|
call += 1;
|
||||||
|
return Promise.resolve(
|
||||||
|
call === 1 ? projectFixtures : [{ ...projectFixtures[0], userId: 'user-2' }],
|
||||||
|
);
|
||||||
|
},
|
||||||
|
validate: validateProjectCollection as unknown as (value: unknown) => {
|
||||||
|
data: Task[];
|
||||||
|
workspace: string | null;
|
||||||
|
},
|
||||||
|
source: 'gateway:/api/projects',
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(collection.freshness).toBe('current');
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
await collection.revalidate();
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(latest?.freshness).toBe('unavailable');
|
||||||
|
expect(latest?.data).toBeNull();
|
||||||
|
expect(latest?.failure).toEqual({ kind: 'invalidated', reason: 'cross-workspace' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ages from current to stale and refuses mutations on stale data', async () => {
|
||||||
|
let fakeNow = NOW;
|
||||||
|
const collection = await renderCollection(
|
||||||
|
taskOptions({
|
||||||
|
clock: () => fakeNow,
|
||||||
|
policy: { staleAfterMs: 40 },
|
||||||
|
tickMs: 10,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(collection.freshness).toBe('current');
|
||||||
|
|
||||||
|
// Age the snapshot past the policy and let the tick recompute.
|
||||||
|
fakeNow = NOW + 60;
|
||||||
|
await act(async () => {
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 25));
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(latest?.freshness).toBe('stale');
|
||||||
|
expect(latest?.data).toEqual(taskFixtures);
|
||||||
|
expect(latest?.canMutate).toBe(false);
|
||||||
|
|
||||||
|
const operation = vi.fn(async () => 'result');
|
||||||
|
await expect(latest?.mutate(operation)).rejects.toBeInstanceOf(StaleMutationError);
|
||||||
|
expect(operation).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('recovers to current after a successful revalidation', async () => {
|
||||||
|
let call = 0;
|
||||||
|
const collection = await renderCollection(
|
||||||
|
taskOptions({
|
||||||
|
fetcher: () => {
|
||||||
|
call += 1;
|
||||||
|
return call === 1
|
||||||
|
? Promise.reject(new Error('first attempt failed'))
|
||||||
|
: Promise.resolve(taskFixtures);
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(collection.freshness).toBe('unavailable');
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
await collection.revalidate();
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(latest?.freshness).toBe('current');
|
||||||
|
expect(latest?.failure).toBeNull();
|
||||||
|
|
||||||
|
const operation = vi.fn(async (data: Task[]) => data.length);
|
||||||
|
await expect(latest?.mutate(operation)).resolves.toBe(taskFixtures.length);
|
||||||
|
expect(operation).toHaveBeenCalledOnce();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('restores a cached snapshot as unverified stale data, then verifies it', async () => {
|
||||||
|
const seededVersion = seedCache('tasks');
|
||||||
|
const deferred = createDeferred<Task[]>();
|
||||||
|
const collection = await renderCollection(taskOptions({ fetcher: () => deferred.promise }));
|
||||||
|
|
||||||
|
// Restored data is situational awareness only: labeled stale, never
|
||||||
|
// current, and mutations are refused before verification.
|
||||||
|
expect(collection.freshness).toBe('stale');
|
||||||
|
expect(collection.data).toEqual(taskFixtures);
|
||||||
|
expect(collection.canMutate).toBe(false);
|
||||||
|
await expect(collection.mutate(vi.fn())).rejects.toBeInstanceOf(StaleMutationError);
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
deferred.resolve(taskFixtures);
|
||||||
|
await deferred.promise;
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(latest?.freshness).toBe('current');
|
||||||
|
expect(latest?.snapshot?.version).toBe(seededVersion + 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('never promotes corrupted cache data to current (cache corruption)', async () => {
|
||||||
|
sessionStorage.setItem('mosaic:freshness:v1:tasks', '{"data":');
|
||||||
|
const collection = await renderCollection(
|
||||||
|
taskOptions({ fetcher: () => Promise.reject(new Error('still down')) }),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(collection.freshness).toBe('unavailable');
|
||||||
|
expect(collection.data).toBeNull();
|
||||||
|
expect(collection.canMutate).toBe(false);
|
||||||
|
// The corrupted entry is dropped so it cannot come back.
|
||||||
|
expect(sessionStorage.getItem('mosaic:freshness:v1:tasks')).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('refuses mutations while unknown or unavailable — the call itself, not just the button', async () => {
|
||||||
|
const deferred = createDeferred<Task[]>();
|
||||||
|
const unknown = await renderCollection(taskOptions({ fetcher: () => deferred.promise }));
|
||||||
|
const operation = vi.fn(async () => 'result');
|
||||||
|
await expect(unknown.mutate(operation)).rejects.toBeInstanceOf(StaleMutationError);
|
||||||
|
expect(operation).not.toHaveBeenCalled();
|
||||||
|
await act(async () => {
|
||||||
|
deferred.reject(new Error('failed'));
|
||||||
|
await deferred.promise.catch(() => undefined);
|
||||||
|
});
|
||||||
|
|
||||||
|
const unavailable = latest!;
|
||||||
|
await expect(unavailable.mutate(operation)).rejects.toBeInstanceOf(StaleMutationError);
|
||||||
|
expect(operation).not.toHaveBeenCalled();
|
||||||
|
expect(unavailable.canMutate).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('degrades to stale with last-known data when a revalidation fails after success', async () => {
|
||||||
|
let call = 0;
|
||||||
|
const collection = await renderCollection(
|
||||||
|
taskOptions({
|
||||||
|
fetcher: () => {
|
||||||
|
call += 1;
|
||||||
|
return call === 1
|
||||||
|
? Promise.resolve(taskFixtures)
|
||||||
|
: Promise.reject(new Error('connection lost'));
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(collection.freshness).toBe('current');
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
await collection.revalidate();
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(latest?.freshness).toBe('stale');
|
||||||
|
expect(latest?.data).toEqual(taskFixtures);
|
||||||
|
const failure: FreshnessFailure | null = latest?.failure ?? null;
|
||||||
|
expect(failure).toEqual({ kind: 'fetch', message: 'connection lost' });
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,281 @@
|
|||||||
|
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||||
|
import {
|
||||||
|
acceptSnapshot,
|
||||||
|
assertMutable,
|
||||||
|
computeFreshness,
|
||||||
|
DEFAULT_FRESHNESS_POLICY,
|
||||||
|
invalidationReasonLabels,
|
||||||
|
type FreshPayload,
|
||||||
|
type FreshSnapshot,
|
||||||
|
type FreshnessPolicy,
|
||||||
|
type FreshnessState,
|
||||||
|
type InvalidationReason,
|
||||||
|
StaleMutationError,
|
||||||
|
} from './model';
|
||||||
|
import { clearSnapshotCache, readSnapshotCache, writeSnapshotCache } from './snapshot-cache';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Freshness-aware collection fetch hook (RI-5-001).
|
||||||
|
*
|
||||||
|
* One hook owns one gateway collection end to end: fetch, schema validation,
|
||||||
|
* snapshot acceptance with provenance, session-scoped last-known caching,
|
||||||
|
* aging, and the mutation guard. Pages consume `freshness` and never infer
|
||||||
|
* health from emptiness.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** Why the latest validation did not produce a current snapshot. */
|
||||||
|
export type FreshnessFailure =
|
||||||
|
| { readonly kind: 'fetch'; readonly message: string }
|
||||||
|
| { readonly kind: 'invalidated'; readonly reason: InvalidationReason };
|
||||||
|
|
||||||
|
export interface UseFreshCollectionOptions<T> {
|
||||||
|
/** Source identity for provenance labels, e.g. `gateway:/api/tasks`. */
|
||||||
|
readonly source: string;
|
||||||
|
/** Performs the unvalidated fetch. The hook owns abort and verification. */
|
||||||
|
readonly fetcher: (signal: AbortSignal) => Promise<unknown>;
|
||||||
|
/**
|
||||||
|
* Runtime schema validator. Returning `null` invalidates the payload
|
||||||
|
* (`schema-mismatch`) instead of letting malformed JSON flow into render.
|
||||||
|
*/
|
||||||
|
readonly validate: (value: unknown) => FreshPayload<T> | null;
|
||||||
|
/** Overrides of the default freshness policy. */
|
||||||
|
readonly policy?: Partial<FreshnessPolicy>;
|
||||||
|
/**
|
||||||
|
* Session cache key for last-known snapshots. `null`/omitted disables
|
||||||
|
* restore. Restored snapshots are unverified: they render only as
|
||||||
|
* labeled `stale` data until a fetch re-verifies them.
|
||||||
|
*/
|
||||||
|
readonly cacheKey?: string | null;
|
||||||
|
/** Injectable clock for deterministic age transitions in tests. */
|
||||||
|
readonly clock?: () => number;
|
||||||
|
/** Aging tick interval override (default derived from `staleAfterMs`). */
|
||||||
|
readonly tickMs?: number;
|
||||||
|
/** When false, no fetch runs (surfaces stay `unavailable`/`unknown`). */
|
||||||
|
readonly enabled?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FreshCollection<T> {
|
||||||
|
/** Last verified (or restored-unverified) snapshot, or `null`. */
|
||||||
|
readonly snapshot: FreshSnapshot<T> | null;
|
||||||
|
/** Snapshot data or `null` — never a fabricated empty collection. */
|
||||||
|
readonly data: T | null;
|
||||||
|
readonly freshness: FreshnessState;
|
||||||
|
/** True while a validation request is in flight. */
|
||||||
|
readonly validating: boolean;
|
||||||
|
/** Outcome of the latest failed validation, `null` when healthy. */
|
||||||
|
readonly failure: FreshnessFailure | null;
|
||||||
|
/** False unless freshness is `current`; drives disabled UI affordances. */
|
||||||
|
readonly canMutate: boolean;
|
||||||
|
/** Re-run the fetch and re-verify. Always allowed (it is a read). */
|
||||||
|
readonly revalidate: () => Promise<void>;
|
||||||
|
/**
|
||||||
|
* Run a state-changing operation against verified-current data only.
|
||||||
|
* Rejects with `StaleMutationError` on any other state — the guard fires
|
||||||
|
* even if a disabled button was bypassed (defense in depth).
|
||||||
|
*/
|
||||||
|
readonly mutate: <R>(operation: (data: T) => Promise<R>) => Promise<R>;
|
||||||
|
}
|
||||||
|
|
||||||
|
const defaultClock = (): number => Date.now();
|
||||||
|
|
||||||
|
function resolveTickMs(policy: FreshnessPolicy, override?: number): number {
|
||||||
|
if (override !== undefined && override > 0) return override;
|
||||||
|
return Math.min(5_000, Math.max(250, Math.floor(policy.staleAfterMs / 4)));
|
||||||
|
}
|
||||||
|
|
||||||
|
function isAuthFailure(caught: unknown): boolean {
|
||||||
|
return (
|
||||||
|
typeof caught === 'object' &&
|
||||||
|
caught !== null &&
|
||||||
|
'statusCode' in caught &&
|
||||||
|
((caught as { statusCode?: unknown }).statusCode === 401 ||
|
||||||
|
(caught as { statusCode?: unknown }).statusCode === 403)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function fetchFailureMessage(caught: unknown): string {
|
||||||
|
if (caught instanceof Error && caught.message.trim().length > 0) return caught.message;
|
||||||
|
return 'The request failed.';
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Human-readable summary of a failure for unavailable/stale notices. */
|
||||||
|
export function describeFailure(failure: FreshnessFailure | null): string | null {
|
||||||
|
if (failure === null) return null;
|
||||||
|
if (failure.kind === 'fetch') return failure.message;
|
||||||
|
return `The snapshot was invalidated: ${invalidationReasonLabels[failure.reason]}.`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useFreshCollection<T>(options: UseFreshCollectionOptions<T>): FreshCollection<T> {
|
||||||
|
const optionsRef = useRef(options);
|
||||||
|
optionsRef.current = options;
|
||||||
|
|
||||||
|
const policy = useMemo<FreshnessPolicy>(
|
||||||
|
() => ({ ...DEFAULT_FRESHNESS_POLICY, ...options.policy }),
|
||||||
|
[options.policy],
|
||||||
|
);
|
||||||
|
const policyRef = useRef(policy);
|
||||||
|
policyRef.current = policy;
|
||||||
|
|
||||||
|
const clockRef = useRef(options.clock ?? defaultClock);
|
||||||
|
clockRef.current = options.clock ?? defaultClock;
|
||||||
|
|
||||||
|
const [snapshot, setSnapshot] = useState<FreshSnapshot<T> | null>(null);
|
||||||
|
const [failure, setFailure] = useState<FreshnessFailure | null>(null);
|
||||||
|
const [unverified, setUnverified] = useState(false);
|
||||||
|
const [validating, setValidating] = useState(options.enabled !== false);
|
||||||
|
const [now, setNow] = useState(() => (options.clock ?? defaultClock)());
|
||||||
|
|
||||||
|
const snapshotRef = useRef(snapshot);
|
||||||
|
snapshotRef.current = snapshot;
|
||||||
|
const failureRef = useRef(failure);
|
||||||
|
failureRef.current = failure;
|
||||||
|
const unverifiedRef = useRef(unverified);
|
||||||
|
unverifiedRef.current = unverified;
|
||||||
|
|
||||||
|
const runRef = useRef(0);
|
||||||
|
const abortRef = useRef<AbortController | null>(null);
|
||||||
|
|
||||||
|
const revalidate = useCallback(async (): Promise<void> => {
|
||||||
|
const current = optionsRef.current;
|
||||||
|
if (current.enabled === false) {
|
||||||
|
setValidating(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const runId = ++runRef.current;
|
||||||
|
abortRef.current?.abort();
|
||||||
|
const controller = new AbortController();
|
||||||
|
abortRef.current = controller;
|
||||||
|
setValidating(true);
|
||||||
|
|
||||||
|
let value: unknown;
|
||||||
|
try {
|
||||||
|
value = await current.fetcher(controller.signal);
|
||||||
|
} catch (caught) {
|
||||||
|
if (runRef.current !== runId || controller.signal.aborted) return;
|
||||||
|
if (isAuthFailure(caught)) {
|
||||||
|
// An unauthenticated viewer must not keep (or be served) the
|
||||||
|
// previous user's last-known data.
|
||||||
|
setSnapshot(null);
|
||||||
|
setUnverified(false);
|
||||||
|
if (current.cacheKey) clearSnapshotCache(current.cacheKey);
|
||||||
|
}
|
||||||
|
setFailure({ kind: 'fetch', message: fetchFailureMessage(caught) });
|
||||||
|
setValidating(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (runRef.current !== runId) return;
|
||||||
|
|
||||||
|
const result = acceptSnapshot({
|
||||||
|
value,
|
||||||
|
validate: current.validate,
|
||||||
|
previous: snapshotRef.current,
|
||||||
|
policy: policyRef.current,
|
||||||
|
source: current.source,
|
||||||
|
now: clockRef.current(),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (result.outcome === 'accepted') {
|
||||||
|
setSnapshot(result.snapshot);
|
||||||
|
setUnverified(false);
|
||||||
|
setFailure(null);
|
||||||
|
if (current.cacheKey) writeSnapshotCache(current.cacheKey, result.snapshot);
|
||||||
|
} else {
|
||||||
|
if (result.reason === 'cross-workspace') {
|
||||||
|
// Data verified for a different workspace must not linger as
|
||||||
|
// last-known situational awareness either.
|
||||||
|
setSnapshot(null);
|
||||||
|
setUnverified(false);
|
||||||
|
}
|
||||||
|
if (current.cacheKey) clearSnapshotCache(current.cacheKey);
|
||||||
|
setFailure({ kind: 'invalidated', reason: result.reason });
|
||||||
|
}
|
||||||
|
setValidating(false);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// Restore the last-known snapshot (unverified) and run the first fetch.
|
||||||
|
useEffect(() => {
|
||||||
|
if (optionsRef.current.enabled === false) {
|
||||||
|
setValidating(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const cacheKey = optionsRef.current.cacheKey;
|
||||||
|
if (cacheKey) {
|
||||||
|
const restored = readSnapshotCache<T>({
|
||||||
|
key: cacheKey,
|
||||||
|
workspace: policyRef.current.workspace,
|
||||||
|
policy: policyRef.current,
|
||||||
|
validate: optionsRef.current.validate,
|
||||||
|
});
|
||||||
|
if (restored.outcome === 'hit') {
|
||||||
|
setSnapshot(restored.snapshot);
|
||||||
|
setUnverified(true);
|
||||||
|
} else if (restored.outcome === 'invalidated') {
|
||||||
|
// A corrupted/foreign/regressed entry is dropped immediately; it must
|
||||||
|
// never surface as data. The fetch decides the visible state.
|
||||||
|
clearSnapshotCache(cacheKey);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void revalidate();
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
abortRef.current?.abort();
|
||||||
|
};
|
||||||
|
// Mount-once by design: `revalidate` is stable and reads live options
|
||||||
|
// through refs, so it never needs to re-run when options change.
|
||||||
|
// Route-param pages remount this hook via an identity `key` instead.
|
||||||
|
}, [revalidate]);
|
||||||
|
|
||||||
|
// Aging tick: recomputes freshness as the snapshot ages past the policy.
|
||||||
|
useEffect(() => {
|
||||||
|
const interval = setInterval(
|
||||||
|
() => {
|
||||||
|
setNow(clockRef.current());
|
||||||
|
},
|
||||||
|
resolveTickMs(policyRef.current, optionsRef.current.tickMs),
|
||||||
|
);
|
||||||
|
return () => clearInterval(interval);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const freshness = useMemo<FreshnessState>(() => {
|
||||||
|
if (snapshot === null) return validating ? 'unknown' : 'unavailable';
|
||||||
|
return computeFreshness({
|
||||||
|
snapshot,
|
||||||
|
policy,
|
||||||
|
now,
|
||||||
|
degraded: failure !== null || unverified,
|
||||||
|
});
|
||||||
|
// `now` from state covers age; refs inside computeFreshness are pure.
|
||||||
|
}, [snapshot, validating, failure, unverified, now, policy]);
|
||||||
|
|
||||||
|
const canMutate = freshness === 'current';
|
||||||
|
|
||||||
|
const mutate = useCallback(async <R>(operation: (data: T) => Promise<R>): Promise<R> => {
|
||||||
|
const currentSnapshot = snapshotRef.current;
|
||||||
|
// No verified snapshot at all: with nothing verified there is nothing
|
||||||
|
// current to mutate, regardless of the recorded failure.
|
||||||
|
if (currentSnapshot === null) throw new StaleMutationError('unavailable');
|
||||||
|
const state = computeFreshness({
|
||||||
|
snapshot: currentSnapshot,
|
||||||
|
policy: policyRef.current,
|
||||||
|
now: clockRef.current(),
|
||||||
|
degraded: failureRef.current !== null || unverifiedRef.current,
|
||||||
|
});
|
||||||
|
assertMutable(state);
|
||||||
|
return operation(currentSnapshot.data);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return {
|
||||||
|
snapshot,
|
||||||
|
data: snapshot === null ? null : snapshot.data,
|
||||||
|
freshness,
|
||||||
|
validating,
|
||||||
|
failure,
|
||||||
|
canMutate,
|
||||||
|
revalidate,
|
||||||
|
mutate,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import type { Mission, Project, Task } from '@/lib/types';
|
||||||
|
import {
|
||||||
|
validateMissionCollection,
|
||||||
|
validateProjectCollection,
|
||||||
|
validateProjectEntity,
|
||||||
|
validateTaskCollection,
|
||||||
|
} from './validators';
|
||||||
|
import { missionFixtures, projectFixtures, taskFixtures } from '@/spa/pages/page-fixtures';
|
||||||
|
|
||||||
|
describe('validateTaskCollection', () => {
|
||||||
|
it('accepts a well-formed task collection', () => {
|
||||||
|
expect(validateTaskCollection(taskFixtures)).toEqual({
|
||||||
|
data: taskFixtures,
|
||||||
|
workspace: null,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('accepts an empty collection (a healthy empty state is a valid payload)', () => {
|
||||||
|
expect(validateTaskCollection([])).toEqual({ data: [], workspace: null });
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
['not an array', { items: [] }],
|
||||||
|
['item is not an object', ['nope']],
|
||||||
|
['missing id', [{ ...(taskFixtures[0] as Task), id: undefined }]],
|
||||||
|
['missing title', [{ ...(taskFixtures[0] as Task), title: undefined }]],
|
||||||
|
['unknown status enum', [{ ...(taskFixtures[0] as Task), status: 'finished' }]],
|
||||||
|
['unknown priority enum', [{ ...(taskFixtures[0] as Task), priority: 'urgent' }]],
|
||||||
|
['tags of the wrong type', [{ ...(taskFixtures[0] as Task), tags: 'spa' }]],
|
||||||
|
['metadata of the wrong type', [{ ...(taskFixtures[0] as Task), metadata: 'notes' }]],
|
||||||
|
['createdAt of the wrong type', [{ ...(taskFixtures[0] as Task), createdAt: 1234 }]],
|
||||||
|
['null sneaks past a required string', [{ ...(taskFixtures[0] as Task), title: null }]],
|
||||||
|
])('rejects a malformed payload: %s', (_label, value) => {
|
||||||
|
expect(validateTaskCollection(value)).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('validateMissionCollection', () => {
|
||||||
|
it('accepts a well-formed mission collection', () => {
|
||||||
|
expect(validateMissionCollection(missionFixtures)).toEqual({
|
||||||
|
data: missionFixtures,
|
||||||
|
workspace: null,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
['not an array', null],
|
||||||
|
['item missing name', [{ ...(missionFixtures[0] as Mission), name: 42 }]],
|
||||||
|
['unknown status enum', [{ ...(missionFixtures[0] as Mission), status: 'canceled' }]],
|
||||||
|
['projectId of the wrong type', [{ ...(missionFixtures[0] as Mission), projectId: 7 }]],
|
||||||
|
])('rejects a malformed payload: %s', (_label, value) => {
|
||||||
|
expect(validateMissionCollection(value)).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('validateProjectCollection', () => {
|
||||||
|
it('accepts a uniform workspace-scoped collection and reports its workspace', () => {
|
||||||
|
expect(validateProjectCollection(projectFixtures)).toEqual({
|
||||||
|
data: projectFixtures,
|
||||||
|
workspace: 'user-1',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('accepts an empty collection with no workspace identity', () => {
|
||||||
|
expect(validateProjectCollection([])).toEqual({ data: [], workspace: null });
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
['not an array', 42],
|
||||||
|
['item missing userId', [{ ...(projectFixtures[0] as Project), userId: undefined }]],
|
||||||
|
['unknown status enum', [{ ...(projectFixtures[0] as Project), status: 'live' }]],
|
||||||
|
['description of the wrong type', [{ ...(projectFixtures[0] as Project), description: 1 }]],
|
||||||
|
])('rejects a malformed payload: %s', (_label, value) => {
|
||||||
|
expect(validateProjectCollection(value)).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects a collection mixing workspace identities (cross-workspace leak)', () => {
|
||||||
|
const mixed = [
|
||||||
|
projectFixtures[0] as Project,
|
||||||
|
{ ...(projectFixtures[1] as Project), userId: 'user-2' },
|
||||||
|
];
|
||||||
|
expect(validateProjectCollection(mixed)).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('validateProjectEntity', () => {
|
||||||
|
it('accepts a well-formed project and reports its workspace', () => {
|
||||||
|
expect(validateProjectEntity(projectFixtures[0])).toEqual({
|
||||||
|
data: projectFixtures[0],
|
||||||
|
workspace: 'user-1',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
['not an object', 'project-1'],
|
||||||
|
['null', null],
|
||||||
|
['array', [projectFixtures[0]]],
|
||||||
|
['missing userId', [{ ...(projectFixtures[0] as Project), userId: null }]],
|
||||||
|
])('rejects a malformed entity: %s', (_label, value) => {
|
||||||
|
expect(validateProjectEntity(value)).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,135 @@
|
|||||||
|
import type { Mission, Project, Task, MissionStatus, TaskPriority, TaskStatus } from '@/lib/types';
|
||||||
|
import type { FreshPayload } from './model';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Runtime schema validators for gateway collections (RI-5-001).
|
||||||
|
*
|
||||||
|
* `api<T>()` returns untrusted JSON cast to `T`; these validators are the
|
||||||
|
* seam where a malformed response becomes an explicit schema mismatch
|
||||||
|
* instead of flowing into the render path as if it were healthy data.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const taskStatuses: readonly TaskStatus[] = [
|
||||||
|
'not-started',
|
||||||
|
'in-progress',
|
||||||
|
'blocked',
|
||||||
|
'done',
|
||||||
|
'cancelled',
|
||||||
|
];
|
||||||
|
const taskPriorities: readonly TaskPriority[] = ['critical', 'high', 'medium', 'low'];
|
||||||
|
const missionStatuses: readonly MissionStatus[] = [
|
||||||
|
'planning',
|
||||||
|
'active',
|
||||||
|
'paused',
|
||||||
|
'completed',
|
||||||
|
'failed',
|
||||||
|
];
|
||||||
|
const projectStatuses: readonly Project['status'][] = ['active', 'paused', 'completed', 'archived'];
|
||||||
|
|
||||||
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||||
|
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isString(value: unknown): value is string {
|
||||||
|
return typeof value === 'string';
|
||||||
|
}
|
||||||
|
|
||||||
|
function isNullableString(value: unknown): value is string | null {
|
||||||
|
return value === null || typeof value === 'string';
|
||||||
|
}
|
||||||
|
|
||||||
|
function isOneOf<T extends string>(value: unknown, allowed: readonly T[]): value is T {
|
||||||
|
return typeof value === 'string' && (allowed as readonly string[]).includes(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isNullableRecord(value: unknown): value is Record<string, unknown> | null {
|
||||||
|
return value === null || isRecord(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isNullableStringArray(value: unknown): value is string[] | null {
|
||||||
|
if (value === null) return true;
|
||||||
|
if (!Array.isArray(value)) return false;
|
||||||
|
return value.every((item) => typeof item === 'string');
|
||||||
|
}
|
||||||
|
|
||||||
|
function isIsoLike(value: unknown): value is string {
|
||||||
|
return typeof value === 'string' && value.length > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isTask(value: unknown): value is Task {
|
||||||
|
if (!isRecord(value)) return false;
|
||||||
|
return (
|
||||||
|
isString(value['id']) &&
|
||||||
|
isString(value['title']) &&
|
||||||
|
isOneOf(value['status'], taskStatuses) &&
|
||||||
|
isOneOf(value['priority'], taskPriorities) &&
|
||||||
|
isNullableString(value['projectId']) &&
|
||||||
|
isNullableString(value['missionId']) &&
|
||||||
|
isNullableString(value['assignee']) &&
|
||||||
|
isNullableStringArray(value['tags']) &&
|
||||||
|
isNullableRecord(value['metadata']) &&
|
||||||
|
isNullableString(value['dueDate']) &&
|
||||||
|
isIsoLike(value['createdAt']) &&
|
||||||
|
isIsoLike(value['updatedAt'])
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Tasks carry no workspace identity; scope falls back to the policy. */
|
||||||
|
export function validateTaskCollection(value: unknown): FreshPayload<Task[]> | null {
|
||||||
|
if (!Array.isArray(value) || !value.every(isTask)) return null;
|
||||||
|
return { data: value as Task[], workspace: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
function isMission(value: unknown): value is Mission {
|
||||||
|
if (!isRecord(value)) return false;
|
||||||
|
return (
|
||||||
|
isString(value['id']) &&
|
||||||
|
isString(value['name']) &&
|
||||||
|
isOneOf(value['status'], missionStatuses) &&
|
||||||
|
isNullableString(value['projectId']) &&
|
||||||
|
isNullableString(value['description']) &&
|
||||||
|
isNullableRecord(value['metadata']) &&
|
||||||
|
isIsoLike(value['createdAt']) &&
|
||||||
|
isIsoLike(value['updatedAt'])
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Missions carry no workspace identity; scope falls back to the policy. */
|
||||||
|
export function validateMissionCollection(value: unknown): FreshPayload<Mission[]> | null {
|
||||||
|
if (!Array.isArray(value) || !value.every(isMission)) return null;
|
||||||
|
return { data: value as Mission[], workspace: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
function isProject(value: unknown): value is Project {
|
||||||
|
if (!isRecord(value)) return false;
|
||||||
|
return (
|
||||||
|
isString(value['id']) &&
|
||||||
|
isString(value['name']) &&
|
||||||
|
isOneOf(value['status'], projectStatuses) &&
|
||||||
|
isString(value['userId']) &&
|
||||||
|
isNullableString(value['description']) &&
|
||||||
|
isNullableRecord(value['metadata']) &&
|
||||||
|
isIsoLike(value['createdAt']) &&
|
||||||
|
isIsoLike(value['updatedAt'])
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Projects are workspace-scoped: every item must carry the same `userId`.
|
||||||
|
* A collection mixing identities (cross-workspace leak) is a schema
|
||||||
|
* mismatch; the uniform `userId` becomes the snapshot workspace.
|
||||||
|
*/
|
||||||
|
export function validateProjectCollection(value: unknown): FreshPayload<Project[]> | null {
|
||||||
|
if (!Array.isArray(value) || !value.every(isProject)) return null;
|
||||||
|
const projects = value as Project[];
|
||||||
|
const workspaces = new Set(projects.map((project) => project.userId));
|
||||||
|
if (workspaces.size > 1) return null;
|
||||||
|
return { data: projects, workspace: projects.length > 0 ? projects[0]!.userId : null };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Single project entity (project detail primary collection). */
|
||||||
|
export function validateProjectEntity(value: unknown): FreshPayload<Project> | null {
|
||||||
|
if (!isProject(value)) return null;
|
||||||
|
const project = value as Project;
|
||||||
|
return { data: project, workspace: project.userId };
|
||||||
|
}
|
||||||
@@ -35,6 +35,7 @@ afterEach(async () => {
|
|||||||
document.body.replaceChildren();
|
document.body.replaceChildren();
|
||||||
root = null;
|
root = null;
|
||||||
apiMock.mockReset();
|
apiMock.mockReset();
|
||||||
|
sessionStorage.clear();
|
||||||
});
|
});
|
||||||
|
|
||||||
async function renderProjectDetailPage(): Promise<ReturnType<typeof createMemoryRouter>> {
|
async function renderProjectDetailPage(): Promise<ReturnType<typeof createMemoryRouter>> {
|
||||||
@@ -64,21 +65,49 @@ function clickButtonByText(text: string): void {
|
|||||||
button.dispatchEvent(new MouseEvent('click', { bubbles: true }));
|
button.dispatchEvent(new MouseEvent('click', { bubbles: true }));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function flushAct(): Promise<void> {
|
||||||
|
await act(async () => {
|
||||||
|
await Promise.resolve();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Deferred<T> {
|
||||||
|
promise: Promise<T>;
|
||||||
|
resolve: (value: T) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
function createDeferred<T>(): Deferred<T> {
|
||||||
|
let resolve!: (value: T) => void;
|
||||||
|
const promise = new Promise<T>((res) => {
|
||||||
|
resolve = res;
|
||||||
|
});
|
||||||
|
return { promise, resolve };
|
||||||
|
}
|
||||||
|
|
||||||
|
const projectOneTasks = taskFixtures.filter((task) => task.projectId === 'project-1');
|
||||||
|
|
||||||
|
function mockHealthyLoad(): void {
|
||||||
|
apiMock
|
||||||
|
.mockResolvedValueOnce(projectFixtures[0])
|
||||||
|
.mockResolvedValueOnce(missionFixtures)
|
||||||
|
.mockResolvedValueOnce(projectOneTasks);
|
||||||
|
}
|
||||||
|
|
||||||
describe('ProjectDetailPage', () => {
|
describe('ProjectDetailPage', () => {
|
||||||
it('loads the project, tasks, missions, and optional PRD content for the active project', async () => {
|
it('loads the project, tasks, missions, and optional PRD content for the active project', async () => {
|
||||||
apiMock
|
mockHealthyLoad();
|
||||||
.mockResolvedValueOnce(projectFixtures[0])
|
|
||||||
.mockResolvedValueOnce(missionFixtures)
|
|
||||||
.mockResolvedValueOnce(taskFixtures.filter((task) => task.projectId === 'project-1'));
|
|
||||||
|
|
||||||
await renderProjectDetailPage();
|
await renderProjectDetailPage();
|
||||||
|
|
||||||
expect(apiMock.mock.calls).toEqual([
|
expect(apiMock.mock.calls.map((call) => call[0])).toEqual([
|
||||||
['/api/projects/project-1'],
|
'/api/projects/project-1',
|
||||||
['/api/missions'],
|
'/api/missions',
|
||||||
['/api/tasks?projectId=project-1'],
|
'/api/tasks?projectId=project-1',
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
expect(container.querySelector('[data-freshness]')?.getAttribute('data-freshness')).toBe(
|
||||||
|
'current',
|
||||||
|
);
|
||||||
expect(container.textContent).toContain('Mosaic Stack');
|
expect(container.textContent).toContain('Mosaic Stack');
|
||||||
expect(container.textContent).toContain('Route /projects/:id');
|
expect(container.textContent).toContain('Route /projects/:id');
|
||||||
expect(container.textContent).toContain('Tasks');
|
expect(container.textContent).toContain('Tasks');
|
||||||
@@ -101,10 +130,7 @@ describe('ProjectDetailPage', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('opens and closes the existing read-only task modal from the tasks tab', async () => {
|
it('opens and closes the existing read-only task modal from the tasks tab', async () => {
|
||||||
apiMock
|
mockHealthyLoad();
|
||||||
.mockResolvedValueOnce(projectFixtures[0])
|
|
||||||
.mockResolvedValueOnce(missionFixtures)
|
|
||||||
.mockResolvedValueOnce(taskFixtures.filter((task) => task.projectId === 'project-1'));
|
|
||||||
|
|
||||||
await renderProjectDetailPage();
|
await renderProjectDetailPage();
|
||||||
|
|
||||||
@@ -134,35 +160,153 @@ describe('ProjectDetailPage', () => {
|
|||||||
expect(container.querySelector('[role="dialog"]')).toBeNull();
|
expect(container.querySelector('[role="dialog"]')).toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('renders the project with an empty missions tab when the missions request fails', async () => {
|
it('shows verified completion verdicts when the task collection is current', async () => {
|
||||||
apiMock
|
mockHealthyLoad();
|
||||||
.mockResolvedValueOnce(projectFixtures[0])
|
|
||||||
.mockRejectedValueOnce(new Error('Missions request failed'))
|
|
||||||
.mockResolvedValueOnce(taskFixtures.filter((task) => task.projectId === 'project-1'));
|
|
||||||
|
|
||||||
await renderProjectDetailPage();
|
await renderProjectDetailPage();
|
||||||
|
|
||||||
expect(container.textContent).toContain('Mosaic Stack');
|
const doneCard = [...container.querySelectorAll('div')].find(
|
||||||
expect(container.querySelector('[role="alert"]')).toBeNull();
|
(candidate) => candidate.textContent === 'Done1',
|
||||||
|
);
|
||||||
await act(async () => {
|
expect(doneCard).toBeTruthy();
|
||||||
clickButtonByText('Missions (0)');
|
const inProgressCard = [...container.querySelectorAll('div')].find(
|
||||||
});
|
(candidate) => candidate.textContent === 'In Progress1',
|
||||||
|
);
|
||||||
expect(container.textContent).toContain('No missions for this project');
|
expect(inProgressCard).toBeTruthy();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('renders a visible alert when the project request fails and lets the user navigate back', async () => {
|
it('renders an explicit unavailable missions tab when the missions request fails (partial, not empty)', async () => {
|
||||||
|
apiMock
|
||||||
|
.mockResolvedValueOnce(projectFixtures[0])
|
||||||
|
.mockRejectedValueOnce(new Error('Missions request failed'))
|
||||||
|
.mockResolvedValueOnce(projectOneTasks);
|
||||||
|
|
||||||
|
await renderProjectDetailPage();
|
||||||
|
|
||||||
|
// Secondary failure degrades the surface to partial; the project itself
|
||||||
|
// still renders.
|
||||||
|
expect(container.querySelector('[data-freshness]')?.getAttribute('data-freshness')).toBe(
|
||||||
|
'partial',
|
||||||
|
);
|
||||||
|
expect(container.textContent).toContain('Mosaic Stack');
|
||||||
|
const partial = container.querySelector('[role="status"]');
|
||||||
|
expect(partial?.textContent).toContain('Missions');
|
||||||
|
expect(partial?.textContent).toContain('unavailable');
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
clickButtonByText('Missions (?)');
|
||||||
|
});
|
||||||
|
|
||||||
|
const alert = container.querySelector('[role="alert"]');
|
||||||
|
expect(alert?.textContent).toContain('Missions request failed');
|
||||||
|
// Negative control: a failed fetch must not look like an empty list.
|
||||||
|
expect(container.textContent).not.toContain('No missions for this project');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('marks derived verdicts unknown when the tasks collection is unavailable', async () => {
|
||||||
|
apiMock
|
||||||
|
.mockResolvedValueOnce(projectFixtures[0])
|
||||||
|
.mockResolvedValueOnce(missionFixtures)
|
||||||
|
.mockRejectedValueOnce(new Error('Tasks request failed'));
|
||||||
|
|
||||||
|
await renderProjectDetailPage();
|
||||||
|
|
||||||
|
expect(container.querySelector('[data-freshness]')?.getAttribute('data-freshness')).toBe(
|
||||||
|
'partial',
|
||||||
|
);
|
||||||
|
|
||||||
|
// Completion verdicts become unknown ('?') — never green counts.
|
||||||
|
for (const label of ['Done', 'In Progress', 'Blocked', 'Tasks']) {
|
||||||
|
const unknownCard = [...container.querySelectorAll('div')].find(
|
||||||
|
(candidate) => candidate.textContent === `${label}?`,
|
||||||
|
);
|
||||||
|
expect(unknownCard, `expected ${label} card to render ?`).toBeTruthy();
|
||||||
|
}
|
||||||
|
// Negative control: no green "Done 1" verdict anywhere.
|
||||||
|
expect(
|
||||||
|
[...container.querySelectorAll('div')].some((candidate) => candidate.textContent === 'Done1'),
|
||||||
|
).toBe(false);
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
clickButtonByText('Tasks (?)');
|
||||||
|
});
|
||||||
|
|
||||||
|
const alert = container.querySelector('[role="alert"]');
|
||||||
|
expect(alert?.textContent).toContain('Tasks request failed');
|
||||||
|
// Negative control: no healthy empty task list from a failed fetch.
|
||||||
|
expect(container.textContent).not.toContain('No tasks found');
|
||||||
|
expect(container.querySelector('table')).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('recovers a partial surface to current after revalidation', async () => {
|
||||||
|
apiMock
|
||||||
|
.mockResolvedValueOnce(projectFixtures[0])
|
||||||
|
.mockResolvedValueOnce(missionFixtures)
|
||||||
|
.mockRejectedValueOnce(new Error('Tasks request failed'))
|
||||||
|
.mockResolvedValueOnce(projectFixtures[0])
|
||||||
|
.mockResolvedValueOnce(missionFixtures)
|
||||||
|
.mockResolvedValueOnce(projectOneTasks);
|
||||||
|
|
||||||
|
await renderProjectDetailPage();
|
||||||
|
expect(container.querySelector('[data-freshness]')?.getAttribute('data-freshness')).toBe(
|
||||||
|
'partial',
|
||||||
|
);
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
clickButtonByText('Revalidate');
|
||||||
|
});
|
||||||
|
await flushAct();
|
||||||
|
|
||||||
|
expect(container.querySelector('[data-freshness]')?.getAttribute('data-freshness')).toBe(
|
||||||
|
'current',
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
[...container.querySelectorAll('div')].some((candidate) => candidate.textContent === 'Done1'),
|
||||||
|
).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("never shows one project's data on another project's route after navigation", async () => {
|
||||||
|
mockHealthyLoad();
|
||||||
|
|
||||||
|
const router = await renderProjectDetailPage();
|
||||||
|
expect(container.textContent).toContain('Mosaic Stack');
|
||||||
|
|
||||||
|
const deferred = createDeferred<(typeof projectFixtures)[number]>();
|
||||||
|
apiMock
|
||||||
|
.mockResolvedValueOnce(deferred.promise)
|
||||||
|
.mockResolvedValueOnce([])
|
||||||
|
.mockResolvedValueOnce([]);
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
await router.navigate('/projects/project-2');
|
||||||
|
});
|
||||||
|
|
||||||
|
// While project-2 loads, nothing from project-1 may render on its route.
|
||||||
|
expect(container.textContent).toContain('Loading project...');
|
||||||
|
expect(container.textContent).not.toContain('Mosaic Stack');
|
||||||
|
expect(container.textContent).not.toContain('Route /projects/:id');
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
deferred.resolve(projectFixtures[1]!);
|
||||||
|
await deferred.promise;
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(container.textContent).toContain('Agent Runtime');
|
||||||
|
expect(apiMock.mock.calls[3]?.[0]).toBe('/api/projects/project-2');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('renders a visible unavailable state when the project request fails and lets the user navigate back', async () => {
|
||||||
apiMock
|
apiMock
|
||||||
.mockRejectedValueOnce(new Error('Project request failed'))
|
.mockRejectedValueOnce(new Error('Project request failed'))
|
||||||
.mockResolvedValueOnce(missionFixtures)
|
.mockResolvedValueOnce(missionFixtures)
|
||||||
.mockResolvedValueOnce(taskFixtures.filter((task) => task.projectId === 'project-1'));
|
.mockResolvedValueOnce(projectOneTasks);
|
||||||
|
|
||||||
const router = await renderProjectDetailPage();
|
const router = await renderProjectDetailPage();
|
||||||
|
|
||||||
const alert = container.querySelector('[role="alert"]');
|
const alert = container.querySelector('[role="alert"]');
|
||||||
expect(alert).toBeTruthy();
|
expect(alert).toBeTruthy();
|
||||||
expect(alert?.textContent).toContain('Project request failed');
|
expect(alert?.textContent).toContain('Project request failed');
|
||||||
|
expect(alert?.textContent).toContain('not an empty result');
|
||||||
expect(container.textContent).not.toContain('Mosaic Stack');
|
expect(container.textContent).not.toContain('Mosaic Stack');
|
||||||
|
|
||||||
await act(async () => {
|
await act(async () => {
|
||||||
|
|||||||
@@ -1,14 +1,30 @@
|
|||||||
import { useEffect, useState, type ReactElement } from 'react';
|
import { useState, type ReactElement } from 'react';
|
||||||
import { useNavigate, useParams } from 'react-router-dom';
|
import { useNavigate, useParams } from 'react-router-dom';
|
||||||
import { MissionTimeline } from '@/components/projects/mission-timeline';
|
import { MissionTimeline } from '@/components/projects/mission-timeline';
|
||||||
import { PrdViewer } from '@/components/projects/prd-viewer';
|
import { PrdViewer } from '@/components/projects/prd-viewer';
|
||||||
import { TaskDetailModal } from '@/components/tasks/task-detail-modal';
|
import { TaskDetailModal } from '@/components/tasks/task-detail-modal';
|
||||||
import { TaskListView } from '@/components/tasks/task-list-view';
|
import { TaskListView } from '@/components/tasks/task-list-view';
|
||||||
import { TaskStatusSummary } from '@/components/tasks/task-status-summary';
|
import { TaskStatusSummary } from '@/components/tasks/task-status-summary';
|
||||||
|
import {
|
||||||
|
PartialDataNotice,
|
||||||
|
StaleDataNotice,
|
||||||
|
UnavailableDataNotice,
|
||||||
|
} from '@/components/freshness/freshness-notices';
|
||||||
import { api } from '@/lib/api';
|
import { api } from '@/lib/api';
|
||||||
import { cn } from '@/lib/cn';
|
import { cn } from '@/lib/cn';
|
||||||
import type { Mission, Project, Task, TaskStatus } from '@/lib/types';
|
import type { Mission, Project, Task, TaskStatus } from '@/lib/types';
|
||||||
import { getErrorMessage } from './page-errors';
|
import {
|
||||||
|
combineFreshness,
|
||||||
|
UNKNOWN_VERDICT,
|
||||||
|
verdictValue,
|
||||||
|
type FreshSnapshot,
|
||||||
|
} from '@/lib/freshness/model';
|
||||||
|
import { describeFailure, useFreshCollection } from '@/lib/freshness/use-fresh-collection';
|
||||||
|
import {
|
||||||
|
validateMissionCollection,
|
||||||
|
validateProjectEntity,
|
||||||
|
validateTaskCollection,
|
||||||
|
} from '@/lib/freshness/validators';
|
||||||
|
|
||||||
type Tab = 'overview' | 'tasks' | 'missions' | 'prd';
|
type Tab = 'overview' | 'tasks' | 'missions' | 'prd';
|
||||||
|
|
||||||
@@ -51,73 +67,62 @@ function TabButton({ id, label, activeTab, onClick }: TabButtonProps): ReactElem
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Remounts per project id so no state from one project renders for another. */
|
||||||
export function ProjectDetailPage(): ReactElement {
|
export function ProjectDetailPage(): ReactElement {
|
||||||
const { id = '' } = useParams();
|
const { id = '' } = useParams();
|
||||||
|
return <ProjectDetail id={id} key={id} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
function ProjectDetail({ id }: { id: string }): ReactElement {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const [project, setProject] = useState<Project | null>(null);
|
const enabled = id.length > 0;
|
||||||
const [missions, setMissions] = useState<Mission[]>([]);
|
|
||||||
const [tasks, setTasks] = useState<Task[]>([]);
|
// Primary collection gates the surface; missions and tasks are secondaries
|
||||||
const [loading, setLoading] = useState(true);
|
// whose failures degrade the surface to `partial` instead of rendering
|
||||||
const [error, setError] = useState<string | null>(null);
|
// empty healthy lists.
|
||||||
|
const project = useFreshCollection<Project>({
|
||||||
|
source: `gateway:/api/projects/${id}`,
|
||||||
|
fetcher: (signal) => api<unknown>(`/api/projects/${id}`, { signal }),
|
||||||
|
validate: validateProjectEntity,
|
||||||
|
// No last-known restore: the entity carries workspace identity that
|
||||||
|
// cannot be scope-checked before display (see ProjectsPage note).
|
||||||
|
enabled,
|
||||||
|
});
|
||||||
|
const missions = useFreshCollection<Mission[]>({
|
||||||
|
source: 'gateway:/api/missions',
|
||||||
|
fetcher: (signal) => api<unknown>('/api/missions', { signal }),
|
||||||
|
validate: validateMissionCollection,
|
||||||
|
cacheKey: enabled ? 'missions' : null,
|
||||||
|
enabled,
|
||||||
|
});
|
||||||
|
const tasks = useFreshCollection<Task[]>({
|
||||||
|
source: `gateway:/api/tasks?projectId=${id}`,
|
||||||
|
fetcher: (signal) => api<unknown>(`/api/tasks?projectId=${id}`, { signal }),
|
||||||
|
validate: validateTaskCollection,
|
||||||
|
cacheKey: enabled ? `project-tasks:${id}` : null,
|
||||||
|
enabled,
|
||||||
|
});
|
||||||
|
|
||||||
const [activeTab, setActiveTab] = useState<Tab>('overview');
|
const [activeTab, setActiveTab] = useState<Tab>('overview');
|
||||||
const [taskFilter, setTaskFilter] = useState<TaskStatus | 'all'>('all');
|
const [taskFilter, setTaskFilter] = useState<TaskStatus | 'all'>('all');
|
||||||
const [selectedTask, setSelectedTask] = useState<Task | null>(null);
|
const [selectedTask, setSelectedTask] = useState<Task | null>(null);
|
||||||
|
|
||||||
useEffect(() => {
|
const surface = combineFreshness(project.freshness, [missions.freshness, tasks.freshness]);
|
||||||
if (!id) {
|
const tasksVerified = tasks.freshness === 'current';
|
||||||
setError('Project id is missing.');
|
const projectMissions = missions.data?.filter((mission) => mission.projectId === id) ?? null;
|
||||||
setLoading(false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
let cancelled = false;
|
const retryAll = (): void => {
|
||||||
setLoading(true);
|
void Promise.all([project.revalidate(), missions.revalidate(), tasks.revalidate()]);
|
||||||
setError(null);
|
};
|
||||||
|
|
||||||
void Promise.all([
|
if (!enabled) {
|
||||||
api<Project>('/api/projects/' + id),
|
|
||||||
api<Mission[]>('/api/missions').catch(() => [] as Mission[]),
|
|
||||||
api<Task[]>('/api/tasks?projectId=' + id).catch(() => [] as Task[]),
|
|
||||||
])
|
|
||||||
.then(([loadedProject, allMissions, loadedTasks]) => {
|
|
||||||
if (cancelled) return;
|
|
||||||
setProject(loadedProject);
|
|
||||||
setMissions(allMissions.filter((mission) => mission.projectId === id));
|
|
||||||
setTasks(loadedTasks);
|
|
||||||
})
|
|
||||||
.catch((caught: unknown) => {
|
|
||||||
if (cancelled) return;
|
|
||||||
setError(getErrorMessage(caught, 'Failed to load project.'));
|
|
||||||
})
|
|
||||||
.finally(() => {
|
|
||||||
if (cancelled) return;
|
|
||||||
setLoading(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
cancelled = true;
|
|
||||||
};
|
|
||||||
}, [id]);
|
|
||||||
|
|
||||||
if (loading) {
|
|
||||||
return (
|
|
||||||
<div className="flex min-h-screen flex-col px-4 py-6 sm:px-6">
|
|
||||||
<header className="mb-6 border-b px-1 pb-3">
|
|
||||||
<h1 className="text-2xl font-semibold">Project</h1>
|
|
||||||
</header>
|
|
||||||
<p className="py-16 text-center text-sm text-text-muted">Loading project...</p>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (error || !project) {
|
|
||||||
return (
|
return (
|
||||||
<div className="flex min-h-screen flex-col px-4 py-6 sm:px-6">
|
<div className="flex min-h-screen flex-col px-4 py-6 sm:px-6">
|
||||||
<header className="mb-6 border-b px-1 pb-3">
|
<header className="mb-6 border-b px-1 pb-3">
|
||||||
<h1 className="text-2xl font-semibold">Project</h1>
|
<h1 className="text-2xl font-semibold">Project</h1>
|
||||||
</header>
|
</header>
|
||||||
<div role="alert" className="rounded-lg border border-error/40 px-4 py-3 text-sm">
|
<div role="alert" className="rounded-lg border border-error/40 px-4 py-3 text-sm">
|
||||||
{error ?? 'Project not found.'}
|
Project id is missing.
|
||||||
</div>
|
</div>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
@@ -130,18 +135,81 @@ export function ProjectDetailPage(): ReactElement {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (project.freshness === 'unknown') {
|
||||||
|
return (
|
||||||
|
<div className="flex min-h-screen flex-col px-4 py-6 sm:px-6">
|
||||||
|
<header className="mb-6 border-b px-1 pb-3">
|
||||||
|
<h1 className="text-2xl font-semibold">Project</h1>
|
||||||
|
</header>
|
||||||
|
<p className="py-16 text-center text-sm text-text-muted">Loading project...</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (project.freshness === 'unavailable' || project.data === null) {
|
||||||
|
return (
|
||||||
|
<div className="flex min-h-screen flex-col px-4 py-6 sm:px-6">
|
||||||
|
<header className="mb-6 border-b px-1 pb-3">
|
||||||
|
<h1 className="text-2xl font-semibold">Project</h1>
|
||||||
|
</header>
|
||||||
|
<UnavailableDataNotice
|
||||||
|
title="This project"
|
||||||
|
detail={describeFailure(project.failure)}
|
||||||
|
onRetry={retryAll}
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => navigate('/projects')}
|
||||||
|
className="mt-4 w-fit text-sm underline"
|
||||||
|
>
|
||||||
|
Back to projects
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const projectTasks = tasks.data ?? null;
|
||||||
const filteredTasks =
|
const filteredTasks =
|
||||||
taskFilter === 'all' ? tasks : tasks.filter((task) => task.status === taskFilter);
|
projectTasks === null
|
||||||
const prdContent = getPrdContent(project);
|
? []
|
||||||
|
: taskFilter === 'all'
|
||||||
|
? projectTasks
|
||||||
|
: projectTasks.filter((task) => task.status === taskFilter);
|
||||||
|
|
||||||
|
// Derived completion verdicts: unknown (never green) unless the task
|
||||||
|
// collection is verified current.
|
||||||
|
const doneCount = projectTasks?.filter((task) => task.status === 'done').length ?? 0;
|
||||||
|
const inProgressCount = projectTasks?.filter((task) => task.status === 'in-progress').length ?? 0;
|
||||||
|
const blockedCount = projectTasks?.filter((task) => task.status === 'blocked').length ?? 0;
|
||||||
|
|
||||||
|
const prdContent = getPrdContent(project.data);
|
||||||
const tabs: Array<{ id: Tab; label: string }> = [
|
const tabs: Array<{ id: Tab; label: string }> = [
|
||||||
{ id: 'overview', label: 'Overview' },
|
{ id: 'overview', label: 'Overview' },
|
||||||
{ id: 'tasks', label: `Tasks (${tasks.length})` },
|
{
|
||||||
{ id: 'missions', label: `Missions (${missions.length})` },
|
id: 'tasks',
|
||||||
|
label: `Tasks (${projectTasks === null ? UNKNOWN_VERDICT : projectTasks.length})`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'missions',
|
||||||
|
label: `Missions (${projectMissions === null ? UNKNOWN_VERDICT : projectMissions.length})`,
|
||||||
|
},
|
||||||
...(prdContent ? [{ id: 'prd' as const, label: 'PRD' }] : []),
|
...(prdContent ? [{ id: 'prd' as const, label: 'PRD' }] : []),
|
||||||
];
|
];
|
||||||
|
|
||||||
|
const staleSnapshot: FreshSnapshot<unknown> | null =
|
||||||
|
project.freshness === 'stale'
|
||||||
|
? project.snapshot
|
||||||
|
: missions.freshness === 'stale'
|
||||||
|
? missions.snapshot
|
||||||
|
: tasks.freshness === 'stale'
|
||||||
|
? tasks.snapshot
|
||||||
|
: null;
|
||||||
|
const missingSections: string[] = [];
|
||||||
|
if (missions.freshness === 'unavailable') missingSections.push('Missions');
|
||||||
|
if (tasks.freshness === 'unavailable') missingSections.push('Tasks');
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex min-h-screen flex-col px-4 py-6 sm:px-6">
|
<div data-freshness={surface} className="flex min-h-screen flex-col px-4 py-6 sm:px-6">
|
||||||
<header className="mb-6 border-b px-1 pb-3">
|
<header className="mb-6 border-b px-1 pb-3">
|
||||||
<nav className="mb-4 flex items-center gap-2 text-sm text-text-muted">
|
<nav className="mb-4 flex items-center gap-2 text-sm text-text-muted">
|
||||||
<button
|
<button
|
||||||
@@ -152,49 +220,64 @@ export function ProjectDetailPage(): ReactElement {
|
|||||||
Projects
|
Projects
|
||||||
</button>
|
</button>
|
||||||
<span>/</span>
|
<span>/</span>
|
||||||
<span className="text-text-primary">{project.name}</span>
|
<span className="text-text-primary">{project.data.name}</span>
|
||||||
</nav>
|
</nav>
|
||||||
|
|
||||||
<div className="flex items-start justify-between gap-4">
|
<div className="flex items-start justify-between gap-4">
|
||||||
<div>
|
<div>
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
<h1 className="text-2xl font-semibold text-text-primary">{project.name}</h1>
|
<h1 className="text-2xl font-semibold text-text-primary">{project.data.name}</h1>
|
||||||
<span
|
<span
|
||||||
className={cn(
|
className={cn(
|
||||||
'rounded-full px-2 py-0.5 text-xs',
|
'rounded-full px-2 py-0.5 text-xs',
|
||||||
projectStatusColors[project.status] ?? 'bg-gray-600/20 text-gray-400',
|
projectStatusColors[project.data.status] ?? 'bg-gray-600/20 text-gray-400',
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{project.status}
|
{project.data.status}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
{project.description ? (
|
{project.data.description ? (
|
||||||
<p className="mt-1 text-sm text-text-muted">{project.description}</p>
|
<p className="mt-1 text-sm text-text-muted">{project.data.description}</p>
|
||||||
) : null}
|
) : null}
|
||||||
<p className="mt-2 text-xs text-text-muted">
|
<p className="mt-2 text-xs text-text-muted">
|
||||||
Created {new Date(project.createdAt).toLocaleDateString()} · Updated{' '}
|
Created {new Date(project.data.createdAt).toLocaleDateString()} · Updated{' '}
|
||||||
{new Date(project.updatedAt).toLocaleDateString()}
|
{new Date(project.data.updatedAt).toLocaleDateString()}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
|
{staleSnapshot !== null ? (
|
||||||
|
<div className="mb-6">
|
||||||
|
<StaleDataNotice label={staleSnapshot} onRetry={retryAll} />
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{missingSections.length > 0 ? (
|
||||||
|
<div className="mb-6">
|
||||||
|
<PartialDataNotice missing={missingSections} onRetry={retryAll} />
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
<div className="mb-6 grid grid-cols-2 gap-3 sm:grid-cols-4">
|
<div className="mb-6 grid grid-cols-2 gap-3 sm:grid-cols-4">
|
||||||
<StatCard label="Tasks" value={String(tasks.length)} />
|
<StatCard
|
||||||
|
label="Tasks"
|
||||||
|
value={projectTasks === null ? UNKNOWN_VERDICT : String(projectTasks.length)}
|
||||||
|
/>
|
||||||
<StatCard
|
<StatCard
|
||||||
label="Done"
|
label="Done"
|
||||||
value={String(tasks.filter((task) => task.status === 'done').length)}
|
value={verdictValue(tasksVerified, String(doneCount))}
|
||||||
valueClass="text-success"
|
valueClass={tasksVerified ? 'text-success' : undefined}
|
||||||
/>
|
/>
|
||||||
<StatCard
|
<StatCard
|
||||||
label="In Progress"
|
label="In Progress"
|
||||||
value={String(tasks.filter((task) => task.status === 'in-progress').length)}
|
value={verdictValue(tasksVerified, String(inProgressCount))}
|
||||||
valueClass="text-blue-400"
|
valueClass={tasksVerified ? 'text-blue-400' : undefined}
|
||||||
/>
|
/>
|
||||||
<StatCard
|
<StatCard
|
||||||
label="Blocked"
|
label="Blocked"
|
||||||
value={String(tasks.filter((task) => task.status === 'blocked').length)}
|
value={verdictValue(tasksVerified, String(blockedCount))}
|
||||||
valueClass={tasks.some((task) => task.status === 'blocked') ? 'text-error' : undefined}
|
valueClass={tasksVerified && blockedCount > 0 ? 'text-error' : undefined}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -211,23 +294,43 @@ export function ProjectDetailPage(): ReactElement {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{activeTab === 'overview' ? (
|
{activeTab === 'overview' ? (
|
||||||
<OverviewTab project={project} missions={missions} tasks={tasks} />
|
<OverviewTab project={project.data} missions={projectMissions} tasks={projectTasks} />
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
{activeTab === 'tasks' ? (
|
{activeTab === 'tasks' ? (
|
||||||
<div>
|
<div>
|
||||||
<div className="mb-4">
|
{projectTasks === null ? (
|
||||||
<TaskStatusSummary
|
<UnavailableDataNotice
|
||||||
tasks={tasks}
|
title="Tasks"
|
||||||
activeFilter={taskFilter}
|
detail={describeFailure(tasks.failure)}
|
||||||
onFilterChange={setTaskFilter}
|
onRetry={retryAll}
|
||||||
/>
|
/>
|
||||||
</div>
|
) : (
|
||||||
<TaskListView tasks={filteredTasks} onTaskClick={setSelectedTask} />
|
<>
|
||||||
|
<div className="mb-4">
|
||||||
|
<TaskStatusSummary
|
||||||
|
tasks={projectTasks}
|
||||||
|
activeFilter={taskFilter}
|
||||||
|
onFilterChange={setTaskFilter}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<TaskListView tasks={filteredTasks} onTaskClick={setSelectedTask} />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
{activeTab === 'missions' ? <MissionTimeline missions={missions} /> : null}
|
{activeTab === 'missions' ? (
|
||||||
|
projectMissions === null ? (
|
||||||
|
<UnavailableDataNotice
|
||||||
|
title="Missions"
|
||||||
|
detail={describeFailure(missions.failure)}
|
||||||
|
onRetry={retryAll}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<MissionTimeline missions={projectMissions} />
|
||||||
|
)
|
||||||
|
) : null}
|
||||||
|
|
||||||
{activeTab === 'prd' && prdContent ? (
|
{activeTab === 'prd' && prdContent ? (
|
||||||
<div className="rounded-lg border border-surface-border bg-surface-card p-6">
|
<div className="rounded-lg border border-surface-border bg-surface-card p-6">
|
||||||
@@ -248,18 +351,26 @@ function OverviewTab({
|
|||||||
tasks,
|
tasks,
|
||||||
}: {
|
}: {
|
||||||
project: Project;
|
project: Project;
|
||||||
missions: Mission[];
|
missions: Mission[] | null;
|
||||||
tasks: Task[];
|
tasks: Task[] | null;
|
||||||
}): ReactElement {
|
}): ReactElement {
|
||||||
const recentTasks = [...tasks]
|
const recentTasks =
|
||||||
.sort((left, right) => new Date(right.updatedAt).getTime() - new Date(left.updatedAt).getTime())
|
tasks === null
|
||||||
.slice(0, 5);
|
? null
|
||||||
|
: [...tasks]
|
||||||
|
.sort(
|
||||||
|
(left, right) =>
|
||||||
|
new Date(right.updatedAt).getTime() - new Date(left.updatedAt).getTime(),
|
||||||
|
)
|
||||||
|
.slice(0, 5);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="grid gap-6 lg:grid-cols-2">
|
<div className="grid gap-6 lg:grid-cols-2">
|
||||||
<section>
|
<section>
|
||||||
<h2 className="mb-3 text-sm font-semibold text-text-secondary">Recent Tasks</h2>
|
<h2 className="mb-3 text-sm font-semibold text-text-secondary">Recent Tasks</h2>
|
||||||
{recentTasks.length === 0 ? (
|
{recentTasks === null ? (
|
||||||
|
<UnavailableDataNotice title="Tasks" />
|
||||||
|
) : recentTasks.length === 0 ? (
|
||||||
<div className="rounded-lg border border-surface-border bg-surface-card p-4 text-center">
|
<div className="rounded-lg border border-surface-border bg-surface-card p-4 text-center">
|
||||||
<p className="text-sm text-text-muted">No tasks yet</p>
|
<p className="text-sm text-text-muted">No tasks yet</p>
|
||||||
</div>
|
</div>
|
||||||
@@ -287,7 +398,9 @@ function OverviewTab({
|
|||||||
|
|
||||||
<section>
|
<section>
|
||||||
<h2 className="mb-3 text-sm font-semibold text-text-secondary">Missions</h2>
|
<h2 className="mb-3 text-sm font-semibold text-text-secondary">Missions</h2>
|
||||||
{missions.length === 0 ? (
|
{missions === null ? (
|
||||||
|
<UnavailableDataNotice title="Missions" />
|
||||||
|
) : missions.length === 0 ? (
|
||||||
<div className="rounded-lg border border-surface-border bg-surface-card p-4 text-center">
|
<div className="rounded-lg border border-surface-border bg-surface-card p-4 text-center">
|
||||||
<p className="text-sm text-text-muted">No missions yet</p>
|
<p className="text-sm text-text-muted">No missions yet</p>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -51,6 +51,7 @@ afterEach(async () => {
|
|||||||
document.body.replaceChildren();
|
document.body.replaceChildren();
|
||||||
root = null;
|
root = null;
|
||||||
apiMock.mockReset();
|
apiMock.mockReset();
|
||||||
|
sessionStorage.clear();
|
||||||
});
|
});
|
||||||
|
|
||||||
async function renderProjectsPage(): Promise<ReturnType<typeof createMemoryRouter>> {
|
async function renderProjectsPage(): Promise<ReturnType<typeof createMemoryRouter>> {
|
||||||
@@ -71,6 +72,22 @@ async function renderProjectsPage(): Promise<ReturnType<typeof createMemoryRoute
|
|||||||
return router;
|
return router;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function clickButtonByText(text: string): void {
|
||||||
|
const button = [...container.querySelectorAll('button')].find((candidate) =>
|
||||||
|
candidate.textContent?.includes(text),
|
||||||
|
);
|
||||||
|
if (!button) {
|
||||||
|
throw new Error(`Button containing "${text}" not found`);
|
||||||
|
}
|
||||||
|
button.dispatchEvent(new MouseEvent('click', { bubbles: true }));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function flushAct(): Promise<void> {
|
||||||
|
await act(async () => {
|
||||||
|
await Promise.resolve();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
describe('ProjectsPage', () => {
|
describe('ProjectsPage', () => {
|
||||||
it('shows a visible loading state while the project request is in flight', async () => {
|
it('shows a visible loading state while the project request is in flight', async () => {
|
||||||
const deferred = createDeferred<typeof projectFixtures>();
|
const deferred = createDeferred<typeof projectFixtures>();
|
||||||
@@ -91,7 +108,7 @@ describe('ProjectsPage', () => {
|
|||||||
|
|
||||||
const router = await renderProjectsPage();
|
const router = await renderProjectsPage();
|
||||||
|
|
||||||
expect(apiMock).toHaveBeenCalledWith('/api/projects');
|
expect(apiMock.mock.calls[0]?.[0]).toBe('/api/projects');
|
||||||
expect(container.textContent).toContain('Mosaic Stack');
|
expect(container.textContent).toContain('Mosaic Stack');
|
||||||
expect(container.textContent).toContain('Agent Runtime');
|
expect(container.textContent).toContain('Agent Runtime');
|
||||||
|
|
||||||
@@ -108,7 +125,7 @@ describe('ProjectsPage', () => {
|
|||||||
expect(container.textContent).toContain('Project detail target');
|
expect(container.textContent).toContain('Project detail target');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('renders the empty state when the API returns no projects', async () => {
|
it('renders the empty state only for a verified empty collection', async () => {
|
||||||
apiMock.mockResolvedValueOnce([]);
|
apiMock.mockResolvedValueOnce([]);
|
||||||
|
|
||||||
await renderProjectsPage();
|
await renderProjectsPage();
|
||||||
@@ -117,9 +134,12 @@ describe('ProjectsPage', () => {
|
|||||||
expect(container.textContent).toContain(
|
expect(container.textContent).toContain(
|
||||||
'Projects will appear here when created via the gateway API',
|
'Projects will appear here when created via the gateway API',
|
||||||
);
|
);
|
||||||
|
expect(container.querySelector('[data-freshness]')?.getAttribute('data-freshness')).toBe(
|
||||||
|
'current',
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('renders a visible alert when the projects request fails', async () => {
|
it('renders a failed fetch as an explicit unavailable state, never an empty collection', async () => {
|
||||||
apiMock.mockRejectedValueOnce(new Error('Projects are unavailable'));
|
apiMock.mockRejectedValueOnce(new Error('Projects are unavailable'));
|
||||||
|
|
||||||
await renderProjectsPage();
|
await renderProjectsPage();
|
||||||
@@ -127,5 +147,51 @@ describe('ProjectsPage', () => {
|
|||||||
const alert = container.querySelector('[role="alert"]');
|
const alert = container.querySelector('[role="alert"]');
|
||||||
expect(alert).toBeTruthy();
|
expect(alert).toBeTruthy();
|
||||||
expect(alert?.textContent).toContain('Projects are unavailable');
|
expect(alert?.textContent).toContain('Projects are unavailable');
|
||||||
|
expect(alert?.textContent).toContain('not an empty result');
|
||||||
|
|
||||||
|
// Negative controls: no healthy empty state and no project cards render
|
||||||
|
// from a failed fetch.
|
||||||
|
expect(container.textContent).not.toContain('No projects yet');
|
||||||
|
expect(container.textContent).not.toContain('Mosaic Stack');
|
||||||
|
expect(container.querySelector('[data-freshness]')?.getAttribute('data-freshness')).toBe(
|
||||||
|
'unavailable',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('renders an auth failure as unavailable and recovers after retry', async () => {
|
||||||
|
apiMock
|
||||||
|
.mockRejectedValueOnce(Object.assign(new Error('Unauthorized'), { statusCode: 401 }))
|
||||||
|
.mockResolvedValueOnce(projectFixtures);
|
||||||
|
|
||||||
|
await renderProjectsPage();
|
||||||
|
|
||||||
|
const alert = container.querySelector('[role="alert"]');
|
||||||
|
expect(alert?.textContent).toContain('Unauthorized');
|
||||||
|
expect(container.textContent).not.toContain('No projects yet');
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
clickButtonByText('Retry');
|
||||||
|
});
|
||||||
|
await flushAct();
|
||||||
|
|
||||||
|
expect(container.querySelector('[role="alert"]')).toBeNull();
|
||||||
|
expect(container.textContent).toContain('Mosaic Stack');
|
||||||
|
expect(container.querySelector('[data-freshness]')?.getAttribute('data-freshness')).toBe(
|
||||||
|
'current',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('renders a schema-mismatched response as unavailable, never as data', async () => {
|
||||||
|
apiMock.mockResolvedValueOnce({ results: projectFixtures });
|
||||||
|
|
||||||
|
await renderProjectsPage();
|
||||||
|
|
||||||
|
const alert = container.querySelector('[role="alert"]');
|
||||||
|
expect(alert?.textContent).toContain('not an empty result');
|
||||||
|
expect(container.textContent).not.toContain('Mosaic Stack');
|
||||||
|
expect(container.textContent).not.toContain('No projects yet');
|
||||||
|
expect(container.querySelector('[data-freshness]')?.getAttribute('data-freshness')).toBe(
|
||||||
|
'unavailable',
|
||||||
|
);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,53 +1,51 @@
|
|||||||
import { useEffect, useState, type ReactElement } from 'react';
|
import { type ReactElement } from 'react';
|
||||||
import { useNavigate } from 'react-router-dom';
|
import { useNavigate } from 'react-router-dom';
|
||||||
import { ProjectCard } from '@/components/projects/project-card';
|
import { ProjectCard } from '@/components/projects/project-card';
|
||||||
|
import { StaleDataNotice, UnavailableDataNotice } from '@/components/freshness/freshness-notices';
|
||||||
import { api } from '@/lib/api';
|
import { api } from '@/lib/api';
|
||||||
import type { Project } from '@/lib/types';
|
import type { Project } from '@/lib/types';
|
||||||
import { getErrorMessage } from './page-errors';
|
import { useFreshCollection, describeFailure } from '@/lib/freshness/use-fresh-collection';
|
||||||
|
import { validateProjectCollection } from '@/lib/freshness/validators';
|
||||||
|
|
||||||
export function ProjectsPage(): ReactElement {
|
export function ProjectsPage(): ReactElement {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const [projects, setProjects] = useState<Project[]>([]);
|
const projects = useFreshCollection<Project[]>({
|
||||||
const [loading, setLoading] = useState(true);
|
source: 'gateway:/api/projects',
|
||||||
const [error, setError] = useState<string | null>(null);
|
fetcher: (signal) => api<unknown>('/api/projects', { signal }),
|
||||||
|
validate: validateProjectCollection,
|
||||||
useEffect(() => {
|
// Projects carry workspace identity (userId) that is only knowable from
|
||||||
let cancelled = false;
|
// the payload itself, so a restored entry cannot be scope-checked before
|
||||||
|
// display. Conservative choice: no last-known restore for this surface;
|
||||||
void api<Project[]>('/api/projects')
|
// cross-workspace switching is still invalidated at verification time.
|
||||||
.then((response) => {
|
});
|
||||||
if (cancelled) return;
|
const retry = (): void => {
|
||||||
setProjects(response);
|
void projects.revalidate();
|
||||||
})
|
};
|
||||||
.catch((caught: unknown) => {
|
|
||||||
if (cancelled) return;
|
|
||||||
setError(getErrorMessage(caught, 'Failed to load projects.'));
|
|
||||||
})
|
|
||||||
.finally(() => {
|
|
||||||
if (cancelled) return;
|
|
||||||
setLoading(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
cancelled = true;
|
|
||||||
};
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex min-h-screen flex-col px-4 py-6 sm:px-6">
|
<div
|
||||||
|
data-freshness={projects.freshness}
|
||||||
|
className="flex min-h-screen flex-col px-4 py-6 sm:px-6"
|
||||||
|
>
|
||||||
<header className="mb-6 border-b px-1 pb-3">
|
<header className="mb-6 border-b px-1 pb-3">
|
||||||
<h1 className="text-2xl font-semibold">Projects</h1>
|
<h1 className="text-2xl font-semibold">Projects</h1>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
{error ? (
|
{projects.freshness === 'stale' && projects.snapshot ? (
|
||||||
<div role="alert" className="mb-6 rounded-lg border border-error/40 px-4 py-3 text-sm">
|
<div className="mb-6">
|
||||||
{error}
|
<StaleDataNotice label={projects.snapshot} onRetry={retry} />
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
{loading ? (
|
{projects.freshness === 'unknown' ? (
|
||||||
<p className="py-8 text-center text-sm text-text-muted">Loading projects...</p>
|
<p className="py-8 text-center text-sm text-text-muted">Loading projects...</p>
|
||||||
) : projects.length === 0 ? (
|
) : projects.freshness === 'unavailable' ? (
|
||||||
|
<UnavailableDataNotice
|
||||||
|
title="Projects"
|
||||||
|
detail={describeFailure(projects.failure)}
|
||||||
|
onRetry={retry}
|
||||||
|
/>
|
||||||
|
) : projects.data !== null && projects.data.length === 0 ? (
|
||||||
<div className="py-12 text-center">
|
<div className="py-12 text-center">
|
||||||
<h2 className="text-lg font-medium text-text-secondary">No projects yet</h2>
|
<h2 className="text-lg font-medium text-text-secondary">No projects yet</h2>
|
||||||
<p className="mt-1 text-sm text-text-muted">
|
<p className="mt-1 text-sm text-text-muted">
|
||||||
@@ -56,7 +54,7 @@ export function ProjectsPage(): ReactElement {
|
|||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
||||||
{projects.map((project) => (
|
{(projects.data ?? []).map((project) => (
|
||||||
<ProjectCard
|
<ProjectCard
|
||||||
key={project.id}
|
key={project.id}
|
||||||
project={project}
|
project={project}
|
||||||
|
|||||||
@@ -3,6 +3,9 @@ import { createRoot, type Root } from 'react-dom/client';
|
|||||||
import { createMemoryRouter, RouterProvider, type RouteObject } from 'react-router-dom';
|
import { createMemoryRouter, RouterProvider, type RouteObject } from 'react-router-dom';
|
||||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
|
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
|
||||||
import { taskFixtures } from './page-fixtures';
|
import { taskFixtures } from './page-fixtures';
|
||||||
|
import { acceptSnapshot, DEFAULT_FRESHNESS_POLICY } from '@/lib/freshness/model';
|
||||||
|
import { writeSnapshotCache } from '@/lib/freshness/snapshot-cache';
|
||||||
|
import { validateTaskCollection } from '@/lib/freshness/validators';
|
||||||
|
|
||||||
const { apiMock } = vi.hoisted(() => ({
|
const { apiMock } = vi.hoisted(() => ({
|
||||||
apiMock: vi.fn(),
|
apiMock: vi.fn(),
|
||||||
@@ -48,6 +51,7 @@ afterEach(async () => {
|
|||||||
document.body.replaceChildren();
|
document.body.replaceChildren();
|
||||||
root = null;
|
root = null;
|
||||||
apiMock.mockReset();
|
apiMock.mockReset();
|
||||||
|
sessionStorage.clear();
|
||||||
});
|
});
|
||||||
|
|
||||||
async function renderTasksPage(): Promise<void> {
|
async function renderTasksPage(): Promise<void> {
|
||||||
@@ -72,6 +76,13 @@ function clickButtonByText(text: string): void {
|
|||||||
button.dispatchEvent(new MouseEvent('click', { bubbles: true }));
|
button.dispatchEvent(new MouseEvent('click', { bubbles: true }));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Flush pending promise callbacks inside the act environment. */
|
||||||
|
async function flushAct(): Promise<void> {
|
||||||
|
await act(async () => {
|
||||||
|
await Promise.resolve();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
describe('TasksPage', () => {
|
describe('TasksPage', () => {
|
||||||
it('shows a visible loading state before the tasks request settles', async () => {
|
it('shows a visible loading state before the tasks request settles', async () => {
|
||||||
const deferred = createDeferred<typeof taskFixtures>();
|
const deferred = createDeferred<typeof taskFixtures>();
|
||||||
@@ -132,7 +143,7 @@ describe('TasksPage', () => {
|
|||||||
expect(container.textContent).toContain('Wire list and kanban modal interactions');
|
expect(container.textContent).toContain('Wire list and kanban modal interactions');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('renders a visible alert when the tasks request fails', async () => {
|
it('renders a failed fetch as an explicit unavailable state, never an empty healthy board', async () => {
|
||||||
apiMock.mockRejectedValueOnce(new Error('Tasks request failed'));
|
apiMock.mockRejectedValueOnce(new Error('Tasks request failed'));
|
||||||
|
|
||||||
await renderTasksPage();
|
await renderTasksPage();
|
||||||
@@ -140,5 +151,80 @@ describe('TasksPage', () => {
|
|||||||
const alert = container.querySelector('[role="alert"]');
|
const alert = container.querySelector('[role="alert"]');
|
||||||
expect(alert).toBeTruthy();
|
expect(alert).toBeTruthy();
|
||||||
expect(alert?.textContent).toContain('Tasks request failed');
|
expect(alert?.textContent).toContain('Tasks request failed');
|
||||||
|
expect(alert?.textContent).toContain('not an empty result');
|
||||||
|
|
||||||
|
// Negative controls: no board, no healthy empty-state markers, and the
|
||||||
|
// surface is marked unavailable rather than current.
|
||||||
|
expect(container.textContent).not.toContain('Not Started');
|
||||||
|
expect(container.textContent).not.toContain('No tasks');
|
||||||
|
expect(container.querySelector('[data-freshness]')?.getAttribute('data-freshness')).toBe(
|
||||||
|
'unavailable',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('recovers to a current board after retrying a failed fetch', async () => {
|
||||||
|
apiMock
|
||||||
|
.mockRejectedValueOnce(new Error('Tasks request failed'))
|
||||||
|
.mockResolvedValueOnce(taskFixtures);
|
||||||
|
|
||||||
|
await renderTasksPage();
|
||||||
|
expect(container.querySelector('[role="alert"]')).toBeTruthy();
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
clickButtonByText('Retry');
|
||||||
|
});
|
||||||
|
await flushAct();
|
||||||
|
|
||||||
|
expect(container.querySelector('[role="alert"]')).toBeNull();
|
||||||
|
expect(container.textContent).toContain('Not Started');
|
||||||
|
expect(container.querySelector('[data-freshness]')?.getAttribute('data-freshness')).toBe(
|
||||||
|
'current',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('labels restored last-known data as stale with source, version, and age until verified', async () => {
|
||||||
|
// Seed a last-known snapshot fetched five minutes ago; the page must
|
||||||
|
// render it only under an explicit staleness label while the fetch is
|
||||||
|
// still in flight.
|
||||||
|
const restored = acceptSnapshot({
|
||||||
|
value: taskFixtures,
|
||||||
|
validate: validateTaskCollection,
|
||||||
|
previous: null,
|
||||||
|
policy: DEFAULT_FRESHNESS_POLICY,
|
||||||
|
source: 'gateway:/api/tasks',
|
||||||
|
now: Date.now() - 5 * 60_000,
|
||||||
|
});
|
||||||
|
if (restored.outcome !== 'accepted') throw new Error('fixture setup failed');
|
||||||
|
writeSnapshotCache('tasks', restored.snapshot);
|
||||||
|
|
||||||
|
const deferred = createDeferred<typeof taskFixtures>();
|
||||||
|
apiMock.mockReturnValueOnce(deferred.promise);
|
||||||
|
|
||||||
|
await renderTasksPage();
|
||||||
|
|
||||||
|
expect(container.querySelector('[data-freshness]')?.getAttribute('data-freshness')).toBe(
|
||||||
|
'stale',
|
||||||
|
);
|
||||||
|
const banner = container.querySelector('[role="status"]');
|
||||||
|
expect(banner?.textContent).toContain('last-known');
|
||||||
|
expect(banner?.textContent).toContain('may be out of date');
|
||||||
|
expect(banner?.textContent).toContain('gateway:/api/tasks');
|
||||||
|
expect(banner?.textContent).toContain('snapshot v1');
|
||||||
|
expect(banner?.textContent).toContain('5m ago');
|
||||||
|
|
||||||
|
// Last-known data still renders as situational awareness under the label.
|
||||||
|
expect(container.textContent).toContain('Route /tasks');
|
||||||
|
expect(container.textContent).not.toContain('Loading tasks...');
|
||||||
|
|
||||||
|
// Verification lands: the banner clears and the surface becomes current.
|
||||||
|
await act(async () => {
|
||||||
|
deferred.resolve(taskFixtures);
|
||||||
|
await deferred.promise;
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(container.querySelector('[role="status"]')).toBeNull();
|
||||||
|
expect(container.querySelector('[data-freshness]')?.getAttribute('data-freshness')).toBe(
|
||||||
|
'current',
|
||||||
|
);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,45 +1,32 @@
|
|||||||
import { useEffect, useState, type ReactElement } from 'react';
|
import { useState, type ReactElement } from 'react';
|
||||||
import { KanbanBoard } from '@/components/tasks/kanban-board';
|
import { KanbanBoard } from '@/components/tasks/kanban-board';
|
||||||
import { TaskDetailModal } from '@/components/tasks/task-detail-modal';
|
import { TaskDetailModal } from '@/components/tasks/task-detail-modal';
|
||||||
import { TaskListView } from '@/components/tasks/task-list-view';
|
import { TaskListView } from '@/components/tasks/task-list-view';
|
||||||
|
import { StaleDataNotice, UnavailableDataNotice } from '@/components/freshness/freshness-notices';
|
||||||
import { api } from '@/lib/api';
|
import { api } from '@/lib/api';
|
||||||
import { cn } from '@/lib/cn';
|
import { cn } from '@/lib/cn';
|
||||||
import type { Task } from '@/lib/types';
|
import type { Task } from '@/lib/types';
|
||||||
import { getErrorMessage } from './page-errors';
|
import { useFreshCollection, describeFailure } from '@/lib/freshness/use-fresh-collection';
|
||||||
|
import { validateTaskCollection } from '@/lib/freshness/validators';
|
||||||
|
|
||||||
type ViewMode = 'list' | 'kanban';
|
type ViewMode = 'list' | 'kanban';
|
||||||
|
|
||||||
export function TasksPage(): ReactElement {
|
export function TasksPage(): ReactElement {
|
||||||
const [tasks, setTasks] = useState<Task[]>([]);
|
const tasks = useFreshCollection<Task[]>({
|
||||||
|
source: 'gateway:/api/tasks',
|
||||||
|
fetcher: (signal) => api<unknown>('/api/tasks', { signal }),
|
||||||
|
validate: validateTaskCollection,
|
||||||
|
cacheKey: 'tasks',
|
||||||
|
});
|
||||||
const [view, setView] = useState<ViewMode>('kanban');
|
const [view, setView] = useState<ViewMode>('kanban');
|
||||||
const [loading, setLoading] = useState(true);
|
|
||||||
const [error, setError] = useState<string | null>(null);
|
|
||||||
const [selectedTask, setSelectedTask] = useState<Task | null>(null);
|
const [selectedTask, setSelectedTask] = useState<Task | null>(null);
|
||||||
|
|
||||||
useEffect(() => {
|
const retry = (): void => {
|
||||||
let cancelled = false;
|
void tasks.revalidate();
|
||||||
|
};
|
||||||
void api<Task[]>('/api/tasks')
|
|
||||||
.then((response) => {
|
|
||||||
if (cancelled) return;
|
|
||||||
setTasks(response);
|
|
||||||
})
|
|
||||||
.catch((caught: unknown) => {
|
|
||||||
if (cancelled) return;
|
|
||||||
setError(getErrorMessage(caught, 'Failed to load tasks.'));
|
|
||||||
})
|
|
||||||
.finally(() => {
|
|
||||||
if (cancelled) return;
|
|
||||||
setLoading(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
cancelled = true;
|
|
||||||
};
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex min-h-screen flex-col px-4 py-6 sm:px-6">
|
<div data-freshness={tasks.freshness} className="flex min-h-screen flex-col px-4 py-6 sm:px-6">
|
||||||
<header className="mb-6 flex items-center justify-between gap-4 border-b px-1 pb-3">
|
<header className="mb-6 flex items-center justify-between gap-4 border-b px-1 pb-3">
|
||||||
<h1 className="text-2xl font-semibold">Tasks</h1>
|
<h1 className="text-2xl font-semibold">Tasks</h1>
|
||||||
<div className="flex rounded-lg border border-surface-border">
|
<div className="flex rounded-lg border border-surface-border">
|
||||||
@@ -70,18 +57,24 @@ export function TasksPage(): ReactElement {
|
|||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
{error ? (
|
{tasks.freshness === 'stale' && tasks.snapshot ? (
|
||||||
<div role="alert" className="mb-6 rounded-lg border border-error/40 px-4 py-3 text-sm">
|
<div className="mb-6">
|
||||||
{error}
|
<StaleDataNotice label={tasks.snapshot} onRetry={retry} />
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
{loading ? (
|
{tasks.freshness === 'unknown' ? (
|
||||||
<p className="py-8 text-center text-sm text-text-muted">Loading tasks...</p>
|
<p className="py-8 text-center text-sm text-text-muted">Loading tasks...</p>
|
||||||
|
) : tasks.freshness === 'unavailable' ? (
|
||||||
|
<UnavailableDataNotice
|
||||||
|
title="Tasks"
|
||||||
|
detail={describeFailure(tasks.failure)}
|
||||||
|
onRetry={retry}
|
||||||
|
/>
|
||||||
) : view === 'kanban' ? (
|
) : view === 'kanban' ? (
|
||||||
<KanbanBoard tasks={tasks} onTaskClick={setSelectedTask} />
|
<KanbanBoard tasks={tasks.data ?? []} onTaskClick={setSelectedTask} />
|
||||||
) : (
|
) : (
|
||||||
<TaskListView tasks={tasks} onTaskClick={setSelectedTask} />
|
<TaskListView tasks={tasks.data ?? []} onTaskClick={setSelectedTask} />
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{selectedTask ? (
|
{selectedTask ? (
|
||||||
|
|||||||
+246
@@ -1,5 +1,14 @@
|
|||||||
# PRD: Mosaic Stack v0.1.0
|
# PRD: Mosaic Stack v0.1.0
|
||||||
|
|
||||||
|
## Current addendum: #1194 — Installed framework-tool drift detection
|
||||||
|
|
||||||
|
- Compare the framework tools shipped with the executing Mosaic package against the deployed `$MOSAIC_HOME/tools` tree by content hash.
|
||||||
|
- Treat every shipped `tools/**` file as framework-owned/required according to `framework-manifest.txt`, while excluding the explicit operator-owned credential carve-out and preserving installed-only operator/unknown files.
|
||||||
|
- Distinguish and count `IN_SYNC`, `STALE`, `NOT_INSTALLED`, and installed-only classifications; fail non-zero when shipped tools are stale or absent and refuse self-comparison that would make drift unobservable.
|
||||||
|
- Surface the observational check through `mosaic doctor`; do not refresh files, restart seats, or mutate live tooling.
|
||||||
|
- Document identity/messaging/gate behavior changes in the current stale set, the reviewed quiet-window keep-mode refresh command, and post-refresh probes against the installed path.
|
||||||
|
- Prove by construction that a stale and missing deployed tool are detected; that regression must fail before this checker exists.
|
||||||
|
|
||||||
## Metadata
|
## Metadata
|
||||||
|
|
||||||
- **Owner:** Jason Woltje
|
- **Owner:** Jason Woltje
|
||||||
@@ -102,6 +111,128 @@ Context compaction, session replacement, and same-PID runtime reloads can leave
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## Pi Persistent Goal Loop (#1150)
|
||||||
|
|
||||||
|
### Problem and objective
|
||||||
|
|
||||||
|
A Pi agent can stop after a plausible-looking answer even when the operator's broader objective is
|
||||||
|
not complete, and ordinary compaction can weaken or omit the original objective. Mosaic needs an
|
||||||
|
optional, operator-controlled goal loop that keeps a Pi session oriented, checks progress at native
|
||||||
|
lifecycle boundaries, and resumes work until completion is verified or a bounded safety state is
|
||||||
|
reached.
|
||||||
|
|
||||||
|
The objective is a Mosaic-owned Pi extension deployed from the framework into
|
||||||
|
`~/.config/mosaic/runtime/pi/`. It must not install into or depend on `~/.pi/agent/extensions/`.
|
||||||
|
|
||||||
|
### Scope
|
||||||
|
|
||||||
|
#### In scope
|
||||||
|
|
||||||
|
1. `PGL-REQ-01`: The framework SHALL ship a dedicated Pi goal extension under
|
||||||
|
`packages/mosaic/framework/runtime/pi/`, seed it under `$MOSAIC_HOME/runtime/pi/`, and make
|
||||||
|
`mosaic pi` load it alongside the core Mosaic extension when present.
|
||||||
|
2. `PGL-REQ-02`: `/goal` SHALL support setting a goal plus status, pause, resume, cancel, and help
|
||||||
|
operations without silently replacing an active goal.
|
||||||
|
3. `PGL-REQ-03`: Active branch-specific goal state SHALL be persisted in Pi custom session entries,
|
||||||
|
restored on session start and tree navigation, and never rely on a compaction summary as its
|
||||||
|
source of truth.
|
||||||
|
4. `PGL-REQ-04`: A hidden goal contract SHALL be injected through Pi's `context` event before every
|
||||||
|
model request so it remains effective across tool turns, retries, and post-compaction requests.
|
||||||
|
5. `PGL-REQ-05`: The harness SHALL inspect every `turn_end` and successful `session_compact` event.
|
||||||
|
A structured terminating goal-report tool SHALL capture `continue`, evidence-bearing `achieved`,
|
||||||
|
or `blocked` status without requiring a redundant model turn.
|
||||||
|
6. `PGL-REQ-06`: An achievement claim SHALL remain provisional until a second consecutive
|
||||||
|
evidence-bearing verification report. Any continuation report or successful compaction during
|
||||||
|
verification SHALL reset the verification sequence.
|
||||||
|
7. `PGL-REQ-07`: Continuation SHALL be initiated at safe lifecycle boundaries, primarily
|
||||||
|
`agent_settled`; manual compaction and restored active sessions may schedule a deferred idle
|
||||||
|
continuation without re-entering compaction handlers.
|
||||||
|
8. `PGL-REQ-08`: The loop SHALL have operator cancellation plus bounded turn and repeated-no-progress
|
||||||
|
limits. Exhausted or blocked goals pause rather than continuing indefinitely.
|
||||||
|
9. `PGL-REQ-09`: Framework installation and update SHALL preserve normal manifest ownership: the
|
||||||
|
goal extension is framework-owned under `runtime/**`, while no goal extension or configuration
|
||||||
|
asset is created or modified under the operator's main Pi configuration. Pi remains the owner of
|
||||||
|
its native session files used by `appendEntry()`.
|
||||||
|
|
||||||
|
#### Out of scope
|
||||||
|
|
||||||
|
1. A mathematical guarantee that an arbitrary natural-language goal is semantically complete.
|
||||||
|
2. Automatically executing user-supplied shell predicates or accepting executable validation code in
|
||||||
|
`/goal` arguments.
|
||||||
|
3. Restarting Pi after process, host, or supervisor failure; the existing Mosaic fleet/runtime
|
||||||
|
supervisor owns process durability.
|
||||||
|
4. Gateway, database, web UI, Discord, or cross-harness goal orchestration in this slice.
|
||||||
|
|
||||||
|
### User and stakeholder requirements
|
||||||
|
|
||||||
|
- An operator can start a goal from Pi and see its current phase, evidence, limits, and latest report.
|
||||||
|
- The agent remains oriented after each turn and compaction until verified, paused, blocked,
|
||||||
|
exhausted, or cancelled.
|
||||||
|
- Local testing uses a file under `~/.config/mosaic/runtime/pi/`; the feature never writes an
|
||||||
|
extension asset to `~/.pi/agent/extensions/`.
|
||||||
|
- Framework updates deploy the same reviewed extension source through Mosaic's existing manifest
|
||||||
|
sync path.
|
||||||
|
|
||||||
|
### Non-functional requirements
|
||||||
|
|
||||||
|
1. **Safety:** bounded continuation, explicit cancellation, no arbitrary command execution, and no
|
||||||
|
completion without non-empty reported evidence.
|
||||||
|
2. **Reliability:** serialized continuation scheduling, branch-aware restoration, compaction-safe
|
||||||
|
context injection, and stale-timer cancellation on session shutdown.
|
||||||
|
3. **Performance:** no extra nested judge-model request on every turn; structured reporting uses the
|
||||||
|
active agent's final terminating tool call.
|
||||||
|
4. **Observability:** Pi status/notifications expose phase and bounded counters without recording
|
||||||
|
credentials or hidden model reasoning.
|
||||||
|
5. **Maintainability:** the state machine is deterministic and behavior-tested independently from Pi
|
||||||
|
provider/network access.
|
||||||
|
|
||||||
|
### Acceptance criteria
|
||||||
|
|
||||||
|
1. `AC-PGL-01`: A framework-sync fixture installs the extension at
|
||||||
|
`$MOSAIC_HOME/runtime/pi/goal-extension.ts`, and launcher tests prove both Mosaic Pi extensions are
|
||||||
|
emitted in deterministic order while absent optional files remain backward-compatible.
|
||||||
|
2. `AC-PGL-02`: Command tests prove set/status/pause/resume/cancel behavior, active-goal replacement
|
||||||
|
refusal, and bounded input handling.
|
||||||
|
3. `AC-PGL-03`: Lifecycle tests prove every turn is recorded, active context is injected on every
|
||||||
|
request, two evidence-bearing achievement reports are required, and `agent_settled` continues an
|
||||||
|
unmet goal without duplicate scheduling.
|
||||||
|
4. `AC-PGL-04`: Compaction and restoration tests prove goal state survives, verification is reset and
|
||||||
|
rechecked after compaction, manual compaction continuation is deferred until idle, and tree/session
|
||||||
|
branch state is reconstructed correctly.
|
||||||
|
5. `AC-PGL-05`: Limit tests prove max-turn and repeated-no-progress exhaustion stop autonomous
|
||||||
|
continuation, while pause/cancel/blocked states do not restart.
|
||||||
|
6. `AC-PGL-06`: Focused tests, package typecheck/lint/test, repository quality gates, a local Pi load
|
||||||
|
smoke test from `~/.config/mosaic/runtime/pi/`, independent review, and terminal-green CI pass before
|
||||||
|
issue #1150 closes.
|
||||||
|
|
||||||
|
### Constraints, risks, and assumptions
|
||||||
|
|
||||||
|
- Dependency: Pi's extension API must continue to provide `registerCommand`, `registerTool`,
|
||||||
|
`context`, `turn_end`, `agent_settled`, `session_compact`, session custom entries, and terminating
|
||||||
|
tool results.
|
||||||
|
- Risk: the working agent can overstate completion. Mitigation: structured evidence, a mandatory
|
||||||
|
second verification pass, explicit semantic limitations, and operator-visible reports.
|
||||||
|
- Risk: an impossible goal can consume unbounded resources. Mitigation: hard turn/no-progress bounds
|
||||||
|
and paused terminal states.
|
||||||
|
- Risk: automatic continuation can race compaction or session replacement. Mitigation: drive from
|
||||||
|
`agent_settled`, defer idle restarts, generation-check timers, and clear timers on shutdown.
|
||||||
|
- `ASSUMPTION:` Two consecutive evidence-bearing reports are the initial local verification policy;
|
||||||
|
rationale: it provides a real recheck without doubling every turn's model cost. Future policy may
|
||||||
|
add independent or deterministic validators.
|
||||||
|
- `ASSUMPTION:` Default limits are 40 turns and 6 repeated no-progress reports, configurable only by
|
||||||
|
bounded Mosaic environment settings; rationale: useful persistence with a finite autonomous budget.
|
||||||
|
- `ASSUMPTION:` Documentation remains canonical in-repo for this slice; no external docs publication
|
||||||
|
is requested.
|
||||||
|
|
||||||
|
### Testing and delivery intent
|
||||||
|
|
||||||
|
Use TDD for the deterministic controller and lifecycle invariants. Test with fake Pi lifecycle
|
||||||
|
objects first, then run a local load/smoke test from the deployed Mosaic path. Deliver source, tests,
|
||||||
|
launcher wiring, framework/runtime documentation, user/developer guides, and sitemap updates in one
|
||||||
|
reviewed squash PR to `main` with terminal-green CI.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## Fleet Declarative Configuration Management Workstream (FCM, #758)
|
## Fleet Declarative Configuration Management Workstream (FCM, #758)
|
||||||
|
|
||||||
### Problem and objective
|
### Problem and objective
|
||||||
@@ -146,6 +277,68 @@ lands. M0 consists only of these normative requirements, the complete task DAG,
|
|||||||
documentation IA checklist, and the legacy example/profile disposition inventory. Subsequent cards
|
documentation IA checklist, and the legacy example/profile disposition inventory. Subsequent cards
|
||||||
are defined in [docs/TASKS.md](./TASKS.md) and must remain one card/one PR.
|
are defined in [docs/TASKS.md](./TASKS.md) and must remain one card/one PR.
|
||||||
|
|
||||||
|
### Fleet git identity launch propagation (#1043)
|
||||||
|
|
||||||
|
#### Problem and objective
|
||||||
|
|
||||||
|
A fleet seat can have a registered per-agent Git credential while its launched runtime process lacks
|
||||||
|
`MOSAIC_GIT_IDENTITY`. The credential resolver then cannot select the seat identity reliably, which
|
||||||
|
blocks repository operations on fail-closed estates and can fall through to an unrelated identity on
|
||||||
|
estates where that refusal is not active. The objective is to make Git identity a deterministic,
|
||||||
|
roster-derived part of the generated launch projection and prove it reaches the launched process.
|
||||||
|
|
||||||
|
#### Normative requirements
|
||||||
|
|
||||||
|
1. `FGI-REQ-01`: Every generated fleet agent projection SHALL declare
|
||||||
|
`MOSAIC_GIT_IDENTITY=<MOSAIC_AGENT_NAME>`; a differing or unsafe identity SHALL fail closed before
|
||||||
|
tmux launch.
|
||||||
|
2. `FGI-REQ-02`: The clean `/usr/bin/env -i` pane boundary SHALL pass every variable declared by the
|
||||||
|
generated projection, including `MOSAIC_GIT_IDENTITY`, to the launched runtime process.
|
||||||
|
3. `FGI-REQ-03`: A behavioral integration test SHALL set-compare the complete generated projection
|
||||||
|
against the launched process environment. Source-text/string-presence assertions are insufficient.
|
||||||
|
4. `FGI-REQ-04`: Verification SHALL include RED-first evidence and a delete-the-subject mutation that
|
||||||
|
removes Git-identity pane propagation and makes the behavioral test fail.
|
||||||
|
|
||||||
|
#### Acceptance criteria
|
||||||
|
|
||||||
|
1. `AC-FGI-01`: A launched seat process contains every key/value pair declared by its generated
|
||||||
|
environment projection, including the roster-derived Git identity.
|
||||||
|
2. `AC-FGI-02`: Missing, unsafe, or split Git identity is rejected before a tmux session is created.
|
||||||
|
3. `AC-FGI-03`: Focused launcher and generated-environment tests, repository quality gates,
|
||||||
|
independent review, and the required RED/green/R7 evidence are recorded before push.
|
||||||
|
|
||||||
|
### Framework shell assertion portability (#1098)
|
||||||
|
|
||||||
|
#### Problem and objective
|
||||||
|
|
||||||
|
The blocking framework-shell chain can report that a pane command omitted `/usr/bin/env -i` even when
|
||||||
|
`-i` matched successfully. A short-circuiting `grep -q` under `set -o pipefail` may close its pipe after
|
||||||
|
the match and cause an upstream producer to exit with SIGPIPE, turning a valid semantic result into a
|
||||||
|
nonzero aggregate pipeline. The objective is to inspect the captured NUL-delimited argv directly and
|
||||||
|
make failures carry the observed records needed for diagnosis.
|
||||||
|
|
||||||
|
#### Normative requirements
|
||||||
|
|
||||||
|
1. `FSP-REQ-01`: The pane-boundary test SHALL validate an adjacent `/usr/bin/env`, `-i` argv pair from
|
||||||
|
the authoritative NUL-delimited tmux capture without a short-circuit pipeline whose upstream status
|
||||||
|
can override a successful match.
|
||||||
|
2. `FSP-REQ-02`: Missing, reversed, or non-adjacent boundary tokens SHALL fail, while valid boundaries
|
||||||
|
SHALL remain valid regardless of trailing argv size, pipe capacity, process scheduling, or host/CI
|
||||||
|
utility implementation.
|
||||||
|
3. `FSP-REQ-03`: A failed boundary check SHALL print stable indexed, shell-escaped observed argv records
|
||||||
|
before exiting nonzero; the fixture SHALL continue to contain generated non-secret launch data only.
|
||||||
|
4. `FSP-REQ-04`: Verification SHALL include RED-first large-payload evidence, negative token-order
|
||||||
|
controls, the complete focused launcher suite, canonical Woodpecker CI, and independent review.
|
||||||
|
|
||||||
|
#### Acceptance criteria
|
||||||
|
|
||||||
|
1. `AC-FSP-01`: A large captured argv with adjacent `/usr/bin/env`, `-i` passes even when the former
|
||||||
|
`grep -q` pipeline returns nonzero from an upstream SIGPIPE.
|
||||||
|
2. `AC-FSP-02`: Missing executable, missing flag, and detached/reversed flag fixtures return nonzero and
|
||||||
|
emit the indexed observed argv.
|
||||||
|
3. `AC-FSP-03`: The focused suite passes on the development host and CI image, and the merged-main
|
||||||
|
Woodpecker pipeline is terminal green before #1098 closes.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Exact Cross-Harness Fleet Communications Contract (#766)
|
## Exact Cross-Harness Fleet Communications Contract (#766)
|
||||||
@@ -1345,6 +1538,59 @@ All work is **alpha** (< 0.1.0) until Jason approves 0.1.0 beta release.
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## Workspace placement guard hardening (#1174)
|
||||||
|
|
||||||
|
### Problem and objective
|
||||||
|
|
||||||
|
The Bash pre-tool guard must prevent Git checkouts and repository state from being placed under
|
||||||
|
`$HOME` without refusing ordinary Git commands merely because a source, option value, branch name,
|
||||||
|
or metadata mentions `$HOME`. A guard that over-blocks routine work is unsafe because operators
|
||||||
|
will route around it.
|
||||||
|
|
||||||
|
### Scope and requirements
|
||||||
|
|
||||||
|
1. `WPG-REQ-01`: `git clone` and `git worktree add` placement SHALL be judged from their placement
|
||||||
|
operands, not from every HOME-shaped word in the command.
|
||||||
|
2. `WPG-REQ-02`: Clone sources, references, templates, environment assignments, and non-placement
|
||||||
|
worktree metadata MAY resolve under HOME when all placement operands resolve elsewhere.
|
||||||
|
3. `WPG-REQ-03`: Both attached and separate-value `--separate-git-dir` forms SHALL remain placement
|
||||||
|
operands and SHALL be refused when they resolve under HOME.
|
||||||
|
4. `WPG-REQ-04`: Option classification SHALL account for Git's rule-generated boolean negations
|
||||||
|
without relying on an enumerable allowlist of flag spellings.
|
||||||
|
5. `WPG-REQ-05`: Quote removal, escapes, shell command boundaries, redirections, and end-of-options
|
||||||
|
handling SHALL preserve existing fail-closed checkout coverage.
|
||||||
|
6. `WPG-REQ-06`: Absolute placement aliases SHALL resolve shell-known HOME spellings, dot segments,
|
||||||
|
repeated separators, and existing symlink parents before the HOME boundary comparison.
|
||||||
|
7. Relative targets whose effective path depends on the shell cwd are out of scope and tracked by
|
||||||
|
#1197.
|
||||||
|
|
||||||
|
### Acceptance and verification
|
||||||
|
|
||||||
|
1. Git's own option parser accepts each tested flag, including generated `--no-*` forms, while the
|
||||||
|
guard allows a HOME-valued source with an explicit safe destination.
|
||||||
|
2. Equivalent clone and worktree fixtures cover rule-generated negations and remain discriminating
|
||||||
|
against the prior head where the defect existed.
|
||||||
|
3. Real HOME destinations and both `--separate-git-dir` forms remain blocked, including placements
|
||||||
|
after shell command boundaries.
|
||||||
|
4. The full hermetic guard suite, syntax/static checks, adversarial probes, independent review, and
|
||||||
|
terminal-green CI pass before merge.
|
||||||
|
5. Any option-classification residual is documented with its deliberate failure direction.
|
||||||
|
|
||||||
|
### Constraints, risks, and assumptions
|
||||||
|
|
||||||
|
- Security and usability are co-equal: neither a placement bypass nor routine over-block is an
|
||||||
|
acceptable repair.
|
||||||
|
- `ASSUMPTION:` The value-taking option surface exposed by the installed Git version is closed and
|
||||||
|
measurable through Git's own parser/help output; rationale: boolean flags are rule-generated,
|
||||||
|
while separate-value options have explicit grammar and must be classified as such.
|
||||||
|
- Risk: a future Git release may add a new value-taking placement option. Mitigation: document the
|
||||||
|
chosen residual direction and pin every currently supported placement option in behavior tests.
|
||||||
|
- Risk: a symlink can be replaced after pre-execution canonicalization. Mitigation: resolve every
|
||||||
|
existing parent physically and document the remaining inherent TOCTOU window; the worktree helper
|
||||||
|
remains the authoritative path-derivation mechanism, with atomic closure tracked by #1199.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## Assumptions
|
## Assumptions
|
||||||
|
|
||||||
1. RESOLVED: **pgvector is sufficient** for semantic search at v0.1.0 scale (personal/family/team = thousands to low hundreds-of-thousands of vectors). `@mosaicstack/memory` defines a `VectorStore` interface with pgvector as the default adapter. The interface boundary makes Qdrant a drop-in migration if PG resource contention or scale demands it later. Zero additional infrastructure for v0.1.0. Rationale: Reduces ops burden; pgvector HNSW indexes are fast at this scale; interface abstraction costs almost nothing now.
|
1. RESOLVED: **pgvector is sufficient** for semantic search at v0.1.0 scale (personal/family/team = thousands to low hundreds-of-thousands of vectors). `@mosaicstack/memory` defines a `VectorStore` interface with pgvector as the default adapter. The interface boundary makes Qdrant a drop-in migration if PG resource contention or scale demands it later. Zero additional infrastructure for v0.1.0. Rationale: Reduces ops burden; pgvector HNSW indexes are fast at this scale; interface abstraction costs almost nothing now.
|
||||||
|
|||||||
+15
-1
@@ -1,5 +1,19 @@
|
|||||||
# Tasks — MVP (Top-Level Rollup)
|
# Tasks — MVP (Top-Level Rollup)
|
||||||
|
|
||||||
|
> ---
|
||||||
|
>
|
||||||
|
> **STATUS: SUPERSEDED — 2026-08-20.** kind `tracking` · superseded by `docs/fleet/NORTH_STAR.yaml`
|
||||||
|
>
|
||||||
|
> This file is the pre-backlog tracking mechanism. `NS-2` in the north star declares the
|
||||||
|
> replacement: every backlog item is a Mosaic Backlog card projected from the YAML. That
|
||||||
|
> model replaced this one and nobody retired the old file, so it kept reading as
|
||||||
|
> authoritative while going stale.
|
||||||
|
>
|
||||||
|
> **Do not trust a status in this file.** Verified 2026-08-20: it was already behind the
|
||||||
|
> code when it froze five weeks ago.
|
||||||
|
>
|
||||||
|
> Kept as a record of what was believed. Do not update it; update the YAML.
|
||||||
|
|
||||||
> Single-writer: orchestrator only. Workers read but never modify.
|
> Single-writer: orchestrator only. Workers read but never modify.
|
||||||
>
|
>
|
||||||
> **Mission:** mvp-20260312
|
> **Mission:** mvp-20260312
|
||||||
@@ -108,7 +122,7 @@ Active workstream is **W1 — Federation v1**. Workers should:
|
|||||||
|
|
||||||
## north-star doctrine consolidation — doc PR — feat/north-star-doctrine
|
## north-star doctrine consolidation — doc PR — feat/north-star-doctrine
|
||||||
|
|
||||||
- Status: applied Mos's consolidated merge-map to docs/fleet/north-star.md (budget governance + control plane/central register + 200k cap + delegation + unified-identity Fleet + role-based naming + tmux security + drift re-captures). Doctrine only; #622/#623/#625/#628 out-of-scope. Conflict checklist green. Detail: scratchpads/north-star-doctrine.md.
|
- Status: applied Mos's consolidated merge-map to docs/fleet/FLEET-DOCTRINE.md (budget governance + control plane/central register + 200k cap + delegation + unified-identity Fleet + role-based naming + tmux security + drift re-captures). Doctrine only; #622/#623/#625/#628 out-of-scope. Conflict checklist green. Detail: scratchpads/north-star-doctrine.md.
|
||||||
|
|
||||||
## #631 — re-seed preserves user fleet data (CRITICAL) — fix/631-reseed-preserves-fleet-data
|
## #631 — re-seed preserves user fleet data (CRITICAL) — fix/631-reseed-preserves-fleet-data
|
||||||
|
|
||||||
|
|||||||
@@ -7,7 +7,8 @@
|
|||||||
3. [Provider Configuration](#provider-configuration)
|
3. [Provider Configuration](#provider-configuration)
|
||||||
4. [MCP Server Configuration](#mcp-server-configuration)
|
4. [MCP Server Configuration](#mcp-server-configuration)
|
||||||
5. [Environment Variables Reference](#environment-variables-reference)
|
5. [Environment Variables Reference](#environment-variables-reference)
|
||||||
6. [Local Fleet Canary](./fleet-local-canary.md)
|
6. [Pi Goal Loop Operations](#pi-goal-loop-operations)
|
||||||
|
7. [Local Fleet Canary](./fleet-local-canary.md)
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -264,6 +265,16 @@ Each OIDC provider requires its client ID, client secret, and issuer URL togethe
|
|||||||
| `AGENT_SYSTEM_PROMPT` | — | Platform-level system prompt injected into all sessions |
|
| `AGENT_SYSTEM_PROMPT` | — | Platform-level system prompt injected into all sessions |
|
||||||
| `AGENT_USER_TOOLS` | all tools | Comma-separated allowlist of tools for non-admin users |
|
| `AGENT_USER_TOOLS` | all tools | Comma-separated allowlist of tools for non-admin users |
|
||||||
|
|
||||||
|
### Mosaic Pi goal loop
|
||||||
|
|
||||||
|
| Variable | Default | Description |
|
||||||
|
| ----------------------------- | ------- | -------------------------------------------------------------------- |
|
||||||
|
| `MOSAIC_GOAL_MAX_TURNS` | `40` | Per-goal autonomous turn limit; accepted range `1..500` |
|
||||||
|
| `MOSAIC_GOAL_MAX_NO_PROGRESS` | `6` | Consecutive identical progress-report limit; accepted range `1..100` |
|
||||||
|
|
||||||
|
These variables are consumed by the framework-owned Pi goal extension at goal creation. Invalid or
|
||||||
|
out-of-range values fall back to the defaults; they do not disable the bounds.
|
||||||
|
|
||||||
### Providers
|
### Providers
|
||||||
|
|
||||||
| Variable | Default | Description |
|
| Variable | Default | Description |
|
||||||
@@ -374,3 +385,29 @@ Session cleanup is scoped to one session identifier and only removes that sessio
|
|||||||
| Variable | Default | Description |
|
| Variable | Default | Description |
|
||||||
| ----------------------- | ----------------------------- | ------------------------------------------ |
|
| ----------------------- | ----------------------------- | ------------------------------------------ |
|
||||||
| `MOSAIC_WORKSPACE_ROOT` | monorepo root (auto-detected) | Root path for mission workspace operations |
|
| `MOSAIC_WORKSPACE_ROOT` | monorepo root (auto-detected) | Root path for mission workspace operations |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Pi Goal Loop Operations
|
||||||
|
|
||||||
|
The reviewed runtime asset is deployed at
|
||||||
|
`~/.config/mosaic/runtime/pi/goal-extension.ts` by framework install/update. Do not install another
|
||||||
|
copy under `~/.pi/agent/extensions/`; duplicate registration can create suffixed commands and two
|
||||||
|
competing lifecycle controllers.
|
||||||
|
|
||||||
|
Operational checks:
|
||||||
|
|
||||||
|
1. Run `mosaic pi` and verify `/goal help` is available.
|
||||||
|
2. Use `/goal status` to inspect phase, turn/no-progress limits, compaction checks, and evidence.
|
||||||
|
Reports persist in Pi session data; controller-owned state redacts common credential shapes, but
|
||||||
|
Pi's model/tool-call history is separate. Operators must not place secrets or raw sensitive output
|
||||||
|
in goals, pause reasons, or evidence.
|
||||||
|
3. Use `/goal pause <reason>` before planned maintenance or manual investigation. Pause and cancel
|
||||||
|
abort the current goal-driven run when Pi is busy.
|
||||||
|
4. Use `/goal resume` only after addressing a blocker; counters restart with the configured bounds.
|
||||||
|
5. Use `/goal cancel` before replacing an unfinished goal.
|
||||||
|
|
||||||
|
A blocked or exhausted goal remains stopped and visible; Mosaic does not automatically raise its
|
||||||
|
limits or restart the process. Framework sync owns file deployment, while Pi's native session file
|
||||||
|
owns branch replay. Process/host restart remains the responsibility of the existing runtime or fleet
|
||||||
|
supervisor.
|
||||||
|
|||||||
@@ -8,9 +8,10 @@
|
|||||||
4. [Tasks](#tasks)
|
4. [Tasks](#tasks)
|
||||||
5. [Settings](#settings)
|
5. [Settings](#settings)
|
||||||
6. [CLI Usage](#cli-usage)
|
6. [CLI Usage](#cli-usage)
|
||||||
7. [Sub-package Commands](#sub-package-commands)
|
7. [Pi Persistent Goals](#pi-persistent-goals)
|
||||||
8. [Telemetry](#telemetry)
|
8. [Sub-package Commands](#sub-package-commands)
|
||||||
9. [Local Fleet Canary](./fleet-local-canary.md)
|
9. [Telemetry](#telemetry)
|
||||||
|
10. [Local Fleet Canary](./fleet-local-canary.md)
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -317,6 +318,57 @@ mosaic prdy
|
|||||||
mosaic quality-rails
|
mosaic quality-rails
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Pi Persistent Goals
|
||||||
|
|
||||||
|
`mosaic pi` loads a Mosaic-owned goal extension from
|
||||||
|
`~/.config/mosaic/runtime/pi/goal-extension.ts`. It is deliberately not installed in
|
||||||
|
`~/.pi/agent/extensions/`; framework installation and updates manage it with the rest of the Mosaic
|
||||||
|
runtime assets.
|
||||||
|
|
||||||
|
Start Pi, then set a goal:
|
||||||
|
|
||||||
|
```text
|
||||||
|
/goal set Deliver the feature, tests, documentation, and verification evidence
|
||||||
|
# Shorthand:
|
||||||
|
/goal Deliver the feature, tests, documentation, and verification evidence
|
||||||
|
```
|
||||||
|
|
||||||
|
Control and inspect the loop with:
|
||||||
|
|
||||||
|
| Command | Behavior |
|
||||||
|
| ---------------------- | ------------------------------------------------------------------ |
|
||||||
|
| `/goal status` | Show phase, limits, compaction checks, latest report, and evidence |
|
||||||
|
| `/goal pause [reason]` | Stop autonomous continuation while preserving the goal |
|
||||||
|
| `/goal resume` | Resume with fresh turn and no-progress counters |
|
||||||
|
| `/goal cancel` | Cancel the goal and remove its active status |
|
||||||
|
| `/goal help` | Show command help |
|
||||||
|
|
||||||
|
While a goal is active, Mosaic injects its contract before every Pi model request and checks every
|
||||||
|
completed model/tool turn. The agent ends each work cycle with the structured
|
||||||
|
`mosaic_goal_report` tool. `achieved` is provisional until a second consecutive report rechecks the
|
||||||
|
whole goal with evidence. A continuation report or a successful compaction resets provisional
|
||||||
|
verification.
|
||||||
|
|
||||||
|
Goal statements and reports are stored in Pi session data. Mosaic redacts common credential shapes
|
||||||
|
before appending its goal-state entries and before goal tool output or `/goal status`, but
|
||||||
|
pattern-based redaction is not a secret store. Pi's own model-message and tool-call records are
|
||||||
|
outside that redactor. Never put tokens, passwords, private keys, connection strings, or raw
|
||||||
|
sensitive output in a goal or report; cite the command, artifact, and pass/fail result instead.
|
||||||
|
|
||||||
|
The loop stops instead of running forever when it is paused, blocked, cancelled, verified, reaches
|
||||||
|
its turn limit, or repeats the same no-progress report too many times. Defaults are 40 turns and 6
|
||||||
|
repeated no-progress reports. Operators may lower or raise them within enforced bounds before
|
||||||
|
launching Pi:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
MOSAIC_GOAL_MAX_TURNS=60 MOSAIC_GOAL_MAX_NO_PROGRESS=8 mosaic pi
|
||||||
|
```
|
||||||
|
|
||||||
|
Goal state is branch-specific Pi session data. It survives compaction and session resume, but Pi's
|
||||||
|
process still must be relaunched or supervised after a process/host failure. This initial verifier
|
||||||
|
checks structured evidence twice; it cannot mathematically prove every arbitrary natural-language
|
||||||
|
goal. Use explicit acceptance criteria and inspect `/goal status` for consequential work.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### Claude Code Skill Registration
|
### Claude Code Skill Registration
|
||||||
|
|||||||
@@ -1,5 +1,21 @@
|
|||||||
# Tasks — Federation v1
|
# Tasks — Federation v1
|
||||||
|
|
||||||
|
> ---
|
||||||
|
>
|
||||||
|
> **STATUS: SUPERSEDED — 2026-08-20.** kind `tracking` · superseded by `docs/fleet/NORTH_STAR.yaml`
|
||||||
|
>
|
||||||
|
> This file is the pre-backlog tracking mechanism. `NS-2` in the north star declares the
|
||||||
|
> replacement: every backlog item is a Mosaic Backlog card projected from the YAML. That
|
||||||
|
> model replaced this one and nobody retired the old file, so it kept reading as
|
||||||
|
> authoritative while going stale.
|
||||||
|
>
|
||||||
|
> **Do not trust a status in this file.** Verified 2026-08-20: it was already behind the
|
||||||
|
> code when it froze five weeks ago. `FED-M3-06` is marked not-started and `get.controller.ts`
|
||||||
|
> has existed for eight weeks; `FED-M3-10/11` claim no tests exist while fifteen spec files
|
||||||
|
> do. `FED-M2-DEPLOY-IMG-FIX` names `apps/gateway/Dockerfile`, which is not in the repo.
|
||||||
|
>
|
||||||
|
> Kept as a record of what was believed. Do not update it; update the YAML.
|
||||||
|
|
||||||
> Single-writer: orchestrator only. Workers read but never modify.
|
> Single-writer: orchestrator only. Workers read but never modify.
|
||||||
>
|
>
|
||||||
> **Mission:** federation-v1-20260419
|
> **Mission:** federation-v1-20260419
|
||||||
|
|||||||
@@ -1,9 +1,26 @@
|
|||||||
# Mosaic Fleet — North Star
|
---
|
||||||
|
kind: spec
|
||||||
|
parent: docs/fleet/NORTH_STAR.yaml
|
||||||
|
status: active
|
||||||
|
---
|
||||||
|
|
||||||
|
# Mosaic Fleet — Doctrine
|
||||||
|
|
||||||
|
> **This is the WHY. `NORTH_STAR.yaml` is the WHAT and WHEN.**
|
||||||
|
> Renamed from `north-star.md` on 2026-08-20. It sat one character away from the
|
||||||
|
> generated `NORTH_STAR.md` in the same directory, and the two are read by different
|
||||||
|
> populations — the PRDs and TASKS files cite this one, while the agent role contracts
|
||||||
|
> and the generator spec cite the YAML pair. Same-name-different-thing was the confusion;
|
||||||
|
> the content was never in conflict.
|
||||||
|
>
|
||||||
|
> **Nothing here overrides `NORTH_STAR.yaml`.** Where this document states a plan item,
|
||||||
|
> the YAML is authoritative. Where it states a decision, a rationale, or a role
|
||||||
|
> definition, this document is the record and the YAML carries none of it.
|
||||||
|
>
|
||||||
> **Workstream:** W-FLEET (Fleet) under mission `mvp-20260312`
|
> **Workstream:** W-FLEET (Fleet) under mission `mvp-20260312`
|
||||||
> **Umbrella:** [docs/MISSION-MANIFEST.md](../MISSION-MANIFEST.md) · [docs/PRD.md](../PRD.md) (Mosaic Stack v0.1.0)
|
> **Umbrella:** [docs/MISSION-MANIFEST.md](../MISSION-MANIFEST.md)
|
||||||
> **Status:** doctrine — authored 2026-06-20. Owner of this file: Fleet workstream lead.
|
> **Authored:** 2026-06-20. Owner: Fleet workstream lead.
|
||||||
> This document does **not** modify the MVP rollup; a rollup row is proposed, not written here.
|
> This document does **not** modify the MVP rollup.
|
||||||
|
|
||||||
## Vision
|
## Vision
|
||||||
|
|
||||||
@@ -264,15 +281,17 @@ Dedicated Postgres **instance** vs. dedicated **schema** in the existing instanc
|
|||||||
Recommendation: dedicated schema, existing instance (a migration file, not new infra);
|
Recommendation: dedicated schema, existing instance (a migration file, not new infra);
|
||||||
re-evaluate if isolation or write-volume demands it.
|
re-evaluate if isolation or write-volume demands it.
|
||||||
|
|
||||||
## Phased roadmap
|
## Phased roadmap — SUPERSEDED
|
||||||
|
|
||||||
| Phase | Outcome | Status |
|
Superseded 2026-08-20 by [`NORTH_STAR.yaml`](./NORTH_STAR.yaml), whose `goals` carry both
|
||||||
| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- |
|
a `phase` (build order) and a `tier` (which promise the goal delivers). The five-phase
|
||||||
| 0–1 | tmux PoC, hardening, published CLI v0.0.34 (#565–#568) | ✅ done |
|
table that stood here could not express those as separate axes, and its "Phase 2 —
|
||||||
| **2 — Observability** | fleet ps (host+tenant aware join), heartbeat protocol + dogfood stub answers it, agent watch (read-only), agent send --verify receipts | ▶ now |
|
Observability ▶ now" row stayed unfalsified for two months because a phase has no exit
|
||||||
| 3 — Real runtimes | claude/codex/pi/opencode answer heartbeat; **hybrid lifecycle** (core always-on: **orchestrator + enhancer**; ephemeral workers per lane) | planned |
|
test. Tiers do: see `AC-NS-0` through `AC-NS-7`.
|
||||||
| 4 — Unified definition | one agent schema in gateway; mosaic agent --new → materialized per-tenant session; uid-tenant provisioning; **`fleet` schema migration + `forge-exec` TaskExecutor adapter (forge → `agent-send.sh`)** | planned |
|
|
||||||
| 5 — Control plane | federation-backed cross-host × cross-tenant fleet view; **webUI** (surface chosen then) for MVP-X1 parity; **central register live (spend ledger, docs-as-projections, multi-host Kanban)** | planned |
|
The phase-2 content itself is not lost — it is specified in
|
||||||
|
[`PRD.md`](./PRD.md) (Fleet Phase 2: Operator Observability) and is now tracked as
|
||||||
|
goals `I1`–`I5` at tier 0.
|
||||||
|
|
||||||
## Decisions of record (2026-06-20, with Jason)
|
## Decisions of record (2026-06-20, with Jason)
|
||||||
|
|
||||||
+13
-10
@@ -5,14 +5,14 @@ Generated environment files are rebuildable projections, not an operator-editabl
|
|||||||
|
|
||||||
## Launch chain
|
## Launch chain
|
||||||
|
|
||||||
| Layer | Responsibility |
|
| Layer | Responsibility |
|
||||||
| ------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
|
| ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||||
| Roster | `fleet/roster.yaml` supplies the agent name, class, supported runtime, model, reasoning, tool policy, workdir, and tmux socket. |
|
| Roster | `fleet/roster.yaml` supplies the agent name, class, supported runtime, model, reasoning, tool policy, workdir, and tmux socket; Git identity is derived from the exact agent name. |
|
||||||
| Projection writer | Renders deterministic fleet/agents/<name>.env.generated from the roster. |
|
| Projection writer | Renders deterministic fleet/agents/<name>.env.generated from the roster. |
|
||||||
| Optional local data | Reads a strict, data-only fleet/agents/<name>.env.local; it cannot shadow generated keys. |
|
| Optional local data | Reads a strict, data-only fleet/agents/<name>.env.local; it cannot shadow generated keys. |
|
||||||
| systemd | Starts the launcher with env -i and fixed bootstrap data. It does not preload either environment file. |
|
| systemd | Starts the launcher with env -i and fixed bootstrap data. It does not preload either environment file. |
|
||||||
| session launcher | Validates generated and local data before it queries, creates, or stops an exact tmux session. |
|
| session launcher | Validates generated and local data before it queries, creates, or stops an exact tmux session. |
|
||||||
| runtime launch | Derives the fixed mosaic yolo <runtime> argument array from validated roster data, then seeds the runtime contract. |
|
| runtime launch | Derives the fixed mosaic yolo <runtime> argument array from validated roster data, then seeds the runtime contract. |
|
||||||
|
|
||||||
The launcher never `source`s or `eval`s an environment file and never accepts an environment-supplied
|
The launcher never `source`s or `eval`s an environment file and never accepts an environment-supplied
|
||||||
command. `MOSAIC_AGENT_COMMAND`, command/channel overrides, unknown keys, generated-key shadowing,
|
command. `MOSAIC_AGENT_COMMAND`, command/channel overrides, unknown keys, generated-key shadowing,
|
||||||
@@ -24,6 +24,7 @@ secret-like key names, duplicate keys, comments, quoted/export syntax, and unsaf
|
|||||||
|
|
||||||
```dotenv
|
```dotenv
|
||||||
MOSAIC_AGENT_NAME=<roster name>
|
MOSAIC_AGENT_NAME=<roster name>
|
||||||
|
MOSAIC_GIT_IDENTITY=<roster name>
|
||||||
MOSAIC_AGENT_CLASS=<roster class>
|
MOSAIC_AGENT_CLASS=<roster class>
|
||||||
MOSAIC_AGENT_RUNTIME=<roster runtime>
|
MOSAIC_AGENT_RUNTIME=<roster runtime>
|
||||||
MOSAIC_AGENT_MODEL=<roster model hint>
|
MOSAIC_AGENT_MODEL=<roster model hint>
|
||||||
@@ -33,8 +34,10 @@ MOSAIC_AGENT_WORKDIR=<absolute roster work directory>
|
|||||||
MOSAIC_TMUX_SOCKET=<roster socket or empty>
|
MOSAIC_TMUX_SOCKET=<roster socket or empty>
|
||||||
```
|
```
|
||||||
|
|
||||||
The generated launch contract supports `claude`, `codex`, `opencode`, and `pi`. mosaic fleet add
|
`MOSAIC_GIT_IDENTITY` is not independently configurable: it must equal `MOSAIC_AGENT_NAME`, preventing
|
||||||
rejects another runtime before it writes the roster or modifies generated, local, or quarantine state.
|
split runtime and repository identity authority. The generated launch contract supports `claude`,
|
||||||
|
`codex`, `opencode`, and `pi`. mosaic fleet add rejects another runtime before it writes the roster or
|
||||||
|
modifies generated, local, or quarantine state.
|
||||||
The legacy dogfood stub remains an observability-only canary on its separate `mosaic-factory` socket;
|
The legacy dogfood stub remains an observability-only canary on its separate `mosaic-factory` socket;
|
||||||
it has no generated-launch adapter and cannot be added through this path.
|
it has no generated-launch adapter and cannot be added through this path.
|
||||||
|
|
||||||
|
|||||||
+45
-25
@@ -3,7 +3,7 @@
|
|||||||
> **Generated file — do not edit by hand.**
|
> **Generated file — do not edit by hand.**
|
||||||
> Projected deterministically from [`NORTH_STAR.yaml`](./NORTH_STAR.yaml) by the pure
|
> Projected deterministically from [`NORTH_STAR.yaml`](./NORTH_STAR.yaml) by the pure
|
||||||
> generator in `packages/mosaic/src/commands/fleet.ts` (`renderNorthStarMarkdown`).
|
> generator in `packages/mosaic/src/commands/fleet.ts` (`renderNorthStarMarkdown`).
|
||||||
> Edit the YAML, then regenerate. Self-contained Mosaic — no Hermes dependency.
|
> Edit the YAML, then regenerate. Self-contained Mosaic.
|
||||||
|
|
||||||
## Mission
|
## Mission
|
||||||
|
|
||||||
@@ -11,7 +11,7 @@ A self-driving Mosaic system that 24/7 unattended converts a machine-readable go
|
|||||||
|
|
||||||
## Substrate
|
## Substrate
|
||||||
|
|
||||||
The Mosaic Backlog is the backlog of record + dispatch engine, built on Mosaic's native Postgres storage service (@mosaicstack/db drizzle; PGlite-embedded by default, full Postgres by config). NOT Hermes.
|
The Mosaic Backlog is the backlog of record + dispatch engine, built on Mosaic's native Postgres storage service (@mosaicstack/db drizzle; PGlite-embedded by default, full Postgres by config).
|
||||||
|
|
||||||
## Standing objectives
|
## Standing objectives
|
||||||
|
|
||||||
@@ -24,16 +24,18 @@ The Mosaic Backlog is the backlog of record + dispatch engine, built on Mosaic's
|
|||||||
- **NS-7** — Meta-loop (session-review + enhancer) continuously proposes small fleet-improvement PRs.
|
- **NS-7** — Meta-loop (session-review + enhancer) continuously proposes small fleet-improvement PRs.
|
||||||
- **NS-8** — Single operator-flippable PAUSE kill-switch (fleet/run/PAUSED) honored before every dispatch and every merge.
|
- **NS-8** — Single operator-flippable PAUSE kill-switch (fleet/run/PAUSED) honored before every dispatch and every merge.
|
||||||
- **NS-9** — Mosaic is a general-purpose multi-agent system: the user declares the SYSTEM TYPE to run (e.g. software delivery, personal assistant, research, business/operations) and the orchestrator provisions the matching persona roster and org structure from a cross-domain baseline persona library; the delivery/coding fleet is one profile among many.
|
- **NS-9** — Mosaic is a general-purpose multi-agent system: the user declares the SYSTEM TYPE to run (e.g. software delivery, personal assistant, research, business/operations) and the orchestrator provisions the matching persona roster and org structure from a cross-domain baseline persona library; the delivery/coding fleet is one profile among many.
|
||||||
|
- **NS-10** — An adoption is not complete until the mechanism it replaces is removed. Two live conventions for one concern is the defect, not a transition state. Measured 2026-08-20: brain-home adopted by 9 modules and not 10; MOSAIC_HOME honored in 4 places, each re-deriving it; backlog cards declared while TASKS.md files stayed authoritative. Every one was decided correctly and left half-applied.
|
||||||
|
|
||||||
## Success criteria
|
## Success criteria
|
||||||
|
|
||||||
- **AC-NS-1** — The supervisor keeps a two-agent floor (1 orchestrator + >=1 enhancer) healthy across reboot.
|
- **AC-NS-0** (tier 0) — The operator launches an agent on any configured harness with one command, observes its state and sends it work without attaching to a terminal multiplexer.
|
||||||
- **AC-NS-2** — A goal added to this YAML is decomposed to cards and either merged or escalated, with no human in the loop.
|
- **AC-NS-1** (tier 1) — The supervisor keeps a two-agent floor (1 orchestrator + >=1 enhancer) healthy across reboot.
|
||||||
- **AC-NS-3** — No PR merges with failure/error/no-status/timeout CI, and none bypass pr-merge.sh.
|
- **AC-NS-2** (tier 1) — A goal added to this YAML is decomposed to cards and either merged or escalated, with no human in the loop.
|
||||||
- **AC-NS-4** — TTL is enforced on claims; token caps remain advisory until a real meter exists.
|
- **AC-NS-3** (tier 1) — No PR merges with failure/error/no-status/timeout CI, and none bypass pr-merge.sh.
|
||||||
- **AC-NS-5** — Flipping fleet/run/PAUSED halts dispatch and merges within one tick.
|
- **AC-NS-4** (tier 1) — TTL is enforced on claims; token caps remain advisory until a real meter exists.
|
||||||
- **AC-NS-6** — A user can declare a system type and the fleet provisions the matching persona roster + topology from the baseline library, with no code change.
|
- **AC-NS-5** (tier 1) — Flipping fleet/run/PAUSED halts dispatch and merges within one tick.
|
||||||
- **AC-NS-7** — A user-customized persona (edited or added via the orchestrator) survives mosaic update: baseline reseed never clobbers user overrides.
|
- **AC-NS-6** (tier 2) — A user can declare a system type and the fleet provisions the matching persona roster + topology from the baseline library, with no code change.
|
||||||
|
- **AC-NS-7** (tier 2) — A user-customized persona (edited or added via the orchestrator) survives mosaic update: baseline reseed never clobbers user overrides.
|
||||||
|
|
||||||
## Workstreams
|
## Workstreams
|
||||||
|
|
||||||
@@ -45,26 +47,44 @@ The Mosaic Backlog is the backlog of record + dispatch engine, built on Mosaic's
|
|||||||
| D | Merge-gate — single approver, pr-merge.sh after CI wait |
|
| D | Merge-gate — single approver, pr-merge.sh after CI wait |
|
||||||
| E | Meta-loop — session-review + enhancer improvement PRs |
|
| E | Meta-loop — session-review + enhancer improvement PRs |
|
||||||
| F | Safety-rails — TTL claims, advisory spend, PAUSE kill-switch |
|
| F | Safety-rails — TTL claims, advisory spend, PAUSE kill-switch |
|
||||||
|
| G | Kill-switch — operator PAUSE honored before dispatch and merge |
|
||||||
| H | Personas & system profiles — cross-domain library, system-type provisioning, update-surviving customization |
|
| H | Personas & system profiles — cross-domain library, system-type provisioning, update-surviving customization |
|
||||||
|
| I | Operator surface — launcher, fleet visibility, reliable steering (tier 0) |
|
||||||
|
| J | Web control plane — browser surface over the gateway (tier 1) |
|
||||||
|
| K | Clients — desktop and mobile over the same backend (tier 2) |
|
||||||
|
| L | Auth profiles — per-provider accounts, per-session selection (tier 2) |
|
||||||
|
|
||||||
## Goals (backlog projection)
|
## Goals (backlog projection)
|
||||||
|
|
||||||
| id | title | phase | priority | depends_on |
|
| id | title | tier | phase | priority | depends_on |
|
||||||
| --- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ----- | ----------- | ---------- |
|
| --- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---- | ----- | ----------- | -------------- |
|
||||||
| A1 | Machine-readable NORTH_STAR.yaml + Markdown projection | 1 | must-have | — |
|
| A1 | Machine-readable NORTH_STAR.yaml + Markdown projection | 1 | 1 | must-have | — |
|
||||||
| A2 | Mosaic Backlog schema + storage-service card store (drizzle/PGlite) | 1 | must-have | A1 |
|
| A2 | Mosaic Backlog schema + storage-service card store (drizzle/PGlite) | 1 | 1 | must-have | A1 |
|
||||||
| A3a | Card lifecycle — create/claim/release with stable ids + depends_on DAG | 1 | must-have | A2 |
|
| A3a | Card lifecycle — create/claim/release with stable ids + depends_on DAG | 1 | 1 | must-have | A2 |
|
||||||
| A3b | TTL-bounded claim enforcement (wall-clock) on cards | 1 | must-have | A3a |
|
| A3b | TTL-bounded claim enforcement (wall-clock) on cards | 1 | 1 | must-have | A3a |
|
||||||
| A4 | Advisory spend projection per card (degrades to TTL, no real meter) | 1 | should-have | A3a |
|
| A4 | Advisory spend projection per card (degrades to TTL, no real meter) | 1 | 1 | should-have | A3a |
|
||||||
| B1 | Supervisor tick — readiness scan, two-agent-floor health check | 2 | must-have | A3a |
|
| B1 | Supervisor tick — readiness scan, two-agent-floor health check | 1 | 2 | must-have | A3a |
|
||||||
| B2 | Native dispatch/claim — assign ready dependency-satisfied work | 2 | must-have | A3b, B1 |
|
| B2 | Native dispatch/claim — assign ready dependency-satisfied work | 1 | 2 | must-have | A3b, B1 |
|
||||||
| B3a | Planner decompose — goal added to YAML → cards | 2 | must-have | A2, B1 |
|
| B3a | Planner decompose — goal added to YAML → cards | 1 | 2 | must-have | A2, B1 |
|
||||||
| B3b | Replan request on empty backlog; escalate on no-decompose | 2 | should-have | B3a |
|
| B3b | Replan request on empty backlog; escalate on no-decompose | 1 | 2 | should-have | B3a |
|
||||||
| G1 | PAUSE kill-switch + merge-gate honored before dispatch and merge | 2 | must-have | B2 |
|
| G1 | PAUSE kill-switch + merge-gate honored before dispatch and merge | 1 | 2 | must-have | B2 |
|
||||||
| H1 | Cross-domain baseline persona library (exec, marketing, ops, research, assistant + engineering roles) | 1 | must-have | A1 |
|
| H1 | Cross-domain baseline persona library (exec, marketing, ops, research, assistant + engineering roles) | 2 | 1 | must-have | A1 |
|
||||||
| H2 | System-type profiles — declarative mapping of system type to persona roster + topology | 2 | must-have | H1 |
|
| H2 | System-type profiles — declarative mapping of system type to persona roster + topology | 2 | 2 | must-have | H1 |
|
||||||
| H3 | System-type provisioning — user declares type; orchestrator instantiates the matching roster + structure | 2 | must-have | H2 |
|
| H3 | System-type provisioning — user declares type; orchestrator instantiates the matching roster + structure | 2 | 2 | must-have | H2 |
|
||||||
| H4 | Update-surviving persona customization — ad-hoc edits/additions persisted in a PRESERVE-protected override layer (baseline merged with overrides) | 2 | must-have | H1 |
|
| H4 | Update-surviving persona customization — ad-hoc edits/additions persisted in a PRESERVE-protected override layer (baseline merged with overrides) | 2 | 2 | must-have | H1 |
|
||||||
|
| A5 | NORTH_STAR schema validator — every goal's workstream declared, every workstream has a goal, every depends_on id exists, every tier has a success criterion; runs in CI beside the Markdown regeneration check | 0 | 1 | must-have | A1 |
|
||||||
|
| I1 | One home resolver — a single function resolving MOSAIC_HOME with a sane default, adopted by every module. Today brain-home.ts is imported by 9 modules while 10 still use DEFAULT_MOSAIC_HOME, and MOSAIC_HOME is re-derived ad hoc in 4 places. NS-10 applies - finish the adoption and delete the second path | 0 | 1 | must-have | — |
|
||||||
|
| I2 | mosaic fleet ps sees the fleet that is actually running. Three measured blockers: the roster declares socket `mosaic-fleet` which does not exist, the 18 live sessions are on the default socket, and nothing writes a roster because seats are launched outside the CLI. Make the socket configurable and the roster written at launch, or make ps read tmux + seat dirs directly | 0 | 1 | must-have | I1 |
|
||||||
|
| I3 | Migrate fleet steering onto mosaic agent send --verify (exists, FLEET-OBS-005, spec FR-5) and retire tools/tmux/agent-send.sh, which forges the sender (D33) and returns an uninformative rc (D16, D34). FR-5 predates those defects by a month | 0 | 1 | must-have | I1 |
|
||||||
|
| I4 | mosaic fleet absorbs what launch-seat.sh does and launch-seat.sh is deprecated: compose the prompt file set, force the skill set, wire the style hook, fail closed on any unreadable input, export per-seat git identity, and register the seat in the roster. launch-seat.sh was a manual method; it is the reference implementation, not the destination | 0 | 1 | must-have | I1, I5 |
|
||||||
|
| I5 | Harness probe matrix — verify a working prompt-injection path for claude, codex, opencode and pi, and refuse any runtime whose path is unverified. AC-NS-0 clause 1 ("any configured harness") rests on this. The probe work in docs/plans/2026-08-19_launch-seat-multi-runtime.md (brain, untracked) transfers; its launch-seat.sh target does not | 0 | 1 | must-have | — |
|
||||||
|
| I6 | Finish the heartbeat responder (FLEET-OBS-002, the only Phase-2 task still in-progress; spec FR-2). Health must mean "answered a heartbeat", not "pane alive" — pane state measured two seats wrong on 2026-08-20 | 0 | 1 | must-have | — |
|
||||||
|
| I7 | Independent review and live-fleet dogfood of the Phase-2 verbs (FLEET-OBS-008), then land them (FLEET-OBS-009). Implementation is done and verification is not; "done" in a task file frozen five weeks is not evidence | 0 | 1 | must-have | I2, I3, I4, I6 |
|
||||||
|
| I8 | Neutralize misleading documentation — supersede headers on docs that state a stale status, a false blocker or a retired mechanism. Cheap, and it is tier 0 because a stale doc does not merely fail to help an agent, it actively misroutes one. Rebuilding the documentation is a separate and later job | 0 | 1 | must-have | — |
|
||||||
|
| I9 | Study t3code's agent-attach and multi-provider auth methods and record what transfers. Reference only — Mosaic implements its own within the stack, never adopts the code and never takes the dependency. Informs HOW I/J/K/L are built, not whether | 0 | 1 | should-have | — |
|
||||||
|
| J1 | Web control plane over the gateway — fleet visibility and steering in a browser, same data source as I2 | 1 | 3 | must-have | I2 |
|
||||||
|
| K1 | Desktop and mobile clients against the gateway, authenticated | 2 | 4 | must-have | J1 |
|
||||||
|
| L1 | Per-provider auth profiles with per-session selection | 2 | 4 | must-have | I4 |
|
||||||
|
|
||||||
## Assumptions (vetoable)
|
## Assumptions (vetoable)
|
||||||
|
|
||||||
|
|||||||
+129
-2
@@ -6,7 +6,7 @@
|
|||||||
# packages/mosaic/src/commands/fleet.ts (renderNorthStarMarkdown). Edit the YAML,
|
# packages/mosaic/src/commands/fleet.ts (renderNorthStarMarkdown). Edit the YAML,
|
||||||
# never the .md.
|
# never the .md.
|
||||||
#
|
#
|
||||||
# Self-contained Mosaic. NO Hermes runtime dependency. The backlog of record is
|
# Self-contained Mosaic. The backlog of record is
|
||||||
# the Mosaic Backlog on Mosaic's OWN native Postgres storage service.
|
# the Mosaic Backlog on Mosaic's OWN native Postgres storage service.
|
||||||
|
|
||||||
version: 1
|
version: 1
|
||||||
@@ -24,7 +24,7 @@ substrate:
|
|||||||
note: >-
|
note: >-
|
||||||
The Mosaic Backlog is the backlog of record + dispatch engine, built on
|
The Mosaic Backlog is the backlog of record + dispatch engine, built on
|
||||||
Mosaic's native Postgres storage service (@mosaicstack/db drizzle;
|
Mosaic's native Postgres storage service (@mosaicstack/db drizzle;
|
||||||
PGlite-embedded by default, full Postgres by config). NOT Hermes.
|
PGlite-embedded by default, full Postgres by config).
|
||||||
|
|
||||||
standing_objectives:
|
standing_objectives:
|
||||||
- id: NS-1
|
- id: NS-1
|
||||||
@@ -69,32 +69,53 @@ standing_objectives:
|
|||||||
business/operations) and the orchestrator provisions the matching persona
|
business/operations) and the orchestrator provisions the matching persona
|
||||||
roster and org structure from a cross-domain baseline persona library; the
|
roster and org structure from a cross-domain baseline persona library; the
|
||||||
delivery/coding fleet is one profile among many.
|
delivery/coding fleet is one profile among many.
|
||||||
|
- id: NS-10
|
||||||
|
text: >-
|
||||||
|
An adoption is not complete until the mechanism it replaces is removed.
|
||||||
|
Two live conventions for one concern is the defect, not a transition
|
||||||
|
state. Measured 2026-08-20: brain-home adopted by 9 modules and not 10;
|
||||||
|
MOSAIC_HOME honored in 4 places, each re-deriving it; backlog cards
|
||||||
|
declared while TASKS.md files stayed authoritative. Every one was decided
|
||||||
|
correctly and left half-applied.
|
||||||
|
|
||||||
success_criteria:
|
success_criteria:
|
||||||
|
- id: AC-NS-0
|
||||||
|
tier: 0
|
||||||
|
text: >-
|
||||||
|
The operator launches an agent on any configured harness with one
|
||||||
|
command, observes its state and sends it work without attaching to a
|
||||||
|
terminal multiplexer.
|
||||||
- id: AC-NS-1
|
- id: AC-NS-1
|
||||||
|
tier: 1
|
||||||
text: >-
|
text: >-
|
||||||
The supervisor keeps a two-agent floor (1 orchestrator + >=1 enhancer)
|
The supervisor keeps a two-agent floor (1 orchestrator + >=1 enhancer)
|
||||||
healthy across reboot.
|
healthy across reboot.
|
||||||
- id: AC-NS-2
|
- id: AC-NS-2
|
||||||
|
tier: 1
|
||||||
text: >-
|
text: >-
|
||||||
A goal added to this YAML is decomposed to cards and either merged or
|
A goal added to this YAML is decomposed to cards and either merged or
|
||||||
escalated, with no human in the loop.
|
escalated, with no human in the loop.
|
||||||
- id: AC-NS-3
|
- id: AC-NS-3
|
||||||
|
tier: 1
|
||||||
text: >-
|
text: >-
|
||||||
No PR merges with failure/error/no-status/timeout CI, and none bypass
|
No PR merges with failure/error/no-status/timeout CI, and none bypass
|
||||||
pr-merge.sh.
|
pr-merge.sh.
|
||||||
- id: AC-NS-4
|
- id: AC-NS-4
|
||||||
|
tier: 1
|
||||||
text: >-
|
text: >-
|
||||||
TTL is enforced on claims; token caps remain advisory until a real meter
|
TTL is enforced on claims; token caps remain advisory until a real meter
|
||||||
exists.
|
exists.
|
||||||
- id: AC-NS-5
|
- id: AC-NS-5
|
||||||
|
tier: 1
|
||||||
text: >-
|
text: >-
|
||||||
Flipping fleet/run/PAUSED halts dispatch and merges within one tick.
|
Flipping fleet/run/PAUSED halts dispatch and merges within one tick.
|
||||||
- id: AC-NS-6
|
- id: AC-NS-6
|
||||||
|
tier: 2
|
||||||
text: >-
|
text: >-
|
||||||
A user can declare a system type and the fleet provisions the matching
|
A user can declare a system type and the fleet provisions the matching
|
||||||
persona roster + topology from the baseline library, with no code change.
|
persona roster + topology from the baseline library, with no code change.
|
||||||
- id: AC-NS-7
|
- id: AC-NS-7
|
||||||
|
tier: 2
|
||||||
text: >-
|
text: >-
|
||||||
A user-customized persona (edited or added via the orchestrator) survives
|
A user-customized persona (edited or added via the orchestrator) survives
|
||||||
mosaic update: baseline reseed never clobbers user overrides.
|
mosaic update: baseline reseed never clobbers user overrides.
|
||||||
@@ -112,80 +133,186 @@ workstreams:
|
|||||||
title: Meta-loop — session-review + enhancer improvement PRs
|
title: Meta-loop — session-review + enhancer improvement PRs
|
||||||
- id: F
|
- id: F
|
||||||
title: Safety-rails — TTL claims, advisory spend, PAUSE kill-switch
|
title: Safety-rails — TTL claims, advisory spend, PAUSE kill-switch
|
||||||
|
- id: G
|
||||||
|
title: Kill-switch — operator PAUSE honored before dispatch and merge
|
||||||
- id: H
|
- id: H
|
||||||
title: Personas & system profiles — cross-domain library, system-type provisioning, update-surviving customization
|
title: Personas & system profiles — cross-domain library, system-type provisioning, update-surviving customization
|
||||||
|
- id: I
|
||||||
|
title: Operator surface — launcher, fleet visibility, reliable steering (tier 0)
|
||||||
|
- id: J
|
||||||
|
title: Web control plane — browser surface over the gateway (tier 1)
|
||||||
|
- id: K
|
||||||
|
title: Clients — desktop and mobile over the same backend (tier 2)
|
||||||
|
- id: L
|
||||||
|
title: Auth profiles — per-provider accounts, per-session selection (tier 2)
|
||||||
|
|
||||||
|
# NOTE: workstreams C, D, E and F are declared but currently project no goals.
|
||||||
|
# That is planning debt, not an editing error: their goals have not been written
|
||||||
|
# yet. The A5 validator below reports it rather than letting it stay invisible.
|
||||||
|
|
||||||
goals:
|
goals:
|
||||||
- id: A1
|
- id: A1
|
||||||
title: Machine-readable NORTH_STAR.yaml + Markdown projection
|
title: Machine-readable NORTH_STAR.yaml + Markdown projection
|
||||||
phase: 1
|
phase: 1
|
||||||
|
tier: 1
|
||||||
priority: must-have
|
priority: must-have
|
||||||
depends_on: []
|
depends_on: []
|
||||||
- id: A2
|
- id: A2
|
||||||
title: Mosaic Backlog schema + storage-service card store (drizzle/PGlite)
|
title: Mosaic Backlog schema + storage-service card store (drizzle/PGlite)
|
||||||
phase: 1
|
phase: 1
|
||||||
|
tier: 1
|
||||||
priority: must-have
|
priority: must-have
|
||||||
depends_on: [A1]
|
depends_on: [A1]
|
||||||
- id: A3a
|
- id: A3a
|
||||||
title: Card lifecycle — create/claim/release with stable ids + depends_on DAG
|
title: Card lifecycle — create/claim/release with stable ids + depends_on DAG
|
||||||
phase: 1
|
phase: 1
|
||||||
|
tier: 1
|
||||||
priority: must-have
|
priority: must-have
|
||||||
depends_on: [A2]
|
depends_on: [A2]
|
||||||
- id: A3b
|
- id: A3b
|
||||||
title: TTL-bounded claim enforcement (wall-clock) on cards
|
title: TTL-bounded claim enforcement (wall-clock) on cards
|
||||||
phase: 1
|
phase: 1
|
||||||
|
tier: 1
|
||||||
priority: must-have
|
priority: must-have
|
||||||
depends_on: [A3a]
|
depends_on: [A3a]
|
||||||
- id: A4
|
- id: A4
|
||||||
title: Advisory spend projection per card (degrades to TTL, no real meter)
|
title: Advisory spend projection per card (degrades to TTL, no real meter)
|
||||||
phase: 1
|
phase: 1
|
||||||
|
tier: 1
|
||||||
priority: should-have
|
priority: should-have
|
||||||
depends_on: [A3a]
|
depends_on: [A3a]
|
||||||
- id: B1
|
- id: B1
|
||||||
title: Supervisor tick — readiness scan, two-agent-floor health check
|
title: Supervisor tick — readiness scan, two-agent-floor health check
|
||||||
phase: 2
|
phase: 2
|
||||||
|
tier: 1
|
||||||
priority: must-have
|
priority: must-have
|
||||||
depends_on: [A3a]
|
depends_on: [A3a]
|
||||||
- id: B2
|
- id: B2
|
||||||
title: Native dispatch/claim — assign ready dependency-satisfied work
|
title: Native dispatch/claim — assign ready dependency-satisfied work
|
||||||
phase: 2
|
phase: 2
|
||||||
|
tier: 1
|
||||||
priority: must-have
|
priority: must-have
|
||||||
depends_on: [A3b, B1]
|
depends_on: [A3b, B1]
|
||||||
- id: B3a
|
- id: B3a
|
||||||
title: Planner decompose — goal added to YAML → cards
|
title: Planner decompose — goal added to YAML → cards
|
||||||
phase: 2
|
phase: 2
|
||||||
|
tier: 1
|
||||||
priority: must-have
|
priority: must-have
|
||||||
depends_on: [A2, B1]
|
depends_on: [A2, B1]
|
||||||
- id: B3b
|
- id: B3b
|
||||||
title: Replan request on empty backlog; escalate on no-decompose
|
title: Replan request on empty backlog; escalate on no-decompose
|
||||||
phase: 2
|
phase: 2
|
||||||
|
tier: 1
|
||||||
priority: should-have
|
priority: should-have
|
||||||
depends_on: [B3a]
|
depends_on: [B3a]
|
||||||
- id: G1
|
- id: G1
|
||||||
title: PAUSE kill-switch + merge-gate honored before dispatch and merge
|
title: PAUSE kill-switch + merge-gate honored before dispatch and merge
|
||||||
phase: 2
|
phase: 2
|
||||||
|
tier: 1
|
||||||
priority: must-have
|
priority: must-have
|
||||||
depends_on: [B2]
|
depends_on: [B2]
|
||||||
- id: H1
|
- id: H1
|
||||||
title: Cross-domain baseline persona library (exec, marketing, ops, research, assistant + engineering roles)
|
title: Cross-domain baseline persona library (exec, marketing, ops, research, assistant + engineering roles)
|
||||||
phase: 1
|
phase: 1
|
||||||
|
tier: 2
|
||||||
priority: must-have
|
priority: must-have
|
||||||
depends_on: [A1]
|
depends_on: [A1]
|
||||||
- id: H2
|
- id: H2
|
||||||
title: System-type profiles — declarative mapping of system type to persona roster + topology
|
title: System-type profiles — declarative mapping of system type to persona roster + topology
|
||||||
phase: 2
|
phase: 2
|
||||||
|
tier: 2
|
||||||
priority: must-have
|
priority: must-have
|
||||||
depends_on: [H1]
|
depends_on: [H1]
|
||||||
- id: H3
|
- id: H3
|
||||||
title: System-type provisioning — user declares type; orchestrator instantiates the matching roster + structure
|
title: System-type provisioning — user declares type; orchestrator instantiates the matching roster + structure
|
||||||
phase: 2
|
phase: 2
|
||||||
|
tier: 2
|
||||||
priority: must-have
|
priority: must-have
|
||||||
depends_on: [H2]
|
depends_on: [H2]
|
||||||
- id: H4
|
- id: H4
|
||||||
title: Update-surviving persona customization — ad-hoc edits/additions persisted in a PRESERVE-protected override layer (baseline merged with overrides)
|
title: Update-surviving persona customization — ad-hoc edits/additions persisted in a PRESERVE-protected override layer (baseline merged with overrides)
|
||||||
phase: 2
|
phase: 2
|
||||||
|
tier: 2
|
||||||
priority: must-have
|
priority: must-have
|
||||||
depends_on: [H1]
|
depends_on: [H1]
|
||||||
|
- id: A5
|
||||||
|
title: NORTH_STAR schema validator — every goal's workstream declared, every workstream has a goal, every depends_on id exists, every tier has a success criterion; runs in CI beside the Markdown regeneration check
|
||||||
|
phase: 1
|
||||||
|
tier: 0
|
||||||
|
priority: must-have
|
||||||
|
depends_on: [A1]
|
||||||
|
- id: I1
|
||||||
|
title: One home resolver — a single function resolving MOSAIC_HOME with a sane default, adopted by every module. Today brain-home.ts is imported by 9 modules while 10 still use DEFAULT_MOSAIC_HOME, and MOSAIC_HOME is re-derived ad hoc in 4 places. NS-10 applies - finish the adoption and delete the second path
|
||||||
|
phase: 1
|
||||||
|
tier: 0
|
||||||
|
priority: must-have
|
||||||
|
depends_on: []
|
||||||
|
- id: I2
|
||||||
|
title: 'mosaic fleet ps sees the fleet that is actually running. Three measured blockers: the roster declares socket `mosaic-fleet` which does not exist, the 18 live sessions are on the default socket, and nothing writes a roster because seats are launched outside the CLI. Make the socket configurable and the roster written at launch, or make ps read tmux + seat dirs directly'
|
||||||
|
phase: 1
|
||||||
|
tier: 0
|
||||||
|
priority: must-have
|
||||||
|
depends_on: [I1]
|
||||||
|
- id: I3
|
||||||
|
title: Migrate fleet steering onto mosaic agent send --verify (exists, FLEET-OBS-005, spec FR-5) and retire tools/tmux/agent-send.sh, which forges the sender (D33) and returns an uninformative rc (D16, D34). FR-5 predates those defects by a month
|
||||||
|
phase: 1
|
||||||
|
tier: 0
|
||||||
|
priority: must-have
|
||||||
|
depends_on: [I1]
|
||||||
|
- id: I4
|
||||||
|
title: 'mosaic fleet absorbs what launch-seat.sh does and launch-seat.sh is deprecated: compose the prompt file set, force the skill set, wire the style hook, fail closed on any unreadable input, export per-seat git identity, and register the seat in the roster. launch-seat.sh was a manual method; it is the reference implementation, not the destination'
|
||||||
|
phase: 1
|
||||||
|
tier: 0
|
||||||
|
priority: must-have
|
||||||
|
depends_on: [I1, I5]
|
||||||
|
- id: I5
|
||||||
|
title: Harness probe matrix — verify a working prompt-injection path for claude, codex, opencode and pi, and refuse any runtime whose path is unverified. AC-NS-0 clause 1 ("any configured harness") rests on this. The probe work in docs/plans/2026-08-19_launch-seat-multi-runtime.md (brain, untracked) transfers; its launch-seat.sh target does not
|
||||||
|
phase: 1
|
||||||
|
tier: 0
|
||||||
|
priority: must-have
|
||||||
|
depends_on: []
|
||||||
|
- id: I6
|
||||||
|
title: Finish the heartbeat responder (FLEET-OBS-002, the only Phase-2 task still in-progress; spec FR-2). Health must mean "answered a heartbeat", not "pane alive" — pane state measured two seats wrong on 2026-08-20
|
||||||
|
phase: 1
|
||||||
|
tier: 0
|
||||||
|
priority: must-have
|
||||||
|
depends_on: []
|
||||||
|
- id: I7
|
||||||
|
title: Independent review and live-fleet dogfood of the Phase-2 verbs (FLEET-OBS-008), then land them (FLEET-OBS-009). Implementation is done and verification is not; "done" in a task file frozen five weeks is not evidence
|
||||||
|
phase: 1
|
||||||
|
tier: 0
|
||||||
|
priority: must-have
|
||||||
|
depends_on: [I2, I3, I4, I6]
|
||||||
|
- id: I8
|
||||||
|
title: Neutralize misleading documentation — supersede headers on docs that state a stale status, a false blocker or a retired mechanism. Cheap, and it is tier 0 because a stale doc does not merely fail to help an agent, it actively misroutes one. Rebuilding the documentation is a separate and later job
|
||||||
|
phase: 1
|
||||||
|
tier: 0
|
||||||
|
priority: must-have
|
||||||
|
depends_on: []
|
||||||
|
- id: I9
|
||||||
|
title: Study t3code's agent-attach and multi-provider auth methods and record what transfers. Reference only — Mosaic implements its own within the stack, never adopts the code and never takes the dependency. Informs HOW I/J/K/L are built, not whether
|
||||||
|
phase: 1
|
||||||
|
tier: 0
|
||||||
|
priority: should-have
|
||||||
|
depends_on: []
|
||||||
|
- id: J1
|
||||||
|
title: Web control plane over the gateway — fleet visibility and steering in a browser, same data source as I2
|
||||||
|
phase: 3
|
||||||
|
tier: 1
|
||||||
|
priority: must-have
|
||||||
|
depends_on: [I2]
|
||||||
|
- id: K1
|
||||||
|
title: Desktop and mobile clients against the gateway, authenticated
|
||||||
|
phase: 4
|
||||||
|
tier: 2
|
||||||
|
priority: must-have
|
||||||
|
depends_on: [J1]
|
||||||
|
- id: L1
|
||||||
|
title: Per-provider auth profiles with per-session selection
|
||||||
|
phase: 4
|
||||||
|
tier: 2
|
||||||
|
priority: must-have
|
||||||
|
depends_on: [I4]
|
||||||
|
|
||||||
assumptions:
|
assumptions:
|
||||||
- id: ASM-1
|
- id: ASM-1
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
# PRD — Mosaic Fleet Suite (init, configure, operate)
|
# PRD — Mosaic Fleet Suite (init, configure, operate)
|
||||||
|
|
||||||
> **Workstream:** W-FLEET (Fleet) under mission `mvp-20260312` · **Phase:** 3→4 productization
|
> **Workstream:** W-FLEET (Fleet) under mission `mvp-20260312` · **Phase:** 3→4 productization
|
||||||
> **North star:** [docs/fleet/north-star.md](./north-star.md) · prior: Phase-2 observability (#579), durable launch (#581), real-agent enablement (#583/#584/#586), releases 0.0.35–0.0.37
|
> **North star:** [docs/fleet/FLEET-DOCTRINE.md](./FLEET-DOCTRINE.md) · prior: Phase-2 observability (#579), durable launch (#581), real-agent enablement (#583/#584/#586), releases 0.0.35–0.0.37
|
||||||
> **Lead:** Jarvis @ `w-jarvis`. **Collaborator:** coder agent @ `dragon-lin` (jwoltje@10.1.10.37:coder0-0).
|
> **Lead:** Jarvis @ `w-jarvis`. **Collaborator:** coder agent @ `dragon-lin` (jwoltje@10.1.10.37:coder0-0).
|
||||||
> Owner of this file: Fleet workstream lead. Does not modify MVP single-writer control-plane files.
|
> Owner of this file: Fleet workstream lead. Does not modify MVP single-writer control-plane files.
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
# PRD — Fleet Phase 2: Operator Observability
|
# PRD — Fleet Phase 2: Operator Observability
|
||||||
|
|
||||||
> **Workstream:** W-FLEET under `mvp-20260312` · **Phase:** 2
|
> **Workstream:** W-FLEET under `mvp-20260312` · **Phase:** 2
|
||||||
> **North star:** [docs/fleet/north-star.md](./north-star.md)
|
> **North star:** [docs/fleet/FLEET-DOCTRINE.md](./FLEET-DOCTRINE.md)
|
||||||
> **Source umbrella PRD:** [docs/PRD.md](../PRD.md) (Mosaic Stack v0.1.0)
|
> **Source umbrella PRD:** [docs/PRD.md](../PRD.md) (Mosaic Stack v0.1.0)
|
||||||
> **Tracks task:** `fleet-observability-1` — restore operator observability into fleet agent sessions.
|
> **Tracks task:** `fleet-observability-1` — restore operator observability into fleet agent sessions.
|
||||||
|
|
||||||
|
|||||||
+16
-1
@@ -1,10 +1,25 @@
|
|||||||
# Tasks — W-FLEET (Fleet) Phase 2: Observability
|
# Tasks — W-FLEET (Fleet) Phase 2: Observability
|
||||||
|
|
||||||
|
> ---
|
||||||
|
>
|
||||||
|
> **STATUS: SUPERSEDED — 2026-08-20.** kind `tracking` · superseded by `docs/fleet/NORTH_STAR.yaml`
|
||||||
|
>
|
||||||
|
> This file is the pre-backlog tracking mechanism. `NS-2` in the north star declares the
|
||||||
|
> replacement: every backlog item is a Mosaic Backlog card projected from the YAML. That
|
||||||
|
> model replaced this one and nobody retired the old file, so it kept reading as
|
||||||
|
> authoritative while going stale.
|
||||||
|
>
|
||||||
|
> **Do not trust a status in this file.** Verified 2026-08-20: it was already behind the
|
||||||
|
> code when it froze five weeks ago. The `FLEET-OBS` series was the one thing worth salvaging and
|
||||||
|
> is now carried as goals `I2`, `I3`, `I6` and `I7` at tier 0.
|
||||||
|
>
|
||||||
|
> Kept as a record of what was believed. Do not update it; update the YAML.
|
||||||
|
|
||||||
> Workstream task file for the Fleet. Single-writer: Fleet workstream lead (orchestrator).
|
> Workstream task file for the Fleet. Single-writer: Fleet workstream lead (orchestrator).
|
||||||
> Workers read but never modify. This is **not** the MVP rollup (`docs/TASKS.md`) — a
|
> Workers read but never modify. This is **not** the MVP rollup (`docs/TASKS.md`) — a
|
||||||
> rollup row is proposed to the MVP orchestrator, not written here.
|
> rollup row is proposed to the MVP orchestrator, not written here.
|
||||||
>
|
>
|
||||||
> Mission: `mvp-20260312` · PRD: [docs/fleet/PRD.md](./PRD.md) · North star: [docs/fleet/north-star.md](./north-star.md)
|
> Mission: `mvp-20260312` · PRD: [docs/fleet/PRD.md](./PRD.md) · North star: [docs/fleet/FLEET-DOCTRINE.md](./FLEET-DOCTRINE.md)
|
||||||
> Status: `not-started` | `in-progress` | `done` | `blocked` | `failed`
|
> Status: `not-started` | `in-progress` | `done` | `blocked` | `failed`
|
||||||
|
|
||||||
| id | status | description | depends_on | agent | pr | notes |
|
| id | status | description | depends_on | agent | pr | notes |
|
||||||
|
|||||||
@@ -3,11 +3,12 @@
|
|||||||
The launcher consumes validated data, not shell configuration.
|
The launcher consumes validated data, not shell configuration.
|
||||||
|
|
||||||
1. Read and validate the canonical roster.
|
1. Read and validate the canonical roster.
|
||||||
2. Render deterministic <name>.env.generated data from that roster.
|
2. Render deterministic <name>.env.generated data from that roster, including `MOSAIC_GIT_IDENTITY` derived exactly from the roster agent name.
|
||||||
3. Parse optional <name>.env.local through a strict allowlist.
|
3. Parse optional <name>.env.local through a strict allowlist.
|
||||||
4. Reject generated-key shadowing, unknown or sensitive-looking keys, unsafe paths/values, duplicates, malformed lines, shell syntax, and command overrides.
|
4. Reject generated-key shadowing, unknown or sensitive-looking keys, unsafe paths/values, duplicates, malformed lines, shell syntax, and command overrides.
|
||||||
5. Derive the runtime command from validated runtime/model/reasoning data.
|
5. Reject a Git identity that is unsafe or differs from the generated agent name.
|
||||||
6. Target only the exact configured tmux socket and roster session after ownership checks.
|
6. Derive the runtime command from validated runtime/model/reasoning data and pass every generated projection entry through the clean process environment boundary.
|
||||||
|
7. Target only the exact configured tmux socket and roster session after ownership checks.
|
||||||
|
|
||||||
## File precedence and ownership
|
## File precedence and ownership
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# F4 — Orchestrator chat connector + Matrix (local homeserver)
|
# F4 — Orchestrator chat connector + Matrix (local homeserver)
|
||||||
|
|
||||||
> **Issue:** #616 · **Doctrine:** `docs/fleet/north-star.md` (#613) — orchestrator-chat-connector decision.
|
> **Issue:** #616 · **Doctrine:** `docs/fleet/FLEET-DOCTRINE.md` (#613) — orchestrator-chat-connector decision.
|
||||||
> **Status:** Phase 1 (abstraction + scaffold) in this PR; Phase 2+ are follow-ups (below).
|
> **Status:** Phase 1 (abstraction + scaffold) in this PR; Phase 2+ are follow-ups (below).
|
||||||
|
|
||||||
## Goal
|
## Goal
|
||||||
|
|||||||
@@ -35,6 +35,7 @@ values, credential material, or command text.
|
|||||||
|
|
||||||
```dotenv
|
```dotenv
|
||||||
MOSAIC_AGENT_NAME=<roster name>
|
MOSAIC_AGENT_NAME=<roster name>
|
||||||
|
MOSAIC_GIT_IDENTITY=<roster name>
|
||||||
MOSAIC_AGENT_CLASS=<roster class>
|
MOSAIC_AGENT_CLASS=<roster class>
|
||||||
MOSAIC_AGENT_RUNTIME=<roster runtime>
|
MOSAIC_AGENT_RUNTIME=<roster runtime>
|
||||||
MOSAIC_AGENT_MODEL=<roster model hint>
|
MOSAIC_AGENT_MODEL=<roster model hint>
|
||||||
@@ -44,8 +45,9 @@ MOSAIC_AGENT_WORKDIR=<absolute roster work directory>
|
|||||||
MOSAIC_TMUX_SOCKET=<roster socket or empty>
|
MOSAIC_TMUX_SOCKET=<roster socket or empty>
|
||||||
```
|
```
|
||||||
|
|
||||||
The generated launch contract supports only `claude`, `codex`, `opencode`, and `pi`. fleet add
|
`MOSAIC_GIT_IDENTITY` is derived from and must equal `MOSAIC_AGENT_NAME`; it is not a separate
|
||||||
uses that same runtime authority and rejects any other runtime before it writes the roster or changes
|
operator-controlled identity authority. The generated launch contract supports only `claude`, `codex`,
|
||||||
|
`opencode`, and `pi`. fleet add uses that same runtime authority and rejects any other runtime before it writes the roster or changes
|
||||||
projection, local, or quarantine files. The legacy dogfood stub on its separate `mosaic-factory`
|
projection, local, or quarantine files. The legacy dogfood stub on its separate `mosaic-factory`
|
||||||
socket remains an observability canary; it has no generated-launch adapter and cannot be added through
|
socket remains an observability canary; it has no generated-launch adapter and cannot be added through
|
||||||
this projection path.
|
this projection path.
|
||||||
|
|||||||
@@ -9,8 +9,9 @@
|
|||||||
5. [Adding New MCP Tools](#adding-new-mcp-tools)
|
5. [Adding New MCP Tools](#adding-new-mcp-tools)
|
||||||
6. [Database Schema and Migrations](#database-schema-and-migrations)
|
6. [Database Schema and Migrations](#database-schema-and-migrations)
|
||||||
7. [Claude Code Skill Bridge](#claude-code-skill-bridge)
|
7. [Claude Code Skill Bridge](#claude-code-skill-bridge)
|
||||||
8. [API Endpoint Reference](#api-endpoint-reference)
|
8. [Pi Persistent Goal Extension](#pi-persistent-goal-extension)
|
||||||
9. [Local Fleet Canary](./fleet-local-canary.md)
|
9. [API Endpoint Reference](#api-endpoint-reference)
|
||||||
|
10. [Local Fleet Canary](./fleet-local-canary.md)
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -396,6 +397,85 @@ M1 intentionally manages Claude Code only. Pi's Mosaic launcher can discover the
|
|||||||
canonical root directly. Codex still relies on the existing full skill-sync
|
canonical root directly. Codex still relies on the existing full skill-sync
|
||||||
linker and needs separate parity analysis before this lifecycle API is extended.
|
linker and needs separate parity analysis before this lifecycle API is extended.
|
||||||
|
|
||||||
|
## Pi Persistent Goal Extension
|
||||||
|
|
||||||
|
The source of the Mosaic-owned Pi goal controller is:
|
||||||
|
|
||||||
|
```text
|
||||||
|
packages/mosaic/framework/runtime/pi/goal-extension.ts
|
||||||
|
```
|
||||||
|
|
||||||
|
The framework manifest classifies `runtime/**` as framework-owned. Both the bash installer and the
|
||||||
|
TypeScript file adapter therefore deploy the same reviewed source to:
|
||||||
|
|
||||||
|
```text
|
||||||
|
$MOSAIC_HOME/runtime/pi/goal-extension.ts
|
||||||
|
# default: ~/.config/mosaic/runtime/pi/goal-extension.ts
|
||||||
|
```
|
||||||
|
|
||||||
|
Do not copy or link this extension into `~/.pi/agent/extensions/`. The launcher function
|
||||||
|
`discoverPiExtensionArgs()` emits the core `mosaic-extension.ts` first and the optional
|
||||||
|
`goal-extension.ts` second, preserving compatibility with an older installed framework that does
|
||||||
|
not have the goal file yet.
|
||||||
|
|
||||||
|
### Lifecycle design
|
||||||
|
|
||||||
|
| Pi API | Goal-controller responsibility |
|
||||||
|
| ------------------------------ | --------------------------------------------------------------------------------- |
|
||||||
|
| `registerCommand('goal')` | Set, inspect, pause, resume, or cancel one branch-specific goal |
|
||||||
|
| `registerTool(...)` | Record a terminating structured progress report with evidence |
|
||||||
|
| `context` | Inject the active goal contract before every provider request |
|
||||||
|
| `turn_end` | Record every turn, reject mixed final reports, and enforce the turn bound |
|
||||||
|
| `agent_settled` | Start one deduplicated continuation only after Pi has no retry/compact/queue work |
|
||||||
|
| `session_compact` | Record the compact check, reset provisional verification, and defer idle work |
|
||||||
|
| `session_start`/`session_tree` | Rebuild state from custom entries on the active branch |
|
||||||
|
| `session_shutdown` | Invalidate deferred callbacks and clear UI state |
|
||||||
|
|
||||||
|
State is appended as `mosaic-goal-state` custom entries, which do not enter model context. The
|
||||||
|
`context` hook creates a fresh hidden `mosaic-goal-context` message for each request instead of
|
||||||
|
trusting compaction summaries. The `mosaic_goal_report` result uses `terminate: true`; when it is the
|
||||||
|
sole final tool call, Pi avoids an unnecessary model response before the controller decides whether
|
||||||
|
to verify, continue, or stop.
|
||||||
|
|
||||||
|
Before state is appended or displayed, the controller applies bounded credential-pattern redaction
|
||||||
|
to the goal statement, report summary/evidence/next step, and stop reason. Fingerprints are computed
|
||||||
|
over redacted report content. Pi session entries are append-only, so a credential-bearing legacy
|
||||||
|
entry cannot honestly be erased by the extension: restoration fails closed, emits a warning, and
|
||||||
|
requires removal of the affected session before setting a new goal. This is defense-in-depth rather
|
||||||
|
than a secret-storage contract, and it does not rewrite Pi's separate model-message/tool-call
|
||||||
|
history. Goal prompts tell the agent not to submit credentials or raw sensitive output, and tests use
|
||||||
|
canaries to prove known forms do not reach new custom entries, status text, context, or tool details
|
||||||
|
while ordinary typed fields such as `token: string` remain intact.
|
||||||
|
|
||||||
|
Completion remains evidence-gated but semantic: two consecutive `achieved` reports are required,
|
||||||
|
and the second run is explicitly a verification pass. This avoids an extra judge-model request after
|
||||||
|
every turn. Deterministic validator commands are intentionally not accepted as `/goal` input in this
|
||||||
|
slice, so never describe this mechanism as proof of arbitrary natural-language completion.
|
||||||
|
|
||||||
|
### Tests and local smoke workflow
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pnpm --filter @mosaicstack/mosaic exec vitest run \
|
||||||
|
src/runtime/pi-goal-extension.spec.ts \
|
||||||
|
src/commands/launch.spec.ts \
|
||||||
|
src/config/file-adapter.test.ts
|
||||||
|
|
||||||
|
bash packages/mosaic/framework/tools/quality/scripts/test-install-migration.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
For an additive local smoke test without reseeding unrelated live framework files:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
install -D -m 0644 \
|
||||||
|
packages/mosaic/framework/runtime/pi/goal-extension.ts \
|
||||||
|
~/.config/mosaic/runtime/pi/goal-extension.ts
|
||||||
|
|
||||||
|
pi --extension ~/.config/mosaic/runtime/pi/goal-extension.ts
|
||||||
|
```
|
||||||
|
|
||||||
|
Use `/goal help`, `/goal set ...`, and `/goal status` in that test session. A released framework
|
||||||
|
sync installs the file, and a released Mosaic CLI loads it automatically through `mosaic pi`.
|
||||||
|
|
||||||
## API Endpoint Reference
|
## API Endpoint Reference
|
||||||
|
|
||||||
All endpoints are served by the gateway at `http://localhost:14242` by default.
|
All endpoints are served by the gateway at `http://localhost:14242` by default.
|
||||||
|
|||||||
@@ -4,7 +4,16 @@
|
|||||||
**Tracking:** [Mosaic Stack issue #751](https://git.mosaicstack.dev/mosaicstack/stack/issues/751)
|
**Tracking:** [Mosaic Stack issue #751](https://git.mosaicstack.dev/mosaicstack/stack/issues/751)
|
||||||
**Execution:** USC web1 only; collision-free GPT coder2/3/4/5 lanes
|
**Execution:** USC web1 only; collision-free GPT coder2/3/4/5 lanes
|
||||||
**Contract:** `SHARED-CONTRACT.md` + four `contracts/*.v1.ts` files
|
**Contract:** `SHARED-CONTRACT.md` + four `contracts/*.v1.ts` files
|
||||||
**Implementation hold:** no feature slice starts until the canon PR is merged to `main` with terminal-green CI; after merge, each slice remains held until every declared KBN prerequisite is complete.
|
|
||||||
|
> **HOLD LIFTED — 2026-08-20.** The stated condition ("no feature slice starts until the
|
||||||
|
> canon PR is merged to `main` with terminal-green CI") was **met on 2026-07-14** by
|
||||||
|
> `49e8a541` — _docs(#751): Publish native Kanban/SOT canon (#752)_ — which is on both
|
||||||
|
> `main` and `next`, and `docs/requirements/native-kanban-sot.md` is present on `main`.
|
||||||
|
> The line below was never updated, so for five weeks this file advertised a blocker that
|
||||||
|
> did not exist. The status line above ("PUBLICATION IN PROGRESS") is stale for the same
|
||||||
|
> reason. This file is a build plan, not a task tracker, and is NOT superseded.
|
||||||
|
|
||||||
|
**Implementation hold (SATISFIED — see note above):** no feature slice starts until the canon PR is merged to `main` with terminal-green CI; after merge, each slice remains held until every declared KBN prerequisite is complete.
|
||||||
|
|
||||||
> This publication file is not a runtime task authority. After cutover, repository `TASKS.md` is generated read-only and never imported.
|
> This publication file is not a runtime task authority. After cutover, repository `TASKS.md` is generated read-only and never imported.
|
||||||
|
|
||||||
|
|||||||
@@ -22,7 +22,7 @@
|
|||||||
| RI-1-002 | done | RI-N1 negative control: checked-in tests proving a broken mandatory check blocks every publish step and that DAG edges cannot be bypassed | #1275 | pi-glm-5.3 | mosaicstack/stack | test/ri-050-publish-gate-negative | RI-1-001 | 12K | |
|
| RI-1-002 | done | RI-N1 negative control: checked-in tests proving a broken mandatory check blocks every publish step and that DAG edges cannot be bypassed | #1275 | pi-glm-5.3 | mosaicstack/stack | test/ri-050-publish-gate-negative | RI-1-001 | 12K | |
|
||||||
| RI-2-001 | done | RI-N2 (Forge): remove stub-executor false success; `--simulate` typed `simulated` results that satisfy nothing; literal-`true` gates and echo-review replaced with real gates or typed waiting-for-authority | #1275 | pi-glm-5.3 | mosaicstack/stack | fix/ri-050-forge-fail-closed | RI-0-001 | 20K | Independent review APPROVED 2026-08-17 (Gitea review 172 on PR #1278, head 99b8f6ea; reviewing seat fargo — recorded under shared host principal mos-dt-0, provenance correction posted by fred; wrapper gap filed by fred). Executed at head: forge tests 116/116, lint green, typecheck green after building macp dist (minimal-install artifact, not a defect), workspace typecheck 45/45, no external type consumers of the changed interfaces. CI red = known lane-wide fleet-test failure only, carries no information about this change (fred, log-content analysis, pipelines 2456-2458). Non-blocking finding: README L141-143 + skills/mosaic-forge/SKILL.md document bare forge run/resume, which now fails closed — fast-follow docs touch. Merge queued behind #1270. UPDATE 2026-08-18: #1270 merged; CI GREEN at head 4917df1f via serialized retry (pipeline 2477) - root cause of prior reds was CI-agent contention (web SPA timeouts under concurrent pipelines), superseding the fleet-test-failure theory. |
|
| RI-2-001 | done | RI-N2 (Forge): remove stub-executor false success; `--simulate` typed `simulated` results that satisfy nothing; literal-`true` gates and echo-review replaced with real gates or typed waiting-for-authority | #1275 | pi-glm-5.3 | mosaicstack/stack | fix/ri-050-forge-fail-closed | RI-0-001 | 20K | Independent review APPROVED 2026-08-17 (Gitea review 172 on PR #1278, head 99b8f6ea; reviewing seat fargo — recorded under shared host principal mos-dt-0, provenance correction posted by fred; wrapper gap filed by fred). Executed at head: forge tests 116/116, lint green, typecheck green after building macp dist (minimal-install artifact, not a defect), workspace typecheck 45/45, no external type consumers of the changed interfaces. CI red = known lane-wide fleet-test failure only, carries no information about this change (fred, log-content analysis, pipelines 2456-2458). Non-blocking finding: README L141-143 + skills/mosaic-forge/SKILL.md document bare forge run/resume, which now fails closed — fast-follow docs touch. Merge queued behind #1270. UPDATE 2026-08-18: #1270 merged; CI GREEN at head 4917df1f via serialized retry (pipeline 2477) - root cause of prior reds was CI-agent contention (web SPA timeouts under concurrent pipelines), superseding the fleet-test-failure theory. |
|
||||||
| RI-2-002 | done | RI-N2 (MACP): gate runner fails closed on empty commands, stub executors, and unimplemented CI-provider gates unless explicit simulate; typed capability failures | #1275 | pi-glm-5.3 | mosaicstack/stack | fix/ri-050-macp-fail-closed | RI-0-001 | 15K | PR #1293 (head 2097379e): CI green (pipeline 2465), independent review APPROVED (Gitea review 173, jarvis seat, 2026-08-17) - macp 109/109 verified at head. Merge queued behind #1276/#1277/#1278. |
|
| RI-2-002 | done | RI-N2 (MACP): gate runner fails closed on empty commands, stub executors, and unimplemented CI-provider gates unless explicit simulate; typed capability failures | #1275 | pi-glm-5.3 | mosaicstack/stack | fix/ri-050-macp-fail-closed | RI-0-001 | 15K | PR #1293 (head 2097379e): CI green (pipeline 2465), independent review APPROVED (Gitea review 173, jarvis seat, 2026-08-17) - macp 109/109 verified at head. Merge queued behind #1276/#1277/#1278. |
|
||||||
| RI-3-001 | in-progress | RI-N4: complete probe inventory mapping every TS and shell quality-rail check to one canonical check with disposition (preserve/strengthen/retire, each named) | #1275 | pi-glm-5.3 | mosaicstack/stack | docs/ri-050-qr-probe-inventory | RI-0-001 | 12K | |
|
| RI-3-001 | done | RI-N4: complete probe inventory mapping every TS and shell quality-rail check to one canonical check with disposition (preserve/strengthen/retire, each named) | #1275 | pi-glm-5.3 | mosaicstack/stack | docs/ri-050-qr-probe-inventory | RI-0-001 | 12K | PR #1302 (head e06a47fac591): CI green (2484), independent review APPROVED (Gitea review 187, fargo seat, 2026-08-18) — 54 rows / 21 canonical checks / dispositions 43-2-9-0 verified by row-count and code spot-checks. Merged by fargo at pinned head. |
|
||||||
| RI-3-002 | not-started | RI-N4: TS evaluator absorbs effective shell probes; typed results (passed/failed/blocked/error/not-applicable) with versioned digested check definitions; shell commands become thin adapters; contract/parity/negative-control tests | #1275 | pi-glm-5.3 | mosaicstack/stack | feat/ri-050-qr-evaluator | RI-3-001 | 30K | |
|
| RI-3-002 | not-started | RI-N4: TS evaluator absorbs effective shell probes; typed results (passed/failed/blocked/error/not-applicable) with versioned digested check definitions; shell commands become thin adapters; contract/parity/negative-control tests | #1275 | pi-glm-5.3 | mosaicstack/stack | feat/ri-050-qr-evaluator | RI-3-001 | 30K | |
|
||||||
| RI-4-001 | in-progress | RI-N3: one PRD application service — `mission --plan` persists mission↔PRD linkage (ids/versions/selected requirements); `mosaic prdy` routes through the service or becomes a named import/export adapter; Markdown is a labeled generated view; explicit conflict-aware import | #1275 | pi-glm-5.3 | mosaicstack/stack | feat/ri-050-prd-authority | RI-0-001 | 35K | PR #1294 (head 8d258e1d): CI green (pipeline 2466), independent review APPROVED (Gitea review 174, jarvis seat, 2026-08-17) - prdy 20/20 + command specs 9/9 at head. Merge queued behind #1276/#1277/#1278. |
|
| RI-4-001 | in-progress | RI-N3: one PRD application service — `mission --plan` persists mission↔PRD linkage (ids/versions/selected requirements); `mosaic prdy` routes through the service or becomes a named import/export adapter; Markdown is a labeled generated view; explicit conflict-aware import | #1275 | pi-glm-5.3 | mosaicstack/stack | feat/ri-050-prd-authority | RI-0-001 | 35K | PR #1294 (head 8d258e1d): CI green (pipeline 2466), independent review APPROVED (Gitea review 174, jarvis seat, 2026-08-17) - prdy 20/20 + command specs 9/9 at head. Merge queued behind #1276/#1277/#1278. |
|
||||||
| RI-5-001 | done | RI-N5: typed freshness states (current/stale/partial/unknown/unavailable); no failed-fetch-renders-empty; stale derived verdicts → unknown; mutations disabled when stale; failure-matrix tests | #1275 | pi-glm-5.3 | mosaicstack/stack | feat/ri-050-web-stale-safety | RI-0-001 | 25K | |
|
| RI-5-001 | done | RI-N5: typed freshness states (current/stale/partial/unknown/unavailable); no failed-fetch-renders-empty; stale derived verdicts → unknown; mutations disabled when stale; failure-matrix tests | #1275 | pi-glm-5.3 | mosaicstack/stack | feat/ri-050-web-stale-safety | RI-0-001 | 25K | |
|
||||||
|
|||||||
@@ -0,0 +1,186 @@
|
|||||||
|
# Quality-Rails Probe Inventory — RI-3-001
|
||||||
|
|
||||||
|
- **Task:** RI-3-001 (SDLC-D-037 first half; PRD § Release Integrity Workstream, RI-N4)
|
||||||
|
- **Date:** 2026-08-18
|
||||||
|
- **Base:** `origin/next` @ `8199261c` (branch `docs/ri-050-qr-probe-inventory`)
|
||||||
|
- **Follow-up:** RI-3-002 consumes the dispositions here when building the single TS evaluator.
|
||||||
|
|
||||||
|
## 0. Scope and method
|
||||||
|
|
||||||
|
Every mechanism in this repository that verifies a quality, integrity, safety, or release
|
||||||
|
property — TypeScript checks, shell probes, pipeline steps, git hooks, and installer-side
|
||||||
|
assertions — gets one row. Each row's "what it actually verifies" was written from the
|
||||||
|
probe's **code**, not its name or docs. Framework tool unit/regression suites (git wrappers,
|
||||||
|
wake, tmux, orchestrator, …) are treated as one enforcement surface (`test:framework-shell`)
|
||||||
|
because they test tool behavior rather than repo quality; their wiring integrity is itself
|
||||||
|
guarded by `check-test-enumeration.sh`, and the quality-relevant members are rowed
|
||||||
|
individually.
|
||||||
|
|
||||||
|
**Kinds:** `ts` (TypeScript/Node check), `shell` (bash/python probe), `pipeline-step`
|
||||||
|
(exists only inside a Woodpecker pipeline).
|
||||||
|
|
||||||
|
**Enforcement points:** `local` (operator-invoked), `pre-commit`, `pre-push`,
|
||||||
|
`CI ci.yml#<step>`, `publish.yml#<step>` (CI on push to main/next), `turbo <task>`,
|
||||||
|
`agent-runtime` (framework hooks on an agent host), `installer` (host install path),
|
||||||
|
`unwired`.
|
||||||
|
|
||||||
|
**Dispositions** (recommendations for RI-3-002): `preserve` (keep as-is; already the
|
||||||
|
canonical or a correct guard-of-the-guard), `strengthen` (keep, but a concrete gap must
|
||||||
|
close — usually absorption into the TS evaluator), `strengthen (review)` (viable retirement
|
||||||
|
candidate once the evaluator absorbs it; do not retire yet). Note: RI-N4 requires that
|
||||||
|
effective shell probes be **absorbed before** their independent paths retire — no row here
|
||||||
|
is marked `retire` because no absorption exists yet.
|
||||||
|
|
||||||
|
## 1. Inventory
|
||||||
|
|
||||||
|
### 1.1 Repo-level gate tasks (pnpm / turbo)
|
||||||
|
|
||||||
|
| check | location | kind | what it actually verifies | enforcement point | canonical check | disposition | rationale |
|
||||||
|
| ------------------------------------- | ------------------------------------------------------------------------------------ | ---- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ | ------------------------- | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||||
|
| `pnpm preflight` (checkout preflight) | `scripts/preflight.mjs` | ts | Six gate binaries (eslint, husky, prettier, tsc, turbo, vitest) exist and are executable in `node_modules/.bin` (exit 42 if not); no stale `.mosaic-test-work/web-build.lock` (exit 43); `apps/web/.next` is a real directory (not a symlink), every entry owned by the current uid, and its `.mosaic-source-hash` fingerprint + `.mosaic-symlink-manifest` hash match the certified build written by `scripts/build-web.mjs` | `pre-push`; inside `pnpm typecheck` (→ `CI ci.yml#typecheck`, verify-release `typecheck` stage) | QC-1 Checkout integrity | preserve | Blocks a poisoned/stale generated `.next` from faking a green typecheck (the five-month-stale-`.next` class); trust chain is self-contained per-checkout. |
|
||||||
|
| `pnpm typecheck` | root `package.json` → `turbo run typecheck` | ts | Per-package `tsc --noEmit` (all 20 packages); turbo `typecheck` depends on `^build`, so package builds must succeed first; prefixed by checkout preflight | `CI ci.yml#typecheck`; `pre-push`; verify-release `typecheck` stage; `turbo typecheck` | QC-2 Workspace typecheck | preserve | The single workspace-wide type gate; CI and hooks invoke the same task, no divergent checklist. |
|
||||||
|
| `pnpm lint` | root `package.json` → `turbo run lint` | ts | Per-package `eslint src` under root `eslint.config.mjs` (ignores `dist`, `.next`, `framework/**`, etc.) | `CI ci.yml#lint`; `pre-push`; verify-release `lint` stage; `turbo lint` | QC-3 Workspace lint | preserve | Same-task invocation from every surface; no second lint definition. |
|
||||||
|
| `pnpm format:check` | root `package.json` → `prettier --check` | ts | Prettier parse/format equality over `**/*.{ts,tsx,js,jsx,json,md}` minus `.prettierignore` (generated trees, `docs/scratchpads/`, venvs, …) | `CI ci.yml#format`; `pre-push`; verify-release `format` stage | QC-4 Format check | preserve | Single formatter, single ignore list, enforced identically everywhere. |
|
||||||
|
| `pnpm test` | root `package.json` `test` = `test:checkout` && `turbo run test` && `test:installer` | ts | (a) `node --test scripts/*.test.mjs` — checkout-tool units; (b) per-package `vitest run` (mosaic appends the 47-command `test:framework-shell` chain); (c) `tools/install-next-lane.test.sh`; turbo `test` declares DB env vars and depends on `^build` | `CI ci.yml#test` (with `DATABASE_URL` + `db:migrate` first); verify-release `test` stage; `turbo test` | QC-5 Test suite execution | preserve | One composed test command; the chain property (any link red ⇒ step red) is the gate. |
|
||||||
|
| `pnpm build` | root `package.json` → `turbo run build` | ts | Per-package build (`tsc`/Next) with `^build` dependency and `dist/**` outputs | `publish.yml#build`; verify-release `build` stage; `turbo build` | QC-6 Workspace build | preserve | Publish artifacts derive from the same build task CI verifies. |
|
||||||
|
|
||||||
|
### 1.2 Framework quality shell probes (`packages/mosaic/framework/tools/quality/`)
|
||||||
|
|
||||||
|
| check | location | kind | what it actually verifies | enforcement point | canonical check | disposition | rationale |
|
||||||
|
| ------------------------------------------- | ----------------------------------------------------------------------- | ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
|
||||||
|
| Sanitization gate | `scripts/verify-sanitized.sh` | shell | Built-in self-test first (planted identity/structural/YAML+service fixtures; exit 2 if the regexes or extension coverage break), then: (1) identity denylist grep (`jarvis\|jason\|woltje\|brain.woltje.com\|/home/jwoltje\|\bPDA\b`) over all shipped text files **including** `examples/`; (2) structural grep for private `$HOME/src` defaults in shipped scripts **excluding** `examples/`. Any hit ⇒ exit 1 | `CI ci.yml#sanitization`; verify-release `sanitization` stage | QC-7 Framework sanitization | preserve | Labeled one-time regression guard with a self-test that prevents silent no-op; correctly scoped (identity vs structural) and documented as not a general PII detector. |
|
||||||
|
| Resident-context budget | `scripts/check-resident-budget.sh` (+ `--self-test`) | shell | Self-test of the comparator, then `wc -l` vs per-file ceilings (CONSTITUTION 120, AGENTS 120, each RUNTIME.md 90); missing file ⇒ fail; over ceiling ⇒ exit 1 | `CI ci.yml#sanitization` (both modes); verify-release `sanitization` stage | QC-8 Resident-context budget | preserve | Caps the container (lines), never the wording — the deliberate anti-drift design (DESIGN §7); CI-enforceable half only, by design. |
|
||||||
|
| Test-membership enumeration guard (#1017) | `scripts/check-test-enumeration.sh` + `test-enumeration-exclusions.txt` | shell | Parses surface S1 (`packages/mosaic` `test:framework-shell` via JSON+shlex) and S2 (every `framework/tools/\*.sh | .py`token in`ci.yml`, comment lines stripped); population = `_test_.sh`under`framework/tools`; FAILS on: suite-shaped file on disk neither enumerated nor signed-excluded; surface naming a path missing on disk (both directions); exclusion without reason / stale / outside population / contradicting enumeration. Proves **naming, not reachability** (stated in-file) | `CI ci.yml#sanitization` (direct line); link [0] of `test:framework-shell` (thus `CI ci.yml#test`); verify-release `sanitization` stage | QC-9 Test-membership enumeration | preserve | Makes silent under-run impossible; invoked from both surfaces it audits so severing the chain cannot silence it. |
|
||||||
|
| Enumeration-guard needles | `scripts/test-check-test-enumeration.sh` | shell | Needle/control fixtures driven through `--root`: every promised failure mode must trip the guard **on its own words**, plus controls that must pass (null-case defense); covers commented-out ci.yml lines (F1) and line-range parsing (n2b) | `test:framework-shell` → `CI ci.yml#test`; verify-release `test` stage | QC-9 Test-membership enumeration | preserve | Guard-of-the-guard with both polarities; same canonical check by design. |
|
||||||
|
| Upgrade manifest guard (#791 HARD GATE) | `scripts/test-upgrade-manifest-guard.sh` | shell | Keep-mode `install.sh` upgrade against seeded throwaway `MOSAIC_HOME`: every operator sentinel — including an **unanticipated** one — survives byte-identical with unchanged mtime; framework files still update; retired framework files pruned; matrix run with rsync present AND absent (keep path must be rsync-independent); fail-closed matrix (empty/operator-only/malformed/missing manifest aborts loudly, operator files untouched); operator secret never appears in installer output | `CI ci.yml#upgrade-guard`; verify-release `upgrade-guard` stage | QC-10 Upgrade/install safety | preserve | The operator-data hard gate for the `mosaic update` path; negative controls are load-bearing and documented. |
|
||||||
|
| Upgrade rollback gate (#791 B1) | `scripts/test-upgrade-rollback.sh` | shell | Mid-sync failure (PATH-shadowing `cp` shim) must trigger snapshot restore: restore message fires, corrupted file restored, target byte-identical to pre-upgrade; control installer with `set -E` stripped must NOT roll back (proves errtrace is load-bearing); plus signal/exit-guard controls | `CI ci.yml#upgrade-guard`; verify-release `upgrade-guard` stage | QC-10 Upgrade/install safety | preserve | Proves the rollback trap actually fires; the `-E`-stripped control keeps Part A honest. |
|
||||||
|
| Durable-snapshot gate (#791 PR2) | `scripts/test-upgrade-durable-snapshot.sh` | shell | Pre-update snapshot taken before any mutation (0700/0600 perms, secret never logged, retention-pruned); post-sync verify net restores operator files a manifest bug lets the sync touch; CWE-59 symlink-leaf guard proven with a portable cp shim in both polarities (write-through-link must not happen); v1→v2 migration semantics (intended `bin/` removal not healed) | `CI ci.yml#upgrade-guard`; verify-release `upgrade-guard` stage | QC-10 Upgrade/install safety | preserve | Covers tampering and leak vectors the manifest guard cannot see; the shim rationale (busybox vs GNU cp) is documented in-file. |
|
||||||
|
| Install migration matrix (v2→v3) | `scripts/test-install-migration.sh` | shell | Fixture matrix running the real installer with `MOSAIC_SYNC_ONLY=1`: fresh install seeds + stamps version 3; legacy user-edited AGENTS overwritten with `.pre-constitution.bak` preserved (and idempotent); tuned STANDARDS overwritten; operator files (SOUL, credentials) preserved. Mirrors the TS suite `packages/mosaic/src/config/file-adapter.test.ts` — both installers must behave identically | `CI ci.yml#upgrade-guard`; verify-release `upgrade-guard` stage | QC-10 Upgrade/install safety | preserve | Pins the shell/TS installer parity contract; removal would orphan that parity requirement. |
|
||||||
|
| Enforcement verification probe (bash) | `scripts/verify.sh` | shell | Attempts **real commits** in the target repo: planted type error must produce a commit blocked with `error`; planted `any` must trip `no-explicit-any`; planted lint error must trip `prettier`; gitleaks binary must exist (3a) and detect a planted AWS key via `gitleaks git --pre-commit --staged --redact` (3b). Verdicts are output-grep matches on hook stderr | `local` via installed `mosaic-quality-verify` on scaffolded target projects; **not run in this repo's CI** | QC-20 Downstream enforcement verification | strengthen (review) | Mechanism is genuinely behavioral (stronger than file presence) but verdict logic is grep-on-output and it is unwired here; absorb as the evaluator's enforcement-probe check (the RI-N4 evaluator invokes it or reimplements it) before retiring the shell path. |
|
||||||
|
| Enforcement verification probe (PowerShell) | `scripts/verify.ps1` | shell | Windows port of `verify.sh`: same planted-commit tests with `$output -match` matching; no gitleaks self-test parity beyond the same checks | `local` (Windows operator); no Windows CI runner exists | QC-20 Downstream enforcement verification | strengthen (review) | A hand-maintained twin of `verify.sh` with no CI coverage — exactly the drift shape the single evaluator removes; retire after the TS evaluator owns the probe. |
|
||||||
|
| Quality template installer (bash) | `scripts/install.sh` | shell | Copies template files (`.husky/pre-commit` incl. mandatory gitleaks, `.lintstagedrc.js`, `.eslintrc.js`, `tsconfig.json`, `.woodpecker.yml`, `.gitleaks.toml`) into a target project; **warns** (does not verify) about `package.json` snippet merge; no post-condition check | `local` / via `mosaic-quality-apply` | QC-21 Downstream rails scaffolding | strengthen (review) | Duplicates the TS `quality-rails init` scaffolder for a different template set; converging on one scaffolder (with post-scaffold verification) is prerequisite to retiring this path. |
|
||||||
|
| Quality template installer (PowerShell) | `scripts/install.ps1` | shell | Windows twin of the template copy above | `local` (Windows operator) | QC-21 Downstream rails scaffolding | strengthen (review) | Same twin-drift risk as `verify.ps1`; no runner exercises it. |
|
||||||
|
| `mosaic-quality-verify` adapter | `framework/tools/_scripts/mosaic-quality-verify` | shell | Thin adapter: validates target dir exists, asserts `verify.sh` present+executable, `cd` target, exec it. No verdict logic of its own | `local` (installed framework bin) | QC-20 Downstream enforcement verification | preserve | Already the thin-adapter shape RI-N4 prescribes for shell surfaces. |
|
||||||
|
| `mosaic-quality-apply` adapter | `framework/tools/_scripts/mosaic-quality-apply` | shell | Thin adapter: arg validation then exec of quality `install.sh --template … --target …` | `local` (installed framework bin) | QC-21 Downstream rails scaffolding | preserve | Thin adapter, no separate verdict; disposition follows its target script's convergence. |
|
||||||
|
| Roster schema regression | `scripts/test-roster-schema.py` | shell | jsonschema `Draft202012Validator` over `fleet/roster.schema.json` with valid/invalid connector-kind fixtures (tmux/discord/matrix conditional fields) | **unwired** — not on S1 or S2, not signed-excluded; also outside the enumeration guard's `*.sh` population, so the guard cannot see it | QC-5 Test suite execution | strengthen (review) | A real regression suite that currently runs nowhere; wire it into a CI surface or sign an exclusion — leaving it invisible re-arms the exact gap #1017 closed. |
|
||||||
|
| Framework shell chain (S1) | `packages/mosaic/package.json` `test:framework-shell` | shell | 47-command `&&` chain: enumeration guard + needles, 14 lease-broker/mutator-gate python unitests, `check-runtime-launches.py`, and ~30 framework-tool shell suites (git wrappers, wake, woodpecker, tmux, glpi, orchestrator, `_scripts`). Quality-relevant members rowed separately below | `turbo test` → `CI ci.yml#test`; verify-release `test` stage | QC-5 Test suite execution | preserve | The chain is the execution surface the enumeration guard audits; known residuals: a failing link stops later suites (measured in #1270 — suites after position 44 had not run), and the guard proves naming, not reachability. |
|
||||||
|
|
||||||
|
### 1.3 Framework runtime hooks and their harnesses (agent-host enforcement)
|
||||||
|
|
||||||
|
| check | location | kind | what it actually verifies | enforcement point | canonical check | disposition | rationale |
|
||||||
|
| ------------------------------------- | ----------------------------------------------------------------------------------------- | ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------- | --------------------------------------- | ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||||
|
| QA edit hook seam | `framework/tools/qa/qa-hook-stdin.sh` (+ `qa-hook-handler.sh`) | shell | PostToolUse stdin hook: extracts edited file from the tool JSON (jq or grep fallback), skips non-JS/TS, then the deps-preflight gate — exits 1 with the legible sentinel `deps not installed — run pnpm install` when `node_modules/.bin` is missing/empty (the #856 false-red class); the downstream handler only files QA remediation **report templates** (no verification logic) | `agent-runtime` (framework `runtime/claude/settings.json` PostToolUse); never CI | QC-16 Agent-runtime edit-time checks | strengthen (review) | The sentinel gate is real enforcement; the handler's report-filing adds no verdict and its name promises more than the code does — evaluator absorption should keep the sentinel, drop the report theater. |
|
||||||
|
| Typecheck-on-edit hook | `framework/tools/qa/typecheck-hook.sh` | shell | PostToolUse: for edited `.ts/.tsx`, finds nearest `tsconfig.json` and runs `tsc --noEmit`, surfacing errors nonzero to the agent immediately | `agent-runtime` (framework `runtime/claude/settings.json` PostToolUse) | QC-16 Agent-runtime edit-time checks | strengthen (review) | Edit-time duplicate of QC-2 with independent invocation logic; keep behavior, converge invocation through the evaluator adapter. |
|
||||||
|
| Deps-preflight harness | `framework/tools/qa/test-deps-preflight.sh` | shell | Five assertions against the seam incl. a documented RED control (raw `not found`), sentinel behavior for missing and empty `.bin`, and no-false-positive once populated | `test:framework-shell` → `CI ci.yml#test` | QC-16 Agent-runtime edit-time checks | preserve | Guard-of-the-check with a red control; keeps the sentinel from regressing. |
|
||||||
|
| Prompt-helper RCE regression | `framework/tools/_scripts/test-mosaic-init-rce.sh` | shell | Sources the prompt helpers and proves a literal `$(touch /tmp/pwned)` answer round-trips verbatim and never executes (no `/tmp/pwned` created) | `test:framework-shell` → `CI ci.yml#test` | QC-5 Test suite execution | preserve | Cheap, load-bearing security regression on the installer's input path. |
|
||||||
|
| Install-ordering harness (#869 C2) | `framework/tools/_scripts/test-install-ordering-guard.sh` | shell | Drives `mosaic-link-runtime-assets` with a fake `mosaic` on PATH: probe ok ⇒ settings copied + exit 0; probe fail ⇒ exit 1 with degraded outcome but all other runtime files still copied; `--allow-inactive-enforcement` forwarded; no-mosaic-on-PATH ⇒ python3 fallback strips enforcement hooks and exits 1; fallback + flag ⇒ wires as-is, exit 0 | `test:framework-shell` → `CI ci.yml#test` | QC-17 Lease-enforcement wiring safety | preserve | Exercises the shell wiring seam independently of the TS guard's own spec suite (complementary coverage, by design). |
|
||||||
|
| Fleet-transport harness (#1240) | `framework/tools/_scripts/test-fleet-transport-check.sh` | shell | Extracts the shipped `check_fleet_transport`/`fleet_declared_transport` functions **from the shipped scripts** (fails loud if extraction yields nothing) and drives both implementations (mosaic-doctor + `tools/install.sh`) from one case table | `test:framework-shell` → `CI ci.yml#test` | QC-18 Operator-host drift audit | preserve | The anti-drift harness for the one rule shipped twice; extraction-from-source keeps it from testing a stale copy. |
|
||||||
|
| Terminal-green contract (RM-61/#1000) | `framework/tools/woodpecker/test-terminal-green-contract.sh` + `verify-terminal-green.py` | shell | Red-first fixtures: pipeline JSON variants (service failure, step failure, cancelled, etc.) must produce the correct terminal-green verdict; controls must pass | `test:framework-shell` → `CI ci.yml#test` | QC-5 Test suite execution | preserve | Keeps the CI-wait wrapper's green-detection honest; a false green here would poison every merge gate that trusts `pr-ci-wait.sh`. |
|
||||||
|
| Lease-gate launch invariant | `framework/tools/lease-broker/check-runtime-launches.py` | shell | Scans production roots (`packages/`, `apps/`, `plugins/`, `tools/`) across sh/py/ts/yaml suffixes for Claude/Pi process launches **outside** the lease gate; allowlist-based; fails CI on violation | `test:framework-shell` → `CI ci.yml#test` | QC-15 Lease-gate architecture invariant | preserve | The only architectural "no ungated launches" rail; grep+allowlist is the right cost/benefit for this invariant. |
|
||||||
|
|
||||||
|
### 1.4 TypeScript quality logic (`@mosaicstack/quality-rails` + mosaic CLI)
|
||||||
|
|
||||||
|
| check | location | kind | what it actually verifies | enforcement point | canonical check | disposition | rationale |
|
||||||
|
| ---------------------------------------- | ---------------------------------------------------------------------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------- | ------------------------------------- | ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||||
|
| `quality-rails check` | `packages/quality-rails/src/cli.ts` (`mosaic quality-rails check --project`) | ts | **Expected-file presence only**: loops `expectedFilesForKind` (node: `.eslintrc`, `biome.json`, `.githooks/pre-commit`, `PR-CHECKLIST.md`; python: `pyproject.toml`+hooks+checklist; rust: `rustfmt.toml`+…) and exits 1 listing missing paths. Does not execute any linter, formatter, hook, or scanner | `local` (operator CLI); **no CI wiring in this repo** | QC-19 Downstream rails presence check | strengthen | This is the RI-N4 evaluator seed. Today presence ≠ parity (explicitly called out by RI-N4): it must grow typed verdicts (`passed/failed/blocked/error/not-applicable`), check versioning/subject/reason, digested definitions, and absorb the effective shell probes (QC-20 first). |
|
||||||
|
| `quality-rails doctor` | `packages/quality-rails/src/cli.ts` | ts | Same presence data as `check`, printed with ok/missing lines; **cannot fail** (no nonzero exit on missing files) | `local` (operator CLI) | QC-19 Downstream rails presence check | strengthen | A doctor that cannot fail is advisory; fold into `check` (or return typed states) when the evaluator lands. |
|
||||||
|
| `quality-rails init` | `packages/quality-rails/src/cli.ts` + `scaffolder.ts`/`templates.ts` | ts | Scaffolds rails files per detected kind/profile (linters/formatters lists are advisory strings; hooks flag always true); writes files, prints follow-ups — no post-condition verification | `local` (operator CLI) | QC-21 Downstream rails scaffolding | strengthen (review) | Second scaffolding path alongside quality `install.sh` (§1.2); converge on one with post-scaffold verification before retiring either. |
|
||||||
|
| Lease activation probe (#869 C1, hidden) | `packages/mosaic/src/commands/lease-activation-probe.ts` | ts | Real capability probe, not file presence: resolves the installed mosaic CLI and requires it to advertise the exact `{name, version}` activation contract; all deps injectable; registered as hidden CLI command and consumed by C2/C5 | `local` (hidden CLI + consumed by C2/C5); spec-tested via `lease-activation-probe.spec.ts` in `turbo test` | QC-17 Lease-enforcement wiring safety | preserve | The versioned-contract probe is precisely the fail-closed capability check RI-N2 generalizes; already typed and injectable. |
|
||||||
|
| Install-ordering guard (#869 C2, hidden) | `packages/mosaic/src/commands/install-ordering-guard.ts` | ts | Decides whether enforcement hook entries are written into the `~/.claude/settings.json` the framework reseed ships: not activatable ⇒ strip hooks + nonzero loud outcome (default); explicit per-invocation `--allow-inactive-enforcement` opt-out wires-with-warning. Never touches the runtime gate's own fail-closed behavior | `installer` (framework reseed via `mosaic-link-runtime-assets`); spec + shell harness coverage in `turbo test` | QC-17 Lease-enforcement wiring safety | preserve | Correct default-deny with an explicit, non-env opt-out; test-locked from both the TS and shell sides. |
|
||||||
|
| Lease doctor check (#869 C5) | `packages/mosaic/src/commands/lease-doctor-check.ts` | ts | Combines hook-wiring detection in `~/.claude/settings.json` with C1 activatable and C3 broker-supervisor health: wired ∧ (¬activatable ∨ ¬healthy) ⇒ loud `[ERROR]` that forces `mosaic doctor` exit 1 regardless of the bash audit's own exit | `local` (inside `mosaic doctor`); spec coverage in `turbo test` | QC-17 Lease-enforcement wiring safety | preserve | Closes the "bricked host looks green" hole; cannot be masked by the bash script — that composition is the point. |
|
||||||
|
| `mosaic doctor` (framework drift audit) | `packages/mosaic/src/commands/launch.ts` (`doctor`) + `framework/tools/_scripts/mosaic-doctor` | shell+ts | Bash audit of the installed framework home: ~40 expected files/dirs present; runtime files are copies (not symlinks) matching source (`cmp`) or composed runtime-contract markers; hard-gates block present in AGENTS.md; sequential-thinking MCP configured; fleet transport binary present per roster (warn); legacy symlink trees gone; skills synced — **warn-based, exit 1 only with `--fail-on-warn`**, plus C5's forced error | `local` (operator audit) | QC-18 Operator-host drift audit | preserve | Host-state audit CI cannot see (user files by design, DESIGN §7); advisory exit is the documented contract — do not silently change it. |
|
||||||
|
| `mosaic gateway doctor` | `packages/mosaic/src/commands/gateway-doctor.ts` | ts | Probes per-service health (PostgreSQL, Valkey, pgvector) via `@mosaicstack/storage`, reports tier and JSON; exit 1 only when at least one **required** service fails (yellow stays 0) | `local` (operator) | QC-18 Operator-host drift audit | preserve | Service health with correct red/yellow exit semantics; JSON mode exists for scripting. |
|
||||||
|
| `mosaic gateway verify` | `packages/mosaic/src/commands/gateway/verify.ts` | ts | Post-install liveness: daemon meta via HTTP with retries, admin token on file, bootstrap endpoint reachable; aggregated pass/fail | `local`; consumed by `tools/e2e-install-test.sh` | QC-18 Operator-host drift audit | preserve | The first-run proof the installer E2E relies on; retry-aware so startup races don't false-red. |
|
||||||
|
| `mosaic fleet doctor` | `packages/mosaic/src/commands/fleet-reconciler-command.ts` | ts | Classifies local roster-owned drift (no mutation) from the parsed v2 roster | `local` (operator) | QC-18 Operator-host drift audit | preserve | Dry-run classification is the correct non-mutating audit shape. |
|
||||||
|
|
||||||
|
### 1.5 Git hooks (developer machine)
|
||||||
|
|
||||||
|
| check | location | kind | what it actually verifies | enforcement point | canonical check | disposition | rationale |
|
||||||
|
| ------------------------- | --------------------------------------------------------- | ----- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | --------------------------- | ----------- | ----------------------------------------------------------------------------------------------------------------- |
|
||||||
|
| Pre-commit staged hygiene | `.husky/pre-commit` → `npx lint-staged` (`.lintstagedrc`) | shell | On staged files only: `prettier --write` + `eslint --fix` for ts/tsx/js/jsx; `prettier --write` for json/md/yaml/yml. **Mutating** (fixes and re-stages); commit blocks only if a fixer itself fails | `pre-commit` (every local commit; hooks activated by `install-hooks.mjs` via `core.hooksPath .husky/_`) | QC-13 Staged-change hygiene | preserve | Correct scoped fast gate; note it auto-fixes rather than rejects (deliberate). Gap: no secret scan here — see §3. |
|
||||||
|
| Pre-push gate | `.husky/pre-push` | shell | `pnpm preflight && pnpm typecheck && pnpm lint && pnpm format:check` (no test run — documented in AGENTS.md) | `pre-push` | QC-14 Pre-push gate | preserve | Composes QC-1..4 exactly as specified in AGENTS.md; tests intentionally left to CI. |
|
||||||
|
| Hook installer | `scripts/install-hooks.mjs` (`pnpm prepare`) | ts | Stages husky hooks into a scratch repo first, asserts husky produced its `h` shim, quarantines incomplete previous sets, verifies idempotence via full directory snapshot comparison, then sets `core.hooksPath`; skips cleanly with `HUSKY=0` or no git | `installer` (runs on `pnpm install`) | QC-13 Staged-change hygiene | preserve | Self-verifying wiring for the hook gates — a corrupted half-install cannot silently disable them. |
|
||||||
|
|
||||||
|
### 1.6 CI pipeline steps (`.woodpecker/`)
|
||||||
|
|
||||||
|
Step-to-probe mapping for container steps: `ci.yml#sanitization` = QC-7+QC-8+QC-9 (rows §1.2, plus `apk add bash` env prep); `ci.yml#upgrade-guard` = QC-10 (rows §1.2, plus `apk add rsync`); `ci.yml#typecheck`/`#lint`/`#format`/`#test` = QC-2/3/4/5 (rows §1.1). Rows below are mechanisms that exist only in a pipeline.
|
||||||
|
|
||||||
|
| check | location | kind | what it actually verifies | enforcement point | canonical check | disposition | rationale |
|
||||||
|
| -------------------------------------- | -------------------------------------------------------------------------------------- | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------- | ----------------------------------- | --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------- |
|
||||||
|
| Frozen install | `ci.yml#install` | pipeline-step | `pnpm install --frozen-lockfile --prefer-offline` against the baked ci-base store — lockfile supply integrity; a drifted lockfile fails the build before any gate runs | `CI ci.yml#install` | QC-1 Checkout integrity | preserve | Lockfile-pinned dep resolution is the supply-chain floor under every later gate. |
|
||||||
|
| Test-step readiness prelude | `ci.yml#test` prologue | pipeline-step | Installs pinned `@earendil-works/[email protected]` (Invariant R suite requires the real binary) + openssl; waits up to 60×1s on `pg_isready` for the `ci-postgres` service and fails fast if it never comes up; runs `db:migrate` before tests | `CI ci.yml#test` | QC-5 Test suite execution | preserve | Fail-fast environment preconditions — a missing service produces a legible failure, not a wall of red tests. |
|
||||||
|
| Publish verify step (pending RI-1-001) | `publish.yml#verify` (branch `feat/ri-050-publish-gate` @ `46784c8d`, not yet on next) | pipeline-step | (a) Commit identity: fails closed if `CI_COMMIT_SHA` empty, `git rev-parse HEAD` empty, or the two differ; (b) runs the canonical `pnpm verify:release`. **Every publish effect depends on this step; it carries no path filter** | `publish.yml#verify` | QC-11 Terminal release verification | preserve | The RI-N1 exact-commit binding; until it merges, publish steps on next depend on `build` only (see §3 gap 1). |
|
||||||
|
| Publish error classification | `publish.yml#publish-npm` | pipeline-step | Publishes `@mosaicstack/*` (minus web) and classifies outcome: success, or the **only tolerated failure** = already-published (EPUBLISHCONFLICT / "cannot publish over" / "previously published"); explicit fatal on npm `E404/E401/ENEEDAUTH/ECONNREFUSED/ETIMEDOUT/ENOTFOUND` and on any unrecognized failure (replacing the old ` | | echo` that hid a registry 404) | `publish.yml#publish-npm` (main/tags, path-filtered on `packages/**`) | QC-12 Publish-effect integrity | preserve | Converts silent publish fall-on-floor into loud failure; allowlist-of-one error tolerance is the right shape. |
|
||||||
|
| Next-lane publish assertions | `publish.yml#publish-next-npm` | pipeline-step | Guards: branch must be `next`, `CI_PIPELINE_NUMBER` required; registry dist-tags JSON must be usable; walks all manifests, strictly parses stable semver, rewrites `X.Y.(Z+1)-next.<N>`; publishes with `--tag next` (never latest); post-publish asserts `npm view @mosaicstack/mosaic@next` resolves to the exact expected version | `publish.yml#publish-next-npm` (push/manual on next) | QC-12 Publish-effect integrity | preserve | Durable prerelease lane with end-to-end resolution proof — the published artifact is verified, not assumed. |
|
||||||
|
| Image destination policy | `publish.yml#build-gateway` / `#build-appservice` / `#build-web` | pipeline-step | Kaniko builds with destination policy: `next` ⇒ sha-tag only (fatal if a tag event sneaks in); `main` ⇒ sha + `latest`; tag events ⇒ sha + `<tag>`; anything else fatal. Path filters only skip **effects**, never the verify step | `publish.yml#build-*` | QC-12 Publish-effect integrity | preserve | Fail-closed tagging matrix; the exclude-list default-safe design keeps stale images impossible. |
|
||||||
|
|
||||||
|
Adjacent pipeline surface (not a probe): `.woodpecker/ci-image.yml` rebuilds the ci-base image on `pnpm-lock.yaml`/`Dockerfile.ci` change with an immutable `lock-<hash>` tag; pipelines consume `:latest`. Recorded for completeness — no code-quality property is checked.
|
||||||
|
|
||||||
|
### 1.7 Root installer tooling (`tools/`)
|
||||||
|
|
||||||
|
| check | location | kind | what it actually verifies | enforcement point | canonical check | disposition | rationale |
|
||||||
|
| --------------------------- | --------------------------------------------------------- | ----- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------- | ------------------------------- | ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||||
|
| Next-lane installer test | `tools/install-next-lane.test.sh` (`pnpm test:installer`) | shell | Drives `tools/install.sh --next` with faked `node`/`npm` binaries (no network): Node 20 must be rejected; installs must pin **exact** versions (mutable `@next` forbidden); fast path must not unexpectedly fall back to source; gateway-install failure takes the documented fallback | `turbo`-external tail of `pnpm test` → `CI ci.yml#test` | QC-5 Test suite execution | preserve | Hermetic (shimmed) regression net for the installer lane; runs as part of the standard test command. |
|
||||||
|
| Clean-container install E2E | `tools/e2e-install-test.sh` | shell | Full first-run flow in a node:22-alpine container: `install.sh --yes` → `mosaic wizard` (non-interactive) → `mosaic gateway install` → `mosaic gateway verify` exit check (with EXPECTED-SKIP if the installed CLI predates `gateway verify`); skips gracefully without Docker | `local` (manual; requires Docker); **not wired in CI** | QC-5 Test suite execution | strengthen (review) | The only end-to-end proof of the install→verify path; currently operator-initiated only — wire into a periodic/manual CI lane or sign its exclusion explicitly. |
|
||||||
|
| Host installer advisories | `tools/install.sh` (`--check`; `check_fleet_transport`) | shell | `--check` = version comparison only, no install; `check_fleet_transport` warns (non-blocking, by design — tmux is the fleet's dependency, not mosaic's) when the roster-declared transport binary is absent, naming exactly what it blocks; PATH-persistence warnings | `installer` (operator-run) | QC-18 Operator-host drift audit | preserve | Advisory-by-design warnings; the parallel doctor check is drift-tested by §1.3's harness. |
|
||||||
|
|
||||||
|
### 1.8 Pending workstream additions (branch `feat/ri-050-publish-gate` @ `46784c8d`)
|
||||||
|
|
||||||
|
| check | location | kind | what it actually verifies | enforcement point | canonical check | disposition | rationale |
|
||||||
|
| ------------------------------- | ---------------------------------------------------- | ---- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- | ----------------------------------- | ----------- | ---------------------------------------------------------------------------------------------- |
|
||||||
|
| Canonical terminal verification | `scripts/verify-release.mjs` (`pnpm verify:release`) | ts | One command replaying the full mandatory set as stages — sanitization, upgrade-guard, typecheck (incl. preflight), lint, format, test, build — mirroring `ci.yml` step-for-step; fail-fast on first failing command; requires `bash`+`rsync` on PATH; `--stage <name>` for wiring smoke-tests only | `publish.yml#verify` (pending); `local` (`pnpm verify:release`) | QC-11 Terminal release verification | preserve | The RI-N1 canonical command — CI and publication share one semantic checklist by construction. |
|
||||||
|
| Verify-parity contract test | `scripts/verify-release.test.mjs` | ts | Parses the real `ci.yml`/`publish.yml`: stage table must match ci.yml step-for-step; every publish-effect step (name `publish*` or image-pushing) must transitively depend on `verify`; commit-identity assertion must be present; `verify` must carry no path filter | `test:checkout` → `CI ci.yml#test` (once merged) | QC-11 Terminal release verification | preserve | Guard-of-the-guard at checkout time — the two surfaces cannot drift apart silently. |
|
||||||
|
|
||||||
|
## 2. Canonical check set
|
||||||
|
|
||||||
|
The deduplicated checks every row above maps onto. IDs are stable for RI-3-002 to consume.
|
||||||
|
|
||||||
|
- **QC-1 Checkout integrity.** Owns: the checkout can run its gates — frozen-lockfile dependency resolution, required gate binaries present, no stale build lock, and the `apps/web/.next` generated-state trust chain (real directory, uid ownership, certified source fingerprint, certified symlink manifest). Implemented by `scripts/preflight.mjs` + frozen install steps.
|
||||||
|
- **QC-2 Workspace typecheck.** Owns workspace-wide TypeScript soundness: per-package `tsc --noEmit` over built dependencies (`turbo typecheck`). The single definition invoked by CI, pre-push, and terminal verification.
|
||||||
|
- **QC-3 Workspace lint.** Owns static-analysis policy: per-package ESLint under the root config. One config, one task, every surface.
|
||||||
|
- **QC-4 Format check.** Owns formatting uniformity: Prettier check with the repo ignore list. (The pre-commit variant additionally fixes; the verdict form is this check.)
|
||||||
|
- **QC-5 Test suite execution.** Owns execution of all test surfaces: checkout script units (`node --test`), per-package Vitest suites (including the framework shell chain and its python unitests), the installer-lane shim test, and — once wired — `test-roster-schema.py` and container E2E. Also owns guards-of-the-gate that live inside the chain (terminal-green contract, RCE regression).
|
||||||
|
- **QC-6 Workspace build.** Owns artifact buildability: `turbo build` producing the artifacts publication consumes.
|
||||||
|
- **QC-7 Framework sanitization.** Owns the open-source guarantee for the shipped framework package: no operator-identity tokens anywhere (examples included), no private `$HOME` defaults in shipped scripts, with a self-test that keeps the regexes honest.
|
||||||
|
- **QC-8 Resident-context budget.** Owns the line-count ceilings on framework files injected into every agent's context (Constitution, dispatcher, RUNTIME.md slices) — the CI-enforceable half of the resident-prompt budget.
|
||||||
|
- **QC-9 Test-membership enumeration.** Owns the property that no test suite can silently fall out of CI: disk population vs parsed enumeration surfaces, both-directions staleness, and signed exclusions with reasons. Includes its needle/control harness.
|
||||||
|
- **QC-10 Upgrade/install safety.** Owns the #791 family: operator-path byte-identity across keep-mode upgrades (manifest guard), mid-failure rollback (errtrace-proven), durable pre-update snapshot + verify net + CWE-59 leaf guard, and the v2→v3 migration matrix with shell/TS parity.
|
||||||
|
- **QC-11 Terminal release verification.** Owns the RI-N1 exact-commit binding: commit-identity assertion plus one canonical command (`pnpm verify:release`) replaying the complete mandatory set, with every publish effect depending on it; plus the checkout-time parity/DAG contract test that keeps pipeline and command in sync.
|
||||||
|
- **QC-12 Publish-effect integrity.** Owns publication correctness: npm publish error classification (only already-published tolerated), next-lane versioning and post-publish resolution proof, and image destination/tag policy.
|
||||||
|
- **QC-13 Staged-change hygiene.** Owns commit-time hygiene on staged files (prettier/eslint fix-and-restage) and the self-verifying hook wiring that guarantees the gates are actually installed.
|
||||||
|
- **QC-14 Pre-push gate.** Owns the local push composition: preflight + typecheck + lint + format:check (tests deliberately deferred to CI).
|
||||||
|
- **QC-15 Lease-gate architecture invariant.** Owns "no ungated runtime launches in production code": the scan + allowlist over `packages/`, `apps/`, `plugins/`, `tools/`.
|
||||||
|
- **QC-16 Agent-runtime edit-time checks.** Owns edit-time feedback on agent hosts: the deps-preflight legibility sentinel and typecheck-on-edit, plus their regression harnesses.
|
||||||
|
- **QC-17 Lease-enforcement wiring safety.** Owns the #869 C1/C2/C5 trio: activation capability probe (versioned contract), enforcement-hook wiring gate (default-deny with explicit opt-out), and the doctor check that surfaces a bricked host — with their shell/TS harnesses.
|
||||||
|
- **QC-18 Operator-host drift audit.** Owns host-state health CI cannot see: `mosaic doctor` drift audit (+ fleet transport, both implementations), `fleet doctor` roster classification, `gateway doctor`/`gateway verify` service health, and installer advisories. Advisory exits are part of the contract.
|
||||||
|
- **QC-19 Downstream rails presence check.** Owns "does a scaffolded project still carry its rails files" — today the TS `quality-rails check/doctor` presence loop; per RI-N4 this is the seed that must become the typed evaluator (presence alone is explicitly not parity).
|
||||||
|
- **QC-20 Downstream enforcement verification.** Owns "do the rails actually block" on scaffolded projects: the behavioral planted-commit probe (type error, `any`, lint, gitleaks secret) currently in `verify.sh`/`verify.ps1` behind the `mosaic-quality-verify` adapter.
|
||||||
|
- **QC-21 Downstream rails scaffolding.** Owns putting rails files into a target project: the shell template installer (+ PowerShell twin) and the TS `quality-rails init` scaffolder — currently two paths that must converge.
|
||||||
|
|
||||||
|
## 3. Coverage gaps
|
||||||
|
|
||||||
|
Enforced nowhere but implied, or named in docs/tooling but not wired:
|
||||||
|
|
||||||
|
1. **Publication not yet bound to verification on `next`.** At this base (`8199261c`), `publish.yml` publish steps depend on `build` only; the `verify` step and `scripts/verify-release.mjs` exist on `feat/ri-050-publish-gate` (`46784c8d`) but are not merged. Until RI-1-001 lands, AC-RI-1's negative control cannot hold on the real pipeline.
|
||||||
|
2. **Playwright E2E unwired.** `apps/web` ships `test:e2e` (`playwright test`) with real suites (`admin/auth/chat/navigation.spec.ts`); neither `pnpm test` nor any CI step invokes it. The web UI's user flows are verified only when an operator runs them manually.
|
||||||
|
3. **No secret scanning on this repo.** The framework's own template pre-commit makes gitleaks **required**, and `verify.sh` proves detection with a planted key — but this repository's `.husky/pre-commit` (lint-staged only) and CI run no secret scan. The repo ships the control it does not use.
|
||||||
|
4. **No dependency audit.** The quality `.woodpecker.yml` templates and `docs/CI-SETUP.md` specify `npm audit --audit-level=high` as a pipeline stage; nothing equivalent runs for this repo.
|
||||||
|
5. **No coverage thresholds.** Templates enforce 80% Jest coverage thresholds; this repo's Vitest configs collect coverage with no thresholds — coverage is measured nowhere and enforced nowhere.
|
||||||
|
6. **`test-roster-schema.py` invisible.** A real jsonschema regression suite wired to no surface and invisible to the enumeration guard (its population is `*.sh`; the suite is `.py`). Either enumerate it or sign an exclusion — silence here is the #1017 defect shape.
|
||||||
|
7. **Presence-checker expectations ≠ this repo.** `quality-rails check` expects `.eslintrc`, `biome.json`, `.githooks/pre-commit`, `PR-CHECKLIST.md` for node projects — none describe this monorepo (husky, flat eslint config, no biome, no PR-CHECKLIST.md). The evaluator's check set must be per-subject (versioned, digested), not one global file list.
|
||||||
|
8. **Chain-ordering residual (documented).** `test:framework-shell` is one `&&` chain: a failing link skips every later suite while the step still fails (measured in #1270 — four suites after position 44 had not run since a prior merge). The enumeration guard proves naming, not reachability; both residuals are in-file documented but structurally unfixed.
|
||||||
|
9. **Signed-exclusion burndown open.** 16 signed exclusions remain in `test-enumeration-exclusions.txt`; several are "unmeasured in CI image" or blocked on missing CI tooling (tmux, setsid) — tracked under #1017/#1271. Each is an enforcement promise deferred, not delivered.
|
||||||
|
10. **Windows twins unexercised.** `verify.ps1`, `install.ps1`, `mosaic-doctor.ps1` have no runner anywhere (no Windows CI); behavioral drift from their bash twins is undetectable by construction.
|
||||||
|
11. **QA hook name vs behavior.** `qa-hook-handler.sh` files remediation report templates but performs no verification; the seam's actual gate value is only the deps-preflight sentinel. Anything relying on "QA automation hook" as a check is relying on report-filing.
|
||||||
|
12. **Two test paths, one gated.** CI runs tests against ci-postgres (`DATABASE_URL` set); the local PGlite path is the documented default (AGENTS.md) until KBN-101-02/101-05. Only the CI path is enforced by pipeline.
|
||||||
|
|
||||||
|
## 4. Disposition summary
|
||||||
|
|
||||||
|
| disposition | rows | checks |
|
||||||
|
| ------------------- | ---- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||||
|
| preserve | 43 | Every canonical owner (QC-1..QC-18) plus correct guards-of-the-guard and thin adapters: all of §1.1, the CI-invoked framework probes and adapters in §1.2, all of §1.3, the C1/C2/C5 trio and doctors in §1.4, all of §1.5, all pipeline-only steps in §1.6, §1.7 rows 1 and 3, and §1.8. |
|
||||||
|
| strengthen | 2 | `quality-rails check` and `quality-rails doctor` (QC-19) — the RI-N4 evaluator seed: typed verdicts, versioned/digested check definitions, per-subject check sets. |
|
||||||
|
| strengthen (review) | 9 | `verify.sh` + `verify.ps1` (QC-20), quality `install.sh`/`install.ps1` + `quality-rails init` (QC-21 — scaffold-path convergence), `test-roster-schema.py` (QC-5 — wire or sign), `qa-hook-stdin.sh` seam + `typecheck-hook.sh` (QC-16), `tools/e2e-install-test.sh` (QC-5 — CI lane). |
|
||||||
|
| retire | 0 | None meet the bar: RI-N4 requires effective shell probes be **absorbed before** their paths retire, and no absorption exists yet. The `strengthen (review)` rows are the retirement candidates for RI-3-002 once the evaluator owns their behavior. |
|
||||||
|
|
||||||
|
Row total: 54. Canonical checks: 21 (QC-1..QC-21).
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
# #1099 pipefail + early-exit sweep
|
||||||
|
|
||||||
|
Baseline: `df4c591ab42aa1ae62c12935fdc0e772684864a0`
|
||||||
|
|
||||||
|
This is a site inventory, not a risk count. `FIXED` means the early-exiting consumer no longer has a piped upstream process whose SIGPIPE can become the result under `pipefail`. `NOT-LOAD-BEARING` means the pipeline status is explicitly discarded. `UNREACHABLE-AND-WHY` describes designed input, not a payload-size safety claim.
|
||||||
|
|
||||||
|
## Tranche 1 — runtime and general scripts
|
||||||
|
|
||||||
|
| Baseline site | Verdict | Construction / reason |
|
||||||
|
| ------------------------------------------------------------------- | ------- | ---------------------------------------------------------------------------------------- |
|
||||||
|
| `tools/matrix-presence-harness/run.sh:38` | FIXED | nullglob array selects the first path; no pipeline |
|
||||||
|
| `tools/e2e-install-test.sh:139` | FIXED | capture help completely, then grep via redirection |
|
||||||
|
| `tools/install.sh:312` | FIXED | NUL `mapfile` reads all roots; count != 1 reaches the named malformed-archive diagnostic |
|
||||||
|
| `scripts/analysis/reflect-board-history.sh:76` | FIXED | capture Git history completely, then grep via redirection |
|
||||||
|
| `scripts/analysis/reflect-git-history.sh:67` | FIXED | grep reads from a here-string |
|
||||||
|
| `scripts/analysis/reflect-git-history.sh:69` | FIXED | grep reads from a here-string |
|
||||||
|
| `packages/mosaic/framework/tools/authentik/user-create.sh:72` | FIXED | jq `first(...)` reads the response directly |
|
||||||
|
| `packages/mosaic/framework/tools/git/mutate-push-guard.sh:87` | FIXED | grep `-m1` reads the file directly; downstream `cut` consumes its complete scalar output |
|
||||||
|
| `packages/mosaic/framework/tools/orchestrator/session-resume.sh:94` | FIXED | `mapfile` plus bounded indexed loop replaces `head` pipeline |
|
||||||
|
| `packages/mosaic/framework/tools/prdy/prdy-status.sh:69` | FIXED | grep reads from a here-string |
|
||||||
|
| `packages/mosaic/framework/tools/qa/reflect-stop-hook.sh:172` | FIXED | grep reads from a here-string |
|
||||||
|
| `packages/mosaic/framework/tools/qa/reflect-stop-hook.sh:173` | FIXED | grep reads from a here-string |
|
||||||
|
| `packages/mosaic/framework/tools/qa/reflect-stop-hook.sh:174` | FIXED | grep reads from a here-string |
|
||||||
|
| `packages/mosaic/framework/tools/qa/reflect-stop-hook.sh:175` | FIXED | grep reads from a here-string |
|
||||||
|
| `packages/mosaic/framework/tools/qa/reflect-stop-hook.sh:176` | FIXED | grep reads from a here-string |
|
||||||
|
| `packages/mosaic/framework/tools/qa/reflect-stop-hook.sh:177` | FIXED | grep reads from a here-string |
|
||||||
|
| `packages/mosaic/framework/tools/qa/reflect-stop-hook.sh:178` | FIXED | grep reads from a here-string |
|
||||||
|
| `packages/mosaic/framework/tools/qa/typecheck-hook.sh:16` | FIXED | Bash regex extracts the first field without a pipeline |
|
||||||
|
| `packages/mosaic/framework/tools/qa/typecheck-hook.sh:56` | FIXED | grep and bounded sed each read from a here-string |
|
||||||
|
| `packages/mosaic/framework/tools/tmux/send-message.sh:113` | FIXED | grep reads from a here-string |
|
||||||
|
| `packages/mosaic/framework/tools/tmux/send-message.sh:124` | FIXED | grep reads from a here-string |
|
||||||
|
| `packages/mosaic/framework/tools/wake/detector.sh:126` | FIXED | one awk reads the manifest directly and exits after the first exact key |
|
||||||
|
| `packages/mosaic/framework/tools/wake/detector.sh:270` | FIXED | grep reads from a here-string |
|
||||||
|
| `packages/mosaic/framework/tools/wake/detector.sh:278` | FIXED | grep reads from a here-string |
|
||||||
|
| `packages/mosaic/framework/tools/wake/digest.sh:647` | FIXED | capture complete locator output, then select first line by parameter expansion |
|
||||||
|
| `packages/mosaic/framework/tools/wake/reconcile.sh:149` | FIXED | one awk reads the manifest directly and exits after the first exact key |
|
||||||
|
|
||||||
|
## Explicit withdrawn / non-load-bearing sites
|
||||||
|
|
||||||
|
| Baseline site | Verdict | Reason |
|
||||||
|
| ---------------------------------------------------------------------------- | ------------------- | ------------------------------------------------------------------------------------------------------------------------- | --- | --------------------------------------- |
|
||||||
|
| `tools/install.sh:182` | NOT-LOAD-BEARING | ` | | true` explicitly discards lookup status |
|
||||||
|
| `tools/install.sh:356` | UNREACHABLE-AND-WHY | `pnpm pack` writes one matching CLI tarball into a fresh directory immediately before lookup; citation withdrawn in #1099 |
|
||||||
|
| `tools/install.sh:357` | UNREACHABLE-AND-WHY | same fresh-directory invariant for gateway tarball; citation withdrawn in #1099 |
|
||||||
|
| `tools/install.sh:627` | NOT-LOAD-BEARING | ` | | true` explicitly discards lookup status |
|
||||||
|
| `scripts/agent/session-start.sh:70` | NOT-LOAD-BEARING | optional scratchpad lookup has ` | | true` |
|
||||||
|
| `packages/mosaic/framework/templates/repo/scripts/agent/session-start.sh:58` | NOT-LOAD-BEARING | optional scratchpad lookup has ` | | true` |
|
||||||
|
| `packages/mosaic/framework/tools/qa/qa-hook-stdin.sh:25` | UNREACHABLE-AND-WHY | withdrawn in #1099 after designed-input reachability measurement; preserved without re-litigation |
|
||||||
|
| `packages/mosaic/framework/tools/qa/qa-hook-stdin.sh:27` | UNREACHABLE-AND-WHY | same withdrawn designed-input finding |
|
||||||
|
| `packages/mosaic/framework/tools/qa/qa-hook-stdin.sh:30` | UNREACHABLE-AND-WHY | same withdrawn designed-input finding |
|
||||||
|
| `packages/mosaic/framework/tools/qa/qa-hook-stdin.sh:32` | UNREACHABLE-AND-WHY | same withdrawn designed-input finding |
|
||||||
|
| `packages/mosaic/framework/tools/qa/qa-hook-stdin.sh:34` | UNREACHABLE-AND-WHY | same withdrawn designed-input finding |
|
||||||
|
|
||||||
|
## Tranche 2 — non-wake test harnesses
|
||||||
|
|
||||||
|
All 22 baseline sites below are `FIXED`; the checked-in tranche fixture is passed through the same scanner and asserts all 22 occurrences and 21 normalized identities (the same response-split line occurs twice).
|
||||||
|
|
||||||
|
| Baseline site(s) | Verdict | Construction |
|
||||||
|
| ------------------------------------------------------ | ------- | ------------------------------------------------------------- |
|
||||||
|
| `systemd/user/test-fleet-units.sh:148` | FIXED | capture tmux output, then grep via redirection |
|
||||||
|
| `git/test-issue-comment-readback.sh:283,302` | FIXED | parameter expansion splits status/body without `head` |
|
||||||
|
| `git/test-pr-review-gitea-comment.sh:228` | FIXED | parameter expansion splits status/body |
|
||||||
|
| `git/test-lane-brief-pr-linkage.sh:72` | FIXED | grep reads from a here-string |
|
||||||
|
| `git/test-pr-review-repo-host-override.sh:225-226` | FIXED | grep reads from a here-string |
|
||||||
|
| `orchestrator/smoke-test.sh:67,72` | FIXED | parameter expansion selects first line |
|
||||||
|
| `orchestrator/test-board-roll.sh:99-100` | FIXED | grep reads from a here-string |
|
||||||
|
| `quality/scripts/test-upgrade-durable-snapshot.sh:180` | FIXED | complete sorted output is read with `mapfile`, then indexed |
|
||||||
|
| `quality/scripts/test-upgrade-rollback.sh:339,356` | FIXED | direct `grep -m1` file reads; cleanup captures before testing |
|
||||||
|
| `tmux/test-send-message-socket.sh:37,38,44-46,68,72` | FIXED | capture commands complete before redirected grep assertions |
|
||||||
|
| `tmux/test-send-message-verdict.sh:34` | FIXED | grep reads from a here-string |
|
||||||
|
|
||||||
|
## Tranche 3 — wake validation harnesses
|
||||||
|
|
||||||
|
All 26 baseline occurrences (25 normalized identities; one preimage selector occurs twice) are `FIXED` and mechanically bound through the wake fixture and shared scanner.
|
||||||
|
|
||||||
|
| Baseline site(s) | Verdict | Construction |
|
||||||
|
| -------------------------------------------------------------------------------------------- | ------- | -------------------------------------------------------------------------------------------------------------- |
|
||||||
|
| `wake/test-wake-digest-quarantine.sh:567` | FIXED | complete match populations are captured, then first line selected by parameter expansion |
|
||||||
|
| `wake/test-wake-preimage.sh:182-183,346-347` | FIXED | jq `first(...)` reads each JSONL file directly |
|
||||||
|
| `wake/validate-973/microtest-wake-assert.sh:153,170-171,176,204-209,233-234,251-252,286-287` | FIXED | scalar assertions use here-strings; diagnostics use non-early sed ranges; source line captured before matching |
|
||||||
|
| `wake/validate-973/validate-973.sh:110,119,180,182,187` | FIXED | scalar assertions use here-strings; diagnostic truncation uses consuming sed ranges |
|
||||||
|
|
||||||
|
The scoped inventory is complete: 26 runtime/general + 22 non-wake tests + 26 wake tests fixed; 11 explicitly withdrawn or non-load-bearing sites retain their documented verdicts.
|
||||||
@@ -0,0 +1,229 @@
|
|||||||
|
# #1043 — Fleet pane git-identity propagation
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
|
||||||
|
Ensure a fleet seat's launched runtime process receives its roster-derived `MOSAIC_GIT_IDENTITY`, and lock the complete generated-environment propagation boundary with an enumerated set comparison.
|
||||||
|
|
||||||
|
## Tracking
|
||||||
|
|
||||||
|
- External issue: `mosaicstack/stack#1043`
|
||||||
|
- Branch: `fix/1043-pane-git-identity`
|
||||||
|
- Coordinator: `tl-mosaic`
|
||||||
|
- `docs/TASKS.md`: read-only by project worker contract; not modified.
|
||||||
|
|
||||||
|
## Constraints
|
||||||
|
|
||||||
|
- RED-first bug reproducer is mandatory.
|
||||||
|
- R7 delete-the-subject mutation must turn the behavioral test red.
|
||||||
|
- Assert launched-process environment, not source text.
|
||||||
|
- One push only; do not poll CI after push.
|
||||||
|
- Run the CI queue guard immediately before push and report its `state=` line as state, not evidence.
|
||||||
|
- Do not modify a live host launcher or obtain/copy another credential.
|
||||||
|
- Self-post the PR, verify provider attribution, then stop.
|
||||||
|
- Final status wording: `believed-fixed, pending jarvis validation`.
|
||||||
|
|
||||||
|
## Scope inventory
|
||||||
|
|
||||||
|
Re-derived against `origin/main` at `85d2108e`:
|
||||||
|
|
||||||
|
- Launch consumer: `packages/mosaic/framework/tools/fleet/start-agent-session.sh`
|
||||||
|
- Behavioral launch test: `packages/mosaic/framework/tools/fleet/test-start-agent-session.sh`
|
||||||
|
- Generated-environment contract/parser: `packages/mosaic/src/fleet/generated-env-boundary.ts`
|
||||||
|
- Roster projection producers:
|
||||||
|
- `packages/mosaic/src/commands/fleet.ts`
|
||||||
|
- `packages/mosaic/src/fleet/fleet-reconciler.ts`
|
||||||
|
- `packages/mosaic/src/fleet/fleet-agent-crud.ts`
|
||||||
|
- `packages/mosaic/src/fleet/v1-v2-migration.ts`
|
||||||
|
- Contract and producer tests discovered by repository search.
|
||||||
|
- Generated-environment operator/developer docs and their executable documentation contract test.
|
||||||
|
|
||||||
|
Discrepancy sent to `tl-mosaic`: current main no longer contains the charter's `PANE_SHELL_SNIPPET`; #772 replaced it with an `/usr/bin/env -i` argv launch boundary, and current generated projections do not declare git identity. Code-read inventory is **NOT MEASURED** behavior.
|
||||||
|
|
||||||
|
## Plan
|
||||||
|
|
||||||
|
1. Add the process-environment set-comparison regression first and record RED.
|
||||||
|
2. Add roster-derived `MOSAIC_GIT_IDENTITY=<agent name>` to the complete generated projection contract.
|
||||||
|
3. Validate identity syntax and equality with `MOSAIC_AGENT_NAME`; pass it through the clean pane environment.
|
||||||
|
4. Update affected projection tests and generated-environment docs.
|
||||||
|
5. Run focused and baseline gates.
|
||||||
|
6. Perform R7 by deleting the pane propagation entry, prove RED, restore, and prove GREEN.
|
||||||
|
7. Run independent review, remediate, commit, queue guard, one push, self-post PR, verify provider attribution, and stop without CI polling.
|
||||||
|
|
||||||
|
## Budget
|
||||||
|
|
||||||
|
No explicit token cap was provided. Working cap: one narrow logical unit, no dependency installation unless existing tooling requires it, no unrelated refactor.
|
||||||
|
|
||||||
|
## Evidence log
|
||||||
|
|
||||||
|
### TDD and mutation evidence
|
||||||
|
|
||||||
|
- RED-first, repository launcher: `bash packages/mosaic/framework/tools/fleet/test-start-agent-session.sh` exited 64 on pre-fix source with `code=unknown-key key=MOSAIC_GIT_IDENTITY`. The generated seat could not launch with the required declared identity.
|
||||||
|
- GREEN: the same repository launcher test emitted `ok - start-agent-session generated environment boundary`.
|
||||||
|
- R7 delete-the-subject: removed only `"MOSAIC_GIT_IDENTITY=$MOSAIC_GIT_IDENTITY"` from the repository launch array; the same test exited 1 with `FAIL: runtime pane omitted or changed generated environment keys: MOSAIC_GIT_IDENTITY`.
|
||||||
|
- R7 restoration: restored that launch entry; the same test returned green.
|
||||||
|
- Launcher under test is explicitly `packages/mosaic/framework/tools/fleet/start-agent-session.sh` through the test's `$START`, **not** the stale installed host copy.
|
||||||
|
|
||||||
|
### Situational and focused tests
|
||||||
|
|
||||||
|
- Repository launcher boundary: green, including set comparison of all nine generated projection entries and fail-before-tmux cases for missing, unsafe, mismatched, and local-shadow Git identity.
|
||||||
|
- Fleet systemd launcher integration: `bash packages/mosaic/framework/systemd/user/test-fleet-units.sh` — green.
|
||||||
|
- Focused Mosaic Vitest set: 6 files, 311 tests — green.
|
||||||
|
- `bash -n` on changed shell files — green.
|
||||||
|
- `git diff --check` — green.
|
||||||
|
|
||||||
|
### Baseline gates
|
||||||
|
|
||||||
|
- `pnpm typecheck` — 45/45 tasks green.
|
||||||
|
- `pnpm lint` — 25/25 tasks green.
|
||||||
|
- `pnpm format:check` — green.
|
||||||
|
- `pnpm test:checkout` — green.
|
||||||
|
- Repository-wide Vitest under a hermetic current-version npm prefix: Mosaic 81/81 files and 1510/1510 tests green; other workspace test tasks shown green before the framework-shell phase.
|
||||||
|
- Canonical `pnpm test` is not fully green on this host for unrelated environment-sensitive gates:
|
||||||
|
1. the first two runs exposed the globally installed Mosaic 0.0.48 update banner in three CLI smoke tests expecting empty stderr;
|
||||||
|
2. after isolating that global-version input, the framework wake assertion aborted at the known `#973` Bash `BASH_LINENO` convention check (exit 97; observed `[3 5]`, expected `[3 4]`).
|
||||||
|
No tests were weakened or bypassed; focused changed-surface tests are green. CI remains the canonical clean-environment result and is intentionally not polled after push per charter.
|
||||||
|
|
||||||
|
### Independent review
|
||||||
|
|
||||||
|
- Codex code review first pass: request changes for missing shell rejection-path coverage.
|
||||||
|
- Remediation: added table-driven missing/unsafe/mismatch/local-shadow launcher cases, each asserting no tmux call.
|
||||||
|
- Codex code re-review: **approve**, no findings, confidence 0.88.
|
||||||
|
- Codex security review: risk `none`, no findings, confidence 0.97.
|
||||||
|
|
||||||
|
### Acceptance criteria mapping
|
||||||
|
|
||||||
|
| Acceptance criterion | Evidence |
|
||||||
|
| --- | --- |
|
||||||
|
| AC-FGI-01: launched process receives every generated key/value | Repository launcher process-environment `comm -23` set comparison; GREEN and R7 RED evidence above |
|
||||||
|
| AC-FGI-02: missing, unsafe, or split identity fails before tmux | Table-driven shell cases plus TypeScript generated-boundary tests |
|
||||||
|
| AC-FGI-03: focused/baseline/review evidence recorded | Commands and review outcomes above; host-sensitive full-suite limitations stated explicitly |
|
||||||
|
|
||||||
|
### Documentation checklist
|
||||||
|
|
||||||
|
- PRD updated with #1043 requirements and acceptance criteria.
|
||||||
|
- Fleet launch runbook, generated-env concept, and generated-env reference updated.
|
||||||
|
- No API/OpenAPI, sitemap, user publishing target, deployment, or external docs publication change applies.
|
||||||
|
- `docs/TASKS.md` remains unmodified per its single-writer project contract.
|
||||||
|
|
||||||
|
## Round 2 — PR #1073 review 97 remediation
|
||||||
|
|
||||||
|
### Review blocker
|
||||||
|
|
||||||
|
The launched-process suite was signed-excluded from CI enumeration. Manual GREEN/R7 evidence therefore did not prove a PR workflow could detect regression.
|
||||||
|
|
||||||
|
### RED-first and canonical wiring
|
||||||
|
|
||||||
|
1. Removed the suite's signed exclusion before adding a CI execution path.
|
||||||
|
2. `check-test-enumeration.sh` went RED with exact `UNENUMERATED` output for `test-start-agent-session.sh`: population 49, enumerated 30, excluded 18.
|
||||||
|
3. Added both `framework/tools/fleet/test-start-agent-session.sh` and `framework/systemd/user/test-fleet-units.sh` to `@mosaicstack/mosaic`'s canonical `test:framework-shell` chain.
|
||||||
|
4. The guard returned GREEN: population 49, enumerated 32, excluded 18, surfaces 45. The systemd suite is outside the guard's tools-only population but now has the same explicit canonical execution disposition.
|
||||||
|
|
||||||
|
### Workflow-level R7
|
||||||
|
|
||||||
|
- Deleted only the pane launch entry `"MOSAIC_GIT_IDENTITY=$MOSAIC_GIT_IDENTITY"`.
|
||||||
|
- Ran the exact `.woodpecker/ci.yml` test-step command, `pnpm test`, with only a temporary PATH-scoped npm shim reporting the checkout's current 0.0.49 version so the unrelated global 0.0.48 banner could not preempt the shell chain.
|
||||||
|
- Result: exit 1 at `@mosaicstack/mosaic#test`, with the enumeration guard GREEN followed by `FAIL: runtime pane omitted or changed generated environment keys: MOSAIC_GIT_IDENTITY`.
|
||||||
|
- Restored the launch entry. The canonical `test:framework-shell` chain then reached both newly wired suites and printed both GREEN markers before the known unrelated #973 host-only `BASH_LINENO` abort.
|
||||||
|
- An actual provider PR workflow on the intentionally broken mutant is **NOT MEASURED**: the one-push constraint forbids pushing a red mutant and then a repaired head. Local execution proves the exact PR workflow command and dependency chain go RED on the subject deletion; CI on the repaired pushed head remains canonical.
|
||||||
|
|
||||||
|
### Workflow population
|
||||||
|
|
||||||
|
- **DEFINED:** 3 workflows (`ci.yml`, `ci-image.yml`, `publish.yml`).
|
||||||
|
- **ELIGIBLE for `pull_request`:** 1/3 (`ci.yml`), based on top-level `when:` clauses.
|
||||||
|
- **REPORTED:** Round-1 exact-head provider read reported 1/1 eligible context (`ci/woodpecker/pr/ci`). Post-remediation-head reported count is **NOT MEASURED** by this seat because CI polling is prohibited; workflow definitions and eligibility did not change.
|
||||||
|
|
||||||
|
### Independent remediation review
|
||||||
|
|
||||||
|
- First Round-2 review identified a CI-image blocker: the newly wired launcher suite used Perl, which the Alpine CI base does not install.
|
||||||
|
- Replaced the suite's three Perl-only fixture mutations with POSIX/BusyBox-compatible `sed -i` substitutions; production behavior and assertions are unchanged.
|
||||||
|
- Codex re-review: **APPROVE**, confidence 0.93, no findings.
|
||||||
|
|
||||||
|
### Vitest denominator reconciliation
|
||||||
|
|
||||||
|
The PR's `311/311` is correct for its explicitly named six-file command at both the original and remediation worktrees:
|
||||||
|
|
||||||
|
- generated environment boundary: 24
|
||||||
|
- fleet documentation: 23
|
||||||
|
- Tess service profile: 6
|
||||||
|
- fleet regen command: 27
|
||||||
|
- fleet agent CRUD command: 22
|
||||||
|
- fleet command: 209
|
||||||
|
- total: **311**
|
||||||
|
|
||||||
|
Review 97 reported 312/312 without naming its six files. That is a different or miscounted population and cannot replace the command-scoped 311 denominator; the PR follow-up will name the exact files and arithmetic.
|
||||||
|
|
||||||
|
## Round 3 — Alpine stale-marker portability
|
||||||
|
|
||||||
|
### Objective and plan
|
||||||
|
|
||||||
|
- Replace the GNU-only relative-date fixture with a deterministic POSIX/BusyBox timestamp while preserving the required stale-marker assertion.
|
||||||
|
- Re-run the launcher suite in the canonical `ci-base:latest` Alpine image, then run applicable repository gates and independent review.
|
||||||
|
- Update the PR body to name the repeated GNU-host/Alpine-CI portability pattern, run the mandatory queue guard, push once, verify provider attribution, and stop without CI polling.
|
||||||
|
- Working budget: 8K tokens; scope is one fixture line plus delivery evidence. No production behavior changes.
|
||||||
|
|
||||||
|
### RED-first evidence
|
||||||
|
|
||||||
|
Before the fix, the canonical CI image command
|
||||||
|
`docker run --rm -v "$PWD:/work" -w /work git.mosaicstack.dev/mosaicstack/stack/ci-base:latest bash packages/mosaic/framework/tools/fleet/test-start-agent-session.sh`
|
||||||
|
exited 1 at the stale-marker setup with exact BusyBox output
|
||||||
|
`touch: invalid date '10 seconds ago'`. The prior fresh-marker assertions had already executed, matching pipeline 2233's failure location.
|
||||||
|
|
||||||
|
### Root cause and fix
|
||||||
|
|
||||||
|
The test used GNU `touch -d` relative-date parsing although the PR workflow runs on Alpine/BusyBox. The fixture now uses POSIX `touch -t 200001010000.00`, a fixed timestamp that is unconditionally stale; the stale assertion remains mandatory and was not made tolerant of missing timestamp metadata.
|
||||||
|
|
||||||
|
### Structural pattern
|
||||||
|
|
||||||
|
This is the third GNU-host/Alpine-CI portability defect in the lane: GNU `grep` multi-match counting, Perl-only fixture mutation, and GNU `touch -d` date parsing. The repeated cause is shell suites authored on a GNU host but executed in an Alpine CI image; durable prevention belongs in CI-image execution or portability lint, not assertion weakening.
|
||||||
|
|
||||||
|
### GREEN and quality evidence
|
||||||
|
|
||||||
|
- Focused launcher suite in `ci-base:latest`: exit 0, `ok - start-agent-session generated environment boundary`.
|
||||||
|
- Canonical test step in `ci-base:latest` with the pipeline's `pgvector/pgvector:pg17` service, readiness check, migration, and `pnpm test`: exit 0; 46/46 Turbo tasks; Mosaic 81/81 files and 1510/1510 tests; Gateway 57 passed/5 skipped files and 629 passed/11 skipped tests; enumeration 49 population / 32 enumerated / 18 signed exclusions / 45 named surfaces.
|
||||||
|
- The first image-only `pnpm test` attempt lacked the pipeline PostgreSQL service and failed only on connection refusal after the launcher suite was GREEN. The rerun supplied the canonical service precondition and passed.
|
||||||
|
- Canonical-image baseline: typecheck 45/45 tasks, lint 25/25 tasks, format check GREEN; `git diff --check` GREEN.
|
||||||
|
- Independent Codex code review: APPROVE, confidence 0.96, 2/2 Round-3 files, no findings.
|
||||||
|
- Independent Codex security review: risk none, confidence 0.99, 2/2 Round-3 files, no findings.
|
||||||
|
|
||||||
|
### Re-derived inventory and denominators
|
||||||
|
|
||||||
|
- Round-3 git delta: **2/2 files** — launcher suite and task scratchpad; 25 insertions / 1 deletion before evidence finalization.
|
||||||
|
- Full PR path inventory against `origin/main` at `85d2108e`: **19/19 changed paths**; Round 3 adds no new PR path.
|
||||||
|
- Workflow definition population: **1/3 pull-request-eligible** (`ci.yml` of `ci.yml`, `ci-image.yml`, `publish.yml`).
|
||||||
|
- Do not re-litigate the settled 311/312 populations; both are valid for their separately named Tess6 and CRUD-core7 sets.
|
||||||
|
|
||||||
|
## Round 4 — bound stale-marker observation
|
||||||
|
|
||||||
|
### Objective and plan
|
||||||
|
|
||||||
|
- Make the heartbeat assertion discriminate an initially stale native marker from a fresh marker without changing the production staleness threshold or shortening the polling window.
|
||||||
|
- Freeze only the sidecar's numeric observation clock during the stale-fixture arm so elapsed assertion time cannot turn a fresh mutant stale.
|
||||||
|
- Prove two independent mutants RED: disable production stale-marker detection while retaining the stale fixture; replace the stale fixture with a fresh marker. Restore the tree and prove GREEN in the canonical Alpine image.
|
||||||
|
- Re-derive the changed-path inventory, run applicable quality and independent review gates, commit with environment-only author/committer identity, queue-guard, push once, verify provider attribution using curl stdin config, and stop without CI polling.
|
||||||
|
- Working budget: 8K tokens. Scope is the launcher test and its scratchpad evidence; production launcher behavior remains unchanged.
|
||||||
|
|
||||||
|
### Root cause and bounded observation
|
||||||
|
|
||||||
|
The 30 × 0.1-second assertion window overlaps the production `now - marker > interval * 2 + 1` threshold at interval 1. Depending on second boundaries and load, a fresh marker can age past the threshold before the assertion ends. A focused pre-fix fresh-mutant attempt returned RED while Review 101's full-suite run returned GREEN; the differing result is itself timing dependence, not a discriminating assertion.
|
||||||
|
|
||||||
|
The test now supplies a fixed numeric epoch only to the stale-fixture sidecar. Its real marker mtime is still read from the filesystem, but assertion runtime cannot advance `now`. Date formatting still delegates to the image's real `/bin/date`. Neither the production threshold nor the 30 × 0.1-second polling window changed.
|
||||||
|
|
||||||
|
### Two-mutant RED / restored GREEN
|
||||||
|
|
||||||
|
All three runs used `git.mosaicstack.dev/mosaicstack/stack/ci-base:latest`:
|
||||||
|
|
||||||
|
1. **Stale-detection mutant RED:** replaced only the production stale-age predicate with `false` while retaining the fixed stale marker; suite exit 1 with `FAIL: heartbeat sidecar did not resume after native marker became stale or absent`.
|
||||||
|
2. **Fresh-marker mutant RED:** replaced only `touch -t 200001010000.00` with fresh `touch`; suite exit 1 with the same failed stale-resumption assertion. The fixed observation epoch kept the mutant fresh throughout all 30 polls.
|
||||||
|
3. **Restored tree GREEN:** suite exit 0 with `ok - start-agent-session generated environment boundary`.
|
||||||
|
|
||||||
|
### Re-derived inventory
|
||||||
|
|
||||||
|
- Round-4 delta: **2/2 files** — launcher test plus task scratchpad; production launcher delta is empty.
|
||||||
|
- Full PR inventory against `origin/main`: **19/19 paths**; Round 4 adds no path.
|
||||||
|
- Production stale threshold remains `now - marker > iv * 2 + 1`; assertion polling remains 30 × 0.1 seconds.
|
||||||
|
- Review 101's confirmed enumeration/workflow/CI and attribution evidence is accepted without re-polling or re-derivation.
|
||||||
|
|
||||||
|
## Residual risk
|
||||||
|
|
||||||
|
- Landing on `main` does not update the currently installed host launcher. Host framework installation/reseed and Jarvis live-seat validation are separate downstream events.
|
||||||
|
- Canonical CI result is pending and will not be polled by this seat.
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
# #1098 — Framework shell portability / red main
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
|
||||||
|
Restore terminal-green `main` by making the `test-start-agent-session.sh` clean-environment assertion semantic and portable without removing either newly enumerated framework-shell suite.
|
||||||
|
|
||||||
|
## Scope
|
||||||
|
|
||||||
|
- Tracking issue: `mosaicstack/stack#1098`
|
||||||
|
- Branch: `fix/framework-shell-portability`
|
||||||
|
- Base: `origin/main` at `4fa2768962702d53e16e8b67ee6ad52ebcb0910e`
|
||||||
|
- Primary file: `packages/mosaic/framework/tools/fleet/test-start-agent-session.sh`
|
||||||
|
- Requirements source: `docs/PRD.md` § Framework shell assertion portability (#1098)
|
||||||
|
- Out of scope: deployed files under `~/.config/mosaic`, pnpm-store cleanup, checkout deletion, and changes to the launcher’s `/usr/bin/env -i` behavior.
|
||||||
|
|
||||||
|
## Acceptance criteria
|
||||||
|
|
||||||
|
1. The test inspects the captured NUL-delimited tmux argv semantically and accepts an adjacent `/usr/bin/env`, `-i` pair regardless of trailing payload size or pipe scheduling.
|
||||||
|
2. Missing `/usr/bin/env`, missing `-i`, and non-adjacent `-i` remain failures.
|
||||||
|
3. Failure output includes the observed argv records with stable indexes and shell escaping; it exposes no credentials because this fixture supplies only generated non-secret launch data.
|
||||||
|
4. The focused suite passes on the dev host and in the repository CI image; the blocking PR/main pipeline returns terminal green.
|
||||||
|
5. Independent review passes; PR is squash-merged and #1098 is closed only after merged-main CI is terminal green.
|
||||||
|
|
||||||
|
## Budget
|
||||||
|
|
||||||
|
- ASSUMPTION: 30K-token working budget; rationale: one shell-test defect plus full PR/CI lifecycle.
|
||||||
|
- Auto-reduction: focused shell and package gates first; rely on canonical Woodpecker for the full monorepo suite rather than duplicating a dependency install under constrained `/home`.
|
||||||
|
- Disk baseline before clone/build: `/home` 7.1G free (99% used), `/tmp` 2.4G free (92% used).
|
||||||
|
|
||||||
|
## Investigation
|
||||||
|
|
||||||
|
### First-hand CI evidence
|
||||||
|
|
||||||
|
- Public log: `GET https://ci.mosaicstack.dev/api/repos/47/logs/2269/53041`
|
||||||
|
- Decoded 1,436 entries (11 null `data` entries treated as empty log rows), 190,756 bytes.
|
||||||
|
- Failure: `FAIL: pane command did not clear its environment` immediately after the expected pane-PID warning.
|
||||||
|
- BusyBox primitives, complete assertion pipeline, real CI image, stale/current image digests, Turbo cache masking, gateway failure, and heartbeat-sidecar concurrent writing were independently excluded.
|
||||||
|
|
||||||
|
### Root cause
|
||||||
|
|
||||||
|
The assertion ends in:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
printf '%s\n' "$pane_args" | tail -n +"$after_pane_env" | grep -qxF -- '-i'
|
||||||
|
```
|
||||||
|
|
||||||
|
The script has `set -o pipefail`. `grep -q` exits as soon as it finds the valid `-i` record. Upstream `tail`/`printf` can then receive SIGPIPE, making the aggregate pipeline nonzero even though grep returned 0 and the semantic property is true. This depends on payload size, pipe capacity, and scheduling, explaining a local/image pass with a CI failure.
|
||||||
|
|
||||||
|
Discriminating stress control with `/usr/bin/env` followed immediately by `-i`:
|
||||||
|
|
||||||
|
- 8,192-byte trailing payload: `printf=0 tail=0 grep=0`, aggregate 0.
|
||||||
|
- 16,384-byte trailing payload: `printf=0 tail=141 grep=0`, aggregate 141.
|
||||||
|
- 32,768+ bytes: `printf=141 tail=141 grep=0`, aggregate 141.
|
||||||
|
- A full-reading `grep -xF` control remained 0 for every payload.
|
||||||
|
|
||||||
|
This is a third branch omitted by the earlier present-vs-corrupted split: the pair can be present and intact while `pipefail` reports an upstream SIGPIPE.
|
||||||
|
|
||||||
|
## TDD plan
|
||||||
|
|
||||||
|
1. RED: preserve the one-off stress reproducer above and add an automated large-argv semantic regression that fails under the current pipeline implementation.
|
||||||
|
2. GREEN: parse the authoritative NUL-delimited capture into a Bash array and search for an adjacent `/usr/bin/env`, `-i` pair without a short-circuit pipeline.
|
||||||
|
3. Add negative controls for missing, detached, and reversed tokens.
|
||||||
|
4. On failure, print indexed `%q` argv records before returning nonzero.
|
||||||
|
5. Run focused suite, mutation controls, shell syntax/format checks, then repository baseline gates feasible without dependency installation.
|
||||||
|
6. Independent review, queue guard, push, PR, CI, coordinator merge authorization, squash merge, merged-main CI, issue close.
|
||||||
|
|
||||||
|
## Progress
|
||||||
|
|
||||||
|
- [x] Checkout created and based on `origin/main` `4fa27689`.
|
||||||
|
- [x] CI log decoded directly.
|
||||||
|
- [x] Root-cause stress control reproduced semantic match + aggregate pipeline failure.
|
||||||
|
- [x] RED evidence: intact `/usr/bin/env`, `-i` fixture produced component statuses `0/141/0` and aggregate 141 under the former `grep -q` pipeline; full-reading semantic control stayed 0.
|
||||||
|
- [x] GREEN implementation: direct NUL-argv adjacency parser, indexed diagnostics, and full-reading scalar predicates replace all load-bearing early-exit pipelines in this test.
|
||||||
|
- [x] Baseline/situational tests:
|
||||||
|
- focused launcher suite: PASS on GNU host and cached Alpine CI image;
|
||||||
|
- paired `test-fleet-units.sh`: PASS;
|
||||||
|
- enumeration guard: PASS (`population=53`, `enumerated=36`, `excluded=18`), 14/14 mutation needles;
|
||||||
|
- `bash -n`, ShellCheck, `git diff --check`: PASS;
|
||||||
|
- static denominator after change: zero load-bearing `grep -q`/`head`/`-m1` pipeline candidates in `test-start-agent-session.sh`;
|
||||||
|
- delete-the-subject mutation removing production `-i`: RED with 78 indexed argv records, byte count, and explicit boundary failure.
|
||||||
|
- [x] Independent review:
|
||||||
|
- first Codex review: request changes — negative fixtures did not each assert diagnostics;
|
||||||
|
- remediation: centralized predicate + diagnostic wrapper and exercised all four negative fixtures;
|
||||||
|
- second Codex review: APPROVE, 0 blockers/should-fix/suggestions;
|
||||||
|
- Codex security review: risk none, 0 findings.
|
||||||
|
- [ ] PR CI, formal fleet review, merge, merged-main CI, issue closure.
|
||||||
|
|
||||||
|
## Documentation disposition
|
||||||
|
|
||||||
|
- Updated canonical `docs/PRD.md` with FSP requirements and acceptance criteria.
|
||||||
|
- This is an internal test/reliability change with no API, user workflow, deployment, navigation, or publishing-surface change; no user/admin/API/sitemap update is required.
|
||||||
|
- `docs/TASKS.md` remains unchanged because the project contract makes it orchestrator-only.
|
||||||
|
|
||||||
|
## Risks
|
||||||
|
|
||||||
|
- The CI failure did not print its captured argv, so the exact CI payload is unavailable. The stress control proves the assertion is non-portable and can emit the exact false verdict; branch CI is the canonical confirmation that replacing it resolves pipeline 2269’s failure class.
|
||||||
|
- Printing fixture argv is safe only while this test’s projection remains non-secret. The diagnostic must stay scoped to the test capture and shell-escaped.
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
# #1099 — pipefail + early-exit sweep
|
||||||
|
|
||||||
|
## Scope and decisions
|
||||||
|
|
||||||
|
- Baseline `df4c591ab42aa1ae62c12935fdc0e772684864a0`, after #1100 removed its 35 sites.
|
||||||
|
- Split into review-sized non-closing tranches: runtime/general; tmux/git/quality tests; wake validation/tests.
|
||||||
|
- Do not equate class membership with demonstrated risk. Do not use payload size or pipeline stage count as a safety proxy.
|
||||||
|
- Preserve the issue's withdrawn findings for `qa-hook-stdin.sh` and the two fresh-directory `pnpm pack` lookups. Fix `install.sh:312` because malformed multi-root input must reach its named handler.
|
||||||
|
|
||||||
|
## Tranche 1 TDD
|
||||||
|
|
||||||
|
RED-first control: `node --test scripts/pipefail-early-exit.test.mjs` reported exactly 26 non-accepted runtime/general sites, including `install.sh:312`, and exited 1. A checked-in fixture generated from immutable baseline `df4c591a` records all 26 normalized sites; the control passes every fixture entry through the same scanner, asserts exact identity/count/uniqueness, and separately requires zero findings in the current tree. It also inventories accepted sites rather than silently excluding whole files.
|
||||||
|
|
||||||
|
Construction choices:
|
||||||
|
|
||||||
|
- here-string/file redirection for scalar grep assertions;
|
||||||
|
- full capture then parameter expansion for first-line selection;
|
||||||
|
- arrays/`mapfile` for complete populations;
|
||||||
|
- direct jq/awk/grep selection where one tool can express the property;
|
||||||
|
- no `|| true` added to a load-bearing assertion.
|
||||||
|
|
||||||
|
Site-by-site verdicts: `docs/reports/quality/1099-pipefail-sweep.md`.
|
||||||
|
|
||||||
|
## Tranche 2 TDD
|
||||||
|
|
||||||
|
Expanded the unconditional scanner over 11 non-wake test harnesses. RED named exactly 22 source lines; a second immutable-baseline fixture now asserts those 22 entries through the same scanner. Rewrites preserve command status by capturing producers before redirected assertions, use parameter expansion for line selection, and use complete `mapfile` populations where ordering matters. Current-tree finding count is zero for tranches 1 and 2.
|
||||||
|
|
||||||
|
## Tranche 3 TDD
|
||||||
|
|
||||||
|
Expanded the shared scanner over four wake validation harnesses. RED named 26 occurrences. The wake fixture asserts 26 occurrences / 25 normalized identities through the same scanner; all scalar assertions now use redirection, direct jq selection, complete capture, or consuming diagnostic ranges. Current-tree finding count is zero across the full scoped population.
|
||||||
|
|
||||||
|
## Verification so far
|
||||||
|
|
||||||
|
- `bash -n` on every changed shell script: pass.
|
||||||
|
- structural Node control: pass.
|
||||||
|
- `test-mutate-push-guard.sh`: 8/8 pass.
|
||||||
|
- `test-send-message-verdict.sh`: 3/3 pass.
|
||||||
|
- `test-send-message-socket.sh`: pass.
|
||||||
|
- Independent review 143 found two semantic regressions: a help-probe `|| true` changed the failure truth table, and an unguarded Git capture changed non-Git data-dir behavior from rc 0 + JSON to silent rc 128. Both received RED-first regressions before correction; help status is now separate and required, and Git status remains condition-guarded.
|
||||||
|
- Wake static inventory remains aligned at 261/261 after line-neutral rewrites; no static-set mismatch. Wake detector/reconcile/digest/preimage suites terminate at their existing fail-closed #973 `BASH_LINENO` environment probe (exit 97, observed `[3 5]`, expected `[3 4]`) before subject tests. No bypass or skip was used; canonical CI remains required.
|
||||||
|
- ShellCheck reports only pre-existing source-following, unused-variable, and untouched `ls | head` findings; no new diagnostic was introduced.
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
# #1150 — Pi persistent goal extension
|
||||||
|
|
||||||
|
- **Task ID:** ISSUE-1150 (no `docs/TASKS.md` row; that file is orchestrator-only)
|
||||||
|
- **Issue:** #1150 — `pi: add persistent /goal controller extension to Mosaic framework`
|
||||||
|
- **Branch:** `feat/1150-pi-goal-extension`
|
||||||
|
- **Mode:** Delivery
|
||||||
|
- **Status:** in progress
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
|
||||||
|
Build and locally validate a Mosaic-owned Pi `/goal` extension. Source must ship from
|
||||||
|
`packages/mosaic/framework/runtime/pi/`, framework sync must deploy it under
|
||||||
|
`~/.config/mosaic/runtime/pi/`, and no extension/configuration asset may be written into `~/.pi`.
|
||||||
|
Pi's native session manager remains the owner of session entries.
|
||||||
|
|
||||||
|
## Scope and acceptance source
|
||||||
|
|
||||||
|
- Canonical requirements: `docs/PRD.md`, section **Pi Persistent Goal Loop (#1150)**.
|
||||||
|
- User intent: continuous goal orientation and status checking after each Pi turn and compaction,
|
||||||
|
tested locally before framework delivery.
|
||||||
|
- Documentation target: canonical in-repo user/developer/runtime docs; no external publication.
|
||||||
|
|
||||||
|
## Assumptions
|
||||||
|
|
||||||
|
- `ASSUMPTION:` Initial semantic verification uses two consecutive structured, evidence-bearing
|
||||||
|
reports from the working agent rather than a second model request after every turn. This keeps the
|
||||||
|
loop testable and avoids doubling model cost while making the limitation explicit.
|
||||||
|
- `ASSUMPTION:` Default autonomous bounds are 40 turns and 6 repeated no-progress reports, with only
|
||||||
|
bounded numeric environment overrides.
|
||||||
|
- `ASSUMPTION:` A local smoke copy to `~/.config/mosaic/runtime/pi/goal-extension.ts` is authorized by
|
||||||
|
the user's explicit request. Full framework reseed into the live home is not required for the smoke
|
||||||
|
test and would touch unrelated framework-owned files.
|
||||||
|
|
||||||
|
## Budget
|
||||||
|
|
||||||
|
- Working estimate: 30K implementation/review tokens.
|
||||||
|
- Hard user cap: none stated.
|
||||||
|
- Cost control: deterministic fake-Pi tests; no nested evaluator calls; only bounded arithmetic/load
|
||||||
|
smoke workflows against the installed runtime.
|
||||||
|
|
||||||
|
## Plan
|
||||||
|
|
||||||
|
1. Update PRD and create tracking/scratchpad artifacts.
|
||||||
|
2. Read launcher, installer ownership, Pi extension, and documentation surfaces.
|
||||||
|
3. TDD: add fake-Pi behavior tests for commands, state restoration, turn checks, compaction, limits,
|
||||||
|
verification, and continuation deduplication.
|
||||||
|
4. Implement `runtime/pi/goal-extension.ts` and deterministic launcher discovery.
|
||||||
|
5. Add framework-sync/deployment acceptance coverage.
|
||||||
|
6. Update user, developer, runtime, framework README, and sitemap documentation.
|
||||||
|
7. Run focused tests, local Mosaic-path smoke test, then baseline repository gates.
|
||||||
|
8. Run independent review, remediate, commit, push/PR/CI/merge/issue closure per delivery gates.
|
||||||
|
|
||||||
|
## TDD decision
|
||||||
|
|
||||||
|
Applied. The continuation state machine and lifecycle scheduling are control-path logic where a race
|
||||||
|
or false terminal state can cause unbounded work or premature completion.
|
||||||
|
|
||||||
|
## Progress checkpoints
|
||||||
|
|
||||||
|
- [x] Issue #1150 created through Mosaic wrapper.
|
||||||
|
- [x] Isolated worktree created from `origin/main`.
|
||||||
|
- [x] PRD requirements and acceptance criteria added.
|
||||||
|
- [x] Task scratchpad created.
|
||||||
|
- [x] RED controller and security-regression tests written and observed failing before implementation.
|
||||||
|
- [x] Goal controller, launcher discovery, framework deployment coverage, and bounded state machine
|
||||||
|
implemented.
|
||||||
|
- [x] User, admin, developer, runtime, adapter, README, and sitemap documentation updated.
|
||||||
|
- [x] Final source copied additively to `~/.config/mosaic/runtime/pi/goal-extension.ts`; source and
|
||||||
|
deployed SHA-256 are identical.
|
||||||
|
- [x] Live Pi RPC smoke from the exact Mosaic path reached `achieved` with two verification passes and
|
||||||
|
no extension errors.
|
||||||
|
- [x] Baseline and situational checks completed, except the explicitly documented unavailable
|
||||||
|
PostgreSQL-only root integration case.
|
||||||
|
- [x] Independent code and OWASP/security reviews completed; all findings remediated and re-reviewed.
|
||||||
|
- [ ] Commit, push, PR, terminal-green CI, squash merge, and issue closure complete.
|
||||||
|
|
||||||
|
## Tests and evidence
|
||||||
|
|
||||||
|
### Situational
|
||||||
|
|
||||||
|
- `pnpm --filter @mosaicstack/mosaic exec vitest run src/runtime/pi-goal-extension.spec.ts`
|
||||||
|
- final: 25 passed.
|
||||||
|
- Covers commands, per-turn checks, context injection, two-pass verification, mixed-report
|
||||||
|
rejection, bounded limits, compaction, branch restore, stale timers, credential redaction,
|
||||||
|
typed-field false-positive protection, and append-only legacy-state fail-closed behavior.
|
||||||
|
- Final focused launcher/controller/file-adapter run: 3 files / 67 tests passed.
|
||||||
|
- Final V8 coverage for `framework/runtime/pi/goal-extension.ts`:
|
||||||
|
- 99.17% statements/lines, 93.78% branches, 100% functions.
|
||||||
|
- Installer migration fixture: 24 passed and byte-compared the deployed framework asset.
|
||||||
|
- Standalone extension TypeScript check against installed Pi 0.84.1 types passed:
|
||||||
|
`pnpm --filter @mosaicstack/mosaic exec tsc --noEmit --pretty false --module NodeNext
|
||||||
|
--moduleResolution NodeNext --target ES2022 --skipLibCheck framework/runtime/pi/goal-extension.ts`.
|
||||||
|
- Live deployment/load evidence:
|
||||||
|
- source/deployed SHA-256:
|
||||||
|
`1f0a3806e0948ad5f49684273a7e535e9880c148f7fd16d13ee487fcd601f637`.
|
||||||
|
- `get_commands` identified `/goal` as an extension command sourced from
|
||||||
|
`~/.config/mosaic/runtime/pi/goal-extension.ts`; `/goal help` succeeded; zero extension errors.
|
||||||
|
- live arithmetic goal ended `achieved`, verification `2/2`, with 3 goal reports / 3 agent starts
|
||||||
|
and zero extension errors.
|
||||||
|
- no goal extension exists under `~/.pi` extension paths.
|
||||||
|
|
||||||
|
### Baseline
|
||||||
|
|
||||||
|
- `pnpm build`: passed before the final framework-only redaction remediation; the extension is not a
|
||||||
|
package build input and its final source passed the standalone Pi type check.
|
||||||
|
- `pnpm typecheck`: 45/45 tasks passed.
|
||||||
|
- `pnpm lint`: 25/25 tasks passed.
|
||||||
|
- `pnpm format:check`: passed.
|
||||||
|
- Final Mosaic package components:
|
||||||
|
- Vitest: 82 files / 1,539 tests passed.
|
||||||
|
- full `test:framework-shell` harness passed.
|
||||||
|
- the discovered pre-existing tmux loader-marker race was reproduced with constructor PID
|
||||||
|
evidence, fixed with a pane readiness/FIFO barrier, passed 3 consecutive focused runs, and passed
|
||||||
|
in the full shell harness.
|
||||||
|
- one combined rerun encountered the separate existing real-lease probe TOCTOU in
|
||||||
|
`install-ordering-guard.spec.ts`; an earlier final Vitest run was fully green and the changed
|
||||||
|
focused suites remained green.
|
||||||
|
- Gateway safe baseline excluding the prohibited PostgreSQL-only fixture: 55 files / 600 tests passed
|
||||||
|
(6 files / 12 tests skipped by their existing environment gates).
|
||||||
|
- Root `pnpm test` reached 43 successful workspace tasks and all changed-package Vitest tests, but
|
||||||
|
the unchanged `apps/gateway/src/__tests__/cross-user-isolation.test.ts` afterAll hook retried a
|
||||||
|
PostgreSQL connection and failed authentication (`28P01`). This checkout explicitly forbids local
|
||||||
|
PostgreSQL startup/access; the failure is unrelated to #1150 and cannot be remediated by starting
|
||||||
|
the database. The gateway suite excluding that PostgreSQL-only file and required CI are used as
|
||||||
|
the safe verification paths.
|
||||||
|
|
||||||
|
### Independent review
|
||||||
|
|
||||||
|
- Codex code review: approved, 0 findings across 15 files.
|
||||||
|
- Initial Codex security review: one medium CWE-532/A09 finding for raw report persistence.
|
||||||
|
- Remediation added central credential-pattern redaction, prompt/docs guidance, canary tests, typed
|
||||||
|
field false-positive guards, and sticky fail-closed restore for credential-bearing append-only
|
||||||
|
history.
|
||||||
|
- Codex security re-review: risk `none`, 0 findings, confidence 0.87.
|
||||||
|
- Focused remediation review findings were fixed; final focused re-review verdict: `APPROVE`.
|
||||||
|
- Focused independent review of the tmux readiness barrier: `APPROVE`, no actionable findings.
|
||||||
|
|
||||||
|
## Risks and blockers
|
||||||
|
|
||||||
|
- Live `~/.config/mosaic` is shared by active Pi/fleet processes. Local deployment remained a single
|
||||||
|
additive framework file and did not reload or restart unrelated sessions.
|
||||||
|
- Completion verification is semantic, not mathematical: the active agent supplies structured
|
||||||
|
evidence twice. Operators must still inspect consequential outcomes.
|
||||||
|
- Credential redaction is pattern-based defense-in-depth, not a secret store. It covers
|
||||||
|
controller-owned state/status/tool details, not Pi's separate model-message/tool-call history.
|
||||||
|
Goals and reports must never contain real secrets or raw sensitive output. Because Pi session
|
||||||
|
entries are append-only, a detected credential-bearing legacy branch fails closed and the affected
|
||||||
|
session must be removed.
|
||||||
|
- Current installed Pi is newer than the repository's historical gateway Pi dependency. The
|
||||||
|
extension was checked and smoke-tested against installed Pi 0.84.1 using stable documented APIs.
|
||||||
|
- Local root testing cannot safely execute the unchanged PostgreSQL-only integration fixture under
|
||||||
|
the checkout's explicit database safety constraints. Terminal-green PR CI remains mandatory before
|
||||||
|
merge.
|
||||||
|
- The unchanged real-lease default-probe test can observe different broker availability across its two
|
||||||
|
sequential probes; one combined package rerun hit that existing TOCTOU. The same final Vitest suite
|
||||||
|
passed in a separate run, and CI remains the merge authority.
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
# #1174 — Wrapper guard rounds 10–11
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
|
||||||
|
Make checkout enforcement judge Git placement operands rather than every HOME-shaped word in the command, without reopening `--separate-git-dir` placement under HOME.
|
||||||
|
|
||||||
|
## Plan
|
||||||
|
|
||||||
|
1. Reproduce the four over-blocks and the placement-option control at head `20d86e39`.
|
||||||
|
2. Add RED fixtures before production changes.
|
||||||
|
3. Extract clone/worktree placement operands from the existing shell-aware normalized stream.
|
||||||
|
4. Run the full guard corpus, historical-head discrimination, syntax/static checks, probes, review, and CI.
|
||||||
|
|
||||||
|
## Progress and evidence
|
||||||
|
|
||||||
|
- Reproduced: `NOTE=$HOME`, `--reference=$HOME`, `GIT_DIR=$HOME/x`, and `--template=$HOME/t` all blocked despite explicit `/src/wt` destinations.
|
||||||
|
- RED at `20d86e39`: expanded suite had 8 failures, all HOME-valued non-placement cases.
|
||||||
|
- GREEN: expanded suite passes 242/242.
|
||||||
|
- Round-10 probes: 7/7 placement expectations and 4/4 placement-option controls pass.
|
||||||
|
- Earlier path probes remain green: 60/60, 24/24, and 17/17.
|
||||||
|
- Historical discrimination with the 242-fixture suite:
|
||||||
|
- `3d0a882a`: 216 pass / 26 fail.
|
||||||
|
- `4b8eba95`: 222 pass / 20 fail.
|
||||||
|
- `20d86e39`: 234 pass / 8 fail.
|
||||||
|
- `bash -n`, ShellCheck warning-or-higher, and `git diff --check`: pass.
|
||||||
|
|
||||||
|
## Residual / risk
|
||||||
|
|
||||||
|
- Relative destinations whose effective path depends on cwd are tracked separately by #1197 and remain out of scope.
|
||||||
|
- Unknown future Git options with a separate following value fail closed when that value is HOME-shaped. This may require classification when Git adds an unrelated path-taking option, but prevents a new placement option from silently bypassing the guard.
|
||||||
|
|
||||||
|
## Round 11 objective and intake
|
||||||
|
|
||||||
|
- **Issue / PR:** #1174.
|
||||||
|
- **Objective:** Remove the finite boolean-flag allowlists that turn accepted clone/worktree flags into fake placement operands, while preserving all real HOME placement blocks.
|
||||||
|
- **Scope:** `wrapper-guard.sh`, its hermetic fixtures, and task documentation. Relative cwd-dependent destinations remain in #1197.
|
||||||
|
- **Surfaces:** security-sensitive Bash hook behavior and shell/Git option grammar; no API, DB, UI, auth, deploy, or dependency changes.
|
||||||
|
- **Budget assumption:** 25K working tokens; reduce exploratory matrices before reducing acceptance coverage.
|
||||||
|
|
||||||
|
### Round 11 plan
|
||||||
|
|
||||||
|
1. Use Git itself to classify accepted/rejected clone and worktree options, and Bash itself to resolve path-word expectations.
|
||||||
|
2. Add RED fixtures for all six reported clone flags, generated negations, and equivalent worktree grammar.
|
||||||
|
3. Replace the open-ended unknown-option fail-closed fallback with a parser based on the closed value-taking option surface; keep explicit placement options special.
|
||||||
|
4. Run the full corpus, historical discrimination, shell/static checks, targeted probes, independent code/security review, one push, and exact-head CI.
|
||||||
|
|
||||||
|
### Root-cause evidence
|
||||||
|
|
||||||
|
- Git 2.39.5 accepts all six reported clone flags and the broader generated family measured in the brief: `--bare`, `--mirror`, `--ipv4`, `--ipv6`, `-4`, `-6`, `--no-local`, `--no-reject-shallow`, `--no-bare`, `--no-sparse`, `--no-dissociate`, `--no-shallow-submodules`, `--no-quiet`, `--no-progress`, and `--no-recurse-submodules`; it rejects `--relative-paths` as unknown.
|
||||||
|
- Git 2.39.5 accepts worktree negations including `--no-force`, `--no-detach`, `--no-lock`, `--no-guess-remote`, and `--no-track`; the current finite worktree flag list does not describe that generated family.
|
||||||
|
- `bash -c "printf '%s' <word>"` resolves `$HOME/source`, `${HOME}/source`, and `"$HOME"/source` under HOME while `/src/wt` remains outside it.
|
||||||
|
- **Hypothesis:** only separate-value options need positive classification. Treat every other option token as a no-value flag unless it is the explicit placement option; this matches Git's non-enumerable boolean family and confines the residual to genuinely new future value-taking options.
|
||||||
|
|
||||||
|
### TDD and verification checkpoints
|
||||||
|
|
||||||
|
- RED against the unmodified `91cc37bc` guard: 253 pass / 22 fail in the initial expanded 275-fixture suite. Failures include all 15 accepted clone flags, accepted long abbreviations, short value-taking bundles, abbreviated placement, worktree metadata abbreviation, and both directions of bundled worktree branch parsing.
|
||||||
|
- An exploratory fail-closed residual test drove emission of every worktree positional. Re-review correctly showed that this over-blocked HOME-shaped commit-ish metadata; a new commit-ish fixture failed RED against that intermediate implementation (278 pass / 2 fail, including one transient message assertion) and the parser was restored to emit only the actual path.
|
||||||
|
- GREEN after remediation: 280/280.
|
||||||
|
- Ultron's 13-shape option probe: 13/13 correct, including the six reported over-blocks, HOME destinations, end-of-options, worktree controls, and a later-command placement.
|
||||||
|
- Round-10 probes remain green: 7/7 subject-placement expectations and 4/4 `--separate-git-dir` controls.
|
||||||
|
- Earlier shell/path probes remain green: 60/60, 24/24, and 17/17.
|
||||||
|
- `bash -n`, ShellCheck warning-or-higher, and `git diff --check`: pass.
|
||||||
|
|
||||||
|
### Deliberate residual
|
||||||
|
|
||||||
|
A future Git release could add a new separate-value option absent from the closed value grammar. It defaults to no-value flag parsing, which leaves the following word positional. For clone, this can fail open if that future option itself creates repository state at its value. For worktree, it can shift which word is read as the path. This hypothetical future ambiguity is accepted deliberately because failing closed on every unclassified option is proven to over-block Git's open-ended present-day boolean/`--no-*` family. Every value-taking and placement option Git currently supports is classified, including accepted abbreviations of `--separate-git-dir`. Relative cwd-dependent targets remain in #1197.
|
||||||
|
|
||||||
|
### Independent review checkpoint
|
||||||
|
|
||||||
|
- Initial Codex code/security review raised `--orphan` as value-taking. Upstream Git `master` contradicts that premise: the synopsis is `[--orphan] [(-b | -B) <new-branch>] <path> [<commit-ish>]`, and the prose derives the branch from the path when `-b`/`-B` is absent. `--orphan` is therefore correctly handled as a boolean flag.
|
||||||
|
- The security review separately identified the generic future worktree shift residual. An attempted fail-closed remediation emitted every positional, but code re-review correctly rejected it because valid grammar has only one placement positional and an optional commit-ish. Final behavior checks only the path and documents the hypothetical future option shift deliberately; paired actual-grammar `--orphan` fixtures cover safe/HOME paths and `-b` metadata.
|
||||||
|
- Security re-review initially had no findings. Code re-review's commit-ish blocker was remediated with a RED fixture and path-only restoration; final code re-review approved with no findings.
|
||||||
|
- Final security review then found non-canonical absolute and symlink aliases. Eight lexical fixtures failed RED against the prior implementation, followed by three symlink fixtures failing RED. Remediation expands only shell-visible HOME tokens, resolves the longest existing directory prefix physically, and lexically normalizes the nonexistent suffix. The suite is now 292/292.
|
||||||
|
- Inherent residual: a symlink can be replaced between pre-tool inspection and Git execution. Existing aliases are resolved; eliminating the race requires enforcement inside the filesystem mutation path rather than a text pre-hook. Security review classified this medium, and architectural closure is tracked in #1199.
|
||||||
|
- Final independent code review: APPROVE, 0 findings. Final security review: no critical/high findings; the single medium TOCTOU residual is explicitly tracked in #1199.
|
||||||
|
|
||||||
|
### Final local evidence
|
||||||
|
|
||||||
|
- Final hermetic suite: 292/292; the same suite against `91cc37bc` discriminates at 256 pass / 36 fail.
|
||||||
|
- Ultron option probe: 13/13; round-10 probes: 7/7 plus 4/4 controls; earlier shell/path probes: 60/60, 24/24, and 17/17.
|
||||||
|
- `bash -n`, ShellCheck warning-or-higher, `git diff --check`, sanitization gate, and test-enumeration gate (population 55; 38 enumerated; 18 signed exclusions): pass.
|
||||||
|
- Independent code review: APPROVE, 0 findings. Security review's remaining medium TOCTOU architecture residual is tracked in #1199; no critical/high findings remain.
|
||||||
|
- Repository-wide TypeScript gates require dependencies absent from this worktree; the canonical Woodpecker pipeline will run them against the pushed exact head.
|
||||||
|
|
||||||
|
### Documentation checklist
|
||||||
|
|
||||||
|
- `docs/PRD.md` updated with WPG requirements, acceptance, canonicalization, and residual risk.
|
||||||
|
- Task scratchpad updated in the same logical change set; `docs/TASKS.md` remains orchestrator-only.
|
||||||
|
- No API, auth, UI, navigation, deployment, user-guide, or admin-guide surface changed; OpenAPI, endpoint index, sitemap, and publishing are not applicable.
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
# #1179 — Required security DI wiring
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
|
||||||
|
Eliminate the shared fail-open defect class **absence read as permission**:
|
||||||
|
|
||||||
|
- FL-01: missing `CommandAuthorizationService` must refuse Nest startup and must not permit command effects.
|
||||||
|
- FL-11: missing `SystemOverrideService` must refuse Nest startup and must not omit stored instruction authority while allowing provider/session effects.
|
||||||
|
|
||||||
|
## Tracking
|
||||||
|
|
||||||
|
- Issue: #1179, child of #1156
|
||||||
|
- Branch: `fix/1179-required-security-di`
|
||||||
|
- Base: `origin/next` at `216cd72226cd9ee17eea461cfe7cd0e010a22f02`
|
||||||
|
|
||||||
|
## Plan
|
||||||
|
|
||||||
|
1. RED: compile the real `AppModule` graph with each required provider independently removed, with a positive control for each intact binding.
|
||||||
|
2. RED: directly exercise each malformed absence path and assert zero command/provider/session effects.
|
||||||
|
3. Stop and report RED to the coordinator before production implementation.
|
||||||
|
4. After authorization, make both constructor injections required, remove absence-as-permission branches, and update explicit legitimate optional test seams.
|
||||||
|
5. Run focused Gateway tests, typecheck, lint, format, build, independent exact-head verification, and focused security review.
|
||||||
|
|
||||||
|
## Immutable path fence
|
||||||
|
|
||||||
|
Production changes are confined to:
|
||||||
|
|
||||||
|
- `apps/gateway/src/commands/command-executor.service.ts`
|
||||||
|
- `apps/gateway/src/agent/agent.service.ts`
|
||||||
|
|
||||||
|
Tests and task evidence are confined to:
|
||||||
|
|
||||||
|
- `apps/gateway/src/__tests__/required-security-wiring.test.ts`
|
||||||
|
- existing direct-constructor specs that require explicit required arguments
|
||||||
|
- `docs/scratchpads/1179-required-security-di.md`
|
||||||
|
|
||||||
|
No files in #1178, #1072, #1080, or #1054 lanes are in scope. `docs/TASKS.md` is orchestrator-owned and will not be modified.
|
||||||
|
|
||||||
|
## Budget
|
||||||
|
|
||||||
|
No explicit token ceiling was provided. Working assumption: one narrow Gateway security packet; split and stop if either arm requires unrelated module rewiring.
|
||||||
|
|
||||||
|
## Progress
|
||||||
|
|
||||||
|
- Intake read from #1179 and parent #1156.
|
||||||
|
- Base independently resolved from the issue's pre-native-stage ordering and repository `origin/next` ref; branch HEAD verified byte-for-byte against the remote ref.
|
||||||
|
- Real consumers and direct constructors inventoried.
|
||||||
|
|
||||||
|
## Tests
|
||||||
|
|
||||||
|
### RED
|
||||||
|
|
||||||
|
- `required-security-wiring.test.ts`: 4 failed, 2 passed before implementation.
|
||||||
|
- Both real-graph negative controls showed module compilation accepted the missing target binding.
|
||||||
|
- Direct FL-01 showed one unauthorized command effect; direct FL-11 showed one provider prompt and one session counter mutation.
|
||||||
|
|
||||||
|
### GREEN
|
||||||
|
|
||||||
|
- `required-security-wiring.test.ts`: 6/6 passed.
|
||||||
|
- FL-01-only production revert: exactly the two FL-01 test cases failed; all four other cases, including FL-11, passed.
|
||||||
|
- FL-11-only production revert: exactly the two FL-11 test cases failed; all four other cases, including FL-01, passed.
|
||||||
|
- Full Gateway suite: 74 files passed, 7 skipped; 831 tests passed, 17 skipped.
|
||||||
|
- Gateway typecheck: passed.
|
||||||
|
- Gateway lint: passed.
|
||||||
|
- Gateway build: passed.
|
||||||
|
- Changed-file Prettier check: passed.
|
||||||
|
|
||||||
|
### Review
|
||||||
|
|
||||||
|
- Codex code review: APPROVE, 0 findings.
|
||||||
|
- Codex focused security review: risk `none`, 0 findings.
|
||||||
|
- Independent exact-head review remains assigned to Scrappy through the coordinator.
|
||||||
|
|
||||||
|
## Risks / blockers
|
||||||
|
|
||||||
|
- `AgentModule` / `CommandsModule` / `ChatModule` contain a production cycle; the module test therefore uses the real top-level `AppModule` and replaces only storage/network leaves, preserving the target service in each arm while isolating the separate required consumer that would otherwise mask that arm's defect.
|
||||||
|
- No broad module rewrite was required.
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
# #1194 — Installed framework-tool drift detection and refresh analysis
|
||||||
|
|
||||||
|
## Decision
|
||||||
|
|
||||||
|
The reported queue-guard source defect was already fixed on `main` by `58b971ab`; the live failure came from a stale `~/.config/mosaic/tools/git/ci-queue-wait.sh`. The durable fix is therefore a detector, not a duplicate queue-guard patch.
|
||||||
|
|
||||||
|
`mosaic doctor` now compares the framework tools bundled with the executing Mosaic package against the deployed tools tree. Doctor is the selected visibility boundary because it is observational and operator-invoked: unlike session start, it does not add a repository/network scan to every seat launch, and it cannot silently replace identity or messaging tools while seats are active. It reports drift without changing files. `--fail-on-warn` converts detected drift into a non-zero doctor result.
|
||||||
|
|
||||||
|
## Classification
|
||||||
|
|
||||||
|
The existing `framework-manifest.txt` is authoritative. The detector invokes the canonical shared `tools/_lib/manifest.sh classify` implementation over the complete source census and refuses missing, unreadable, malformed, incomplete, or zero-framework ownership output. Policy is therefore read rather than duplicated:
|
||||||
|
|
||||||
|
- Current policy classifies source files under `tools/**` as framework-owned and required in the deployed tools tree.
|
||||||
|
- Current policy explicitly classifies `tools/_lib/credentials.json` operator-owned and excludes it from byte comparison; future policy changes take effect without a detector edit.
|
||||||
|
- A file present only in the deployed tools tree is operator-owned/unknown by the manifest's fail-safe default. The detector reports it as `INSTALLED_ONLY operator-or-unknown` under `--verbose` but does not fail or delete it.
|
||||||
|
- Empty/partial source traversal, unreadable directories/files, symlinked census entries, root aliases, and descendant source aliases all return `CANNOT_ASSERT` rather than manufacturing agreement.
|
||||||
|
|
||||||
|
This means `NOT_INSTALLED` is not suppressed by filename guesses such as “test” or “README”: if it ships below source `tools/**`, the installer contract says it should be installed. Source-only implementation files outside `tools/**` are outside this detector population by construction.
|
||||||
|
|
||||||
|
## Current host analysis (observation only; no refresh performed)
|
||||||
|
|
||||||
|
A direct source-vs-installed census showed broad drift, including identity and messaging behavior:
|
||||||
|
|
||||||
|
- Identity/provider operations: stale `git/detect-platform.sh`, `issue-comment.sh`, `issue-create.sh`, `issue-close.sh`, `issue-view.sh`, `pr-create.sh`, `pr-merge.sh`, `pr-review.sh`, `pr-metadata.sh`; missing `pr-edit.sh` and several identity/read-back regression tools.
|
||||||
|
- Messaging/session: stale `tmux/agent-send.sh`, `tmux/send-message.sh`, their regressions, and `fleet/start-agent-session.sh`.
|
||||||
|
- Gate enforcement: stale `git/ci-queue-wait.sh`; missing the queue tri-state/process-level suites and terminal-green verifier.
|
||||||
|
- Lease/QA behavior: stale lease-broker launch/mutation/receipt tools and QA hooks.
|
||||||
|
|
||||||
|
Counts vary with source head and installed local/operator files; the detector prints measured counts every run rather than baking this snapshot into policy.
|
||||||
|
|
||||||
|
## Reviewed refresh command — analyse only, do not run during active seats
|
||||||
|
|
||||||
|
Use the package/release updater's manifest-driven keep-mode sync during a quiet maintenance window:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
MOSAIC_SYNC_ONLY=1 \
|
||||||
|
MOSAIC_INSTALL_MODE=keep \
|
||||||
|
MOSAIC_HOME="$HOME/.config/mosaic" \
|
||||||
|
bash /path/to/reviewed/@mosaicstack/mosaic/framework/install.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
For the globally installed package, resolve the reviewed installer rather than guessing its path:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
PACKAGE_ROOT="$(dirname "$(node -p "require.resolve('@mosaicstack/mosaic/package.json')")")"
|
||||||
|
MOSAIC_SYNC_ONLY=1 MOSAIC_INSTALL_MODE=keep MOSAIC_HOME="$HOME/.config/mosaic" \
|
||||||
|
bash "$PACKAGE_ROOT/framework/install.sh"
|
||||||
|
```
|
||||||
|
|
||||||
|
Do not run this while agent seats are active: the stale set includes identity selection, provider mutation, messaging, queue/merge guards, lease enforcement, and session launch. Syncing those files in place can change behavior between a seat's preflight and mutation.
|
||||||
|
|
||||||
|
## Post-refresh verification
|
||||||
|
|
||||||
|
1. Run `mosaic doctor --fail-on-warn`; require `stale=0 not-installed=0` from the framework drift summary (other unrelated doctor warnings must also be adjudicated).
|
||||||
|
2. Re-run the constructed process-level queue probes against the **installed path**, not the source checkout. Use the source suite while overriding its subject path in a reviewed scratch copy, or reproduce these exact observations:
|
||||||
|
- pending provider payload: guard must print `state=pending`, print the pending context, wait, and exit non-zero/timeout — never return immediately with rc 0;
|
||||||
|
- malformed payload: guard must print `state=malformed` and exit non-zero;
|
||||||
|
- unsupported but valid status vocabulary: guard must print `state=unknown` and exit non-zero.
|
||||||
|
3. Run provider author read-back for one deliberately low-risk wrapper operation before resuming fleet mutation work; wrapper self-report is not identity evidence.
|
||||||
|
4. Relaunch seats only after the quiet-window verification, because existing processes retain loaded environment/context.
|
||||||
|
|
||||||
|
## Probe evidence
|
||||||
|
|
||||||
|
The detector regression constructs a stale installed tool plus a missing shipped tool and observes rc 1 with distinct `STALE` and `NOT_INSTALLED` lines. That case would pass or be invisible before this change because no installed-vs-shipped comparison existed. Additional review-red controls prove:
|
||||||
|
|
||||||
|
- empty and unreadable source censuses return `CANNOT_ASSERT` (they returned clean rc 0 at the first PR head);
|
||||||
|
- deleting the manifest returns `CANNOT_ASSERT`, while changing manifest ownership changes the verdict through the canonical resolver (the first head never opened the manifest);
|
||||||
|
- root and descendant symlink/source aliases cannot return clean (the first head returned clean for a source-backed installed subtree);
|
||||||
|
- a checker hung during doctor is terminated by a bounded watchdog, emits `CANNOT_ASSERT`, and doctor reaches its final warnings line (the first head hung and suppressed the remaining audit).
|
||||||
|
|
||||||
|
Controls retain byte-identical success, exact credential carve-out behavior, and installed-only preservation.
|
||||||
@@ -1,253 +0,0 @@
|
|||||||
import { mkdirSync, readFileSync, rmSync } from 'node:fs';
|
|
||||||
import { join } from 'node:path';
|
|
||||||
import { tmpdir } from 'node:os';
|
|
||||||
import { randomUUID } from 'node:crypto';
|
|
||||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
|
||||||
import { normalizeGate, countAIFindings, runGate, runGates } from '../src/gate-runner.js';
|
|
||||||
|
|
||||||
function makeTmpDir(): string {
|
|
||||||
const dir = join(tmpdir(), `macp-gate-${randomUUID()}`);
|
|
||||||
mkdirSync(dir, { recursive: true });
|
|
||||||
return dir;
|
|
||||||
}
|
|
||||||
|
|
||||||
describe('normalizeGate', () => {
|
|
||||||
it('normalizes a string to mechanical gate', () => {
|
|
||||||
expect(normalizeGate('echo test')).toEqual({
|
|
||||||
command: 'echo test',
|
|
||||||
type: 'mechanical',
|
|
||||||
fail_on: 'blocker',
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it('normalizes an object gate with defaults', () => {
|
|
||||||
expect(normalizeGate({ command: 'lint' })).toEqual({
|
|
||||||
command: 'lint',
|
|
||||||
type: 'mechanical',
|
|
||||||
fail_on: 'blocker',
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it('preserves explicit type and fail_on', () => {
|
|
||||||
expect(normalizeGate({ command: 'review', type: 'ai-review', fail_on: 'any' })).toEqual({
|
|
||||||
command: 'review',
|
|
||||||
type: 'ai-review',
|
|
||||||
fail_on: 'any',
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it('handles non-string/non-object input', () => {
|
|
||||||
expect(normalizeGate(42)).toEqual({ command: '', type: 'mechanical', fail_on: 'blocker' });
|
|
||||||
expect(normalizeGate(null)).toEqual({ command: '', type: 'mechanical', fail_on: 'blocker' });
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('countAIFindings', () => {
|
|
||||||
it('returns zeros for non-object', () => {
|
|
||||||
expect(countAIFindings(null)).toEqual({ blockers: 0, total: 0 });
|
|
||||||
expect(countAIFindings('string')).toEqual({ blockers: 0, total: 0 });
|
|
||||||
expect(countAIFindings([])).toEqual({ blockers: 0, total: 0 });
|
|
||||||
});
|
|
||||||
|
|
||||||
it('counts from stats block', () => {
|
|
||||||
const output = { stats: { blockers: 2, should_fix: 3, suggestions: 1 } };
|
|
||||||
expect(countAIFindings(output)).toEqual({ blockers: 2, total: 6 });
|
|
||||||
});
|
|
||||||
|
|
||||||
it('counts from findings array when stats has no blockers', () => {
|
|
||||||
const output = {
|
|
||||||
stats: { blockers: 0 },
|
|
||||||
findings: [{ severity: 'blocker' }, { severity: 'warning' }, { severity: 'blocker' }],
|
|
||||||
};
|
|
||||||
expect(countAIFindings(output)).toEqual({ blockers: 2, total: 3 });
|
|
||||||
});
|
|
||||||
|
|
||||||
it('uses stats blockers over findings array when stats has blockers', () => {
|
|
||||||
const output = {
|
|
||||||
stats: { blockers: 5 },
|
|
||||||
findings: [{ severity: 'blocker' }, { severity: 'warning' }],
|
|
||||||
};
|
|
||||||
// stats.blockers = 5, total from stats = 5+0+0 = 5, findings not used for total since stats total is non-zero
|
|
||||||
expect(countAIFindings(output)).toEqual({ blockers: 5, total: 5 });
|
|
||||||
});
|
|
||||||
|
|
||||||
it('counts findings length as total when stats has zero total', () => {
|
|
||||||
const output = {
|
|
||||||
findings: [{ severity: 'warning' }, { severity: 'info' }],
|
|
||||||
};
|
|
||||||
expect(countAIFindings(output)).toEqual({ blockers: 0, total: 2 });
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('runGate', () => {
|
|
||||||
let tmp: string;
|
|
||||||
let logPath: string;
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
tmp = makeTmpDir();
|
|
||||||
logPath = join(tmp, 'gate.log');
|
|
||||||
});
|
|
||||||
|
|
||||||
afterEach(() => {
|
|
||||||
rmSync(tmp, { recursive: true, force: true });
|
|
||||||
});
|
|
||||||
|
|
||||||
it('passes mechanical gate on exit 0', () => {
|
|
||||||
const result = runGate('echo hello', tmp, logPath, 30);
|
|
||||||
expect(result.passed).toBe(true);
|
|
||||||
expect(result.exit_code).toBe(0);
|
|
||||||
expect(result.type).toBe('mechanical');
|
|
||||||
expect(result.output).toContain('hello');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('fails mechanical gate on non-zero exit', () => {
|
|
||||||
const result = runGate('exit 1', tmp, logPath, 30);
|
|
||||||
expect(result.passed).toBe(false);
|
|
||||||
expect(result.exit_code).toBe(1);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('ci-pipeline always passes', () => {
|
|
||||||
const result = runGate({ command: 'anything', type: 'ci-pipeline' }, tmp, logPath, 30);
|
|
||||||
expect(result.passed).toBe(true);
|
|
||||||
expect(result.type).toBe('ci-pipeline');
|
|
||||||
expect(result.output).toBe('CI pipeline gate placeholder');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('empty command passes', () => {
|
|
||||||
const result = runGate({ command: '' }, tmp, logPath, 30);
|
|
||||||
expect(result.passed).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('ai-review gate parses JSON output', () => {
|
|
||||||
const json = JSON.stringify({ stats: { blockers: 0, should_fix: 1 } });
|
|
||||||
const result = runGate({ command: `echo '${json}'`, type: 'ai-review' }, tmp, logPath, 30);
|
|
||||||
expect(result.passed).toBe(true);
|
|
||||||
expect(result.blockers).toBe(0);
|
|
||||||
expect(result.findings).toBe(1);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('ai-review gate fails on blockers', () => {
|
|
||||||
const json = JSON.stringify({ stats: { blockers: 2 } });
|
|
||||||
const result = runGate({ command: `echo '${json}'`, type: 'ai-review' }, tmp, logPath, 30);
|
|
||||||
expect(result.passed).toBe(false);
|
|
||||||
expect(result.blockers).toBe(2);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('ai-review gate with fail_on=any fails on any findings', () => {
|
|
||||||
const json = JSON.stringify({ stats: { blockers: 0, should_fix: 1 } });
|
|
||||||
const result = runGate(
|
|
||||||
{ command: `echo '${json}'`, type: 'ai-review', fail_on: 'any' },
|
|
||||||
tmp,
|
|
||||||
logPath,
|
|
||||||
30,
|
|
||||||
);
|
|
||||||
expect(result.passed).toBe(false);
|
|
||||||
expect(result.fail_on).toBe('any');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('ai-review gate fails on invalid JSON output', () => {
|
|
||||||
const result = runGate({ command: 'echo "not json"', type: 'ai-review' }, tmp, logPath, 30);
|
|
||||||
expect(result.passed).toBe(false);
|
|
||||||
expect(result.parse_error).toBeDefined();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('writes to log file', () => {
|
|
||||||
runGate('echo logged', tmp, logPath, 30);
|
|
||||||
const log = readFileSync(logPath, 'utf-8');
|
|
||||||
expect(log).toContain('COMMAND: echo logged');
|
|
||||||
expect(log).toContain('logged');
|
|
||||||
expect(log).toContain('EXIT:');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('runGates', () => {
|
|
||||||
let tmp: string;
|
|
||||||
let logPath: string;
|
|
||||||
let eventsPath: string;
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
tmp = makeTmpDir();
|
|
||||||
logPath = join(tmp, 'gates.log');
|
|
||||||
eventsPath = join(tmp, 'events.ndjson');
|
|
||||||
});
|
|
||||||
|
|
||||||
afterEach(() => {
|
|
||||||
rmSync(tmp, { recursive: true, force: true });
|
|
||||||
});
|
|
||||||
|
|
||||||
it('runs multiple gates and returns results', () => {
|
|
||||||
const { allPassed, gateResults } = runGates(
|
|
||||||
['echo one', 'echo two'],
|
|
||||||
tmp,
|
|
||||||
logPath,
|
|
||||||
30,
|
|
||||||
eventsPath,
|
|
||||||
'task-1',
|
|
||||||
);
|
|
||||||
expect(allPassed).toBe(true);
|
|
||||||
expect(gateResults).toHaveLength(2);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('reports failure when any gate fails', () => {
|
|
||||||
const { allPassed, gateResults } = runGates(
|
|
||||||
['echo ok', 'exit 1'],
|
|
||||||
tmp,
|
|
||||||
logPath,
|
|
||||||
30,
|
|
||||||
eventsPath,
|
|
||||||
'task-2',
|
|
||||||
);
|
|
||||||
expect(allPassed).toBe(false);
|
|
||||||
expect(gateResults[0]!.passed).toBe(true);
|
|
||||||
expect(gateResults[1]!.passed).toBe(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('emits events for each gate', () => {
|
|
||||||
runGates(['echo test'], tmp, logPath, 30, eventsPath, 'task-3');
|
|
||||||
const events = readFileSync(eventsPath, 'utf-8')
|
|
||||||
.trim()
|
|
||||||
.split('\n')
|
|
||||||
.map((l) => JSON.parse(l));
|
|
||||||
expect(events).toHaveLength(2); // started + passed
|
|
||||||
expect(events[0].event_type).toBe('rail.check.started');
|
|
||||||
expect(events[1].event_type).toBe('rail.check.passed');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('skips gates with empty command (non ci-pipeline)', () => {
|
|
||||||
const { gateResults } = runGates(
|
|
||||||
[{ command: '', type: 'mechanical' }, 'echo real'],
|
|
||||||
tmp,
|
|
||||||
logPath,
|
|
||||||
30,
|
|
||||||
eventsPath,
|
|
||||||
'task-4',
|
|
||||||
);
|
|
||||||
expect(gateResults).toHaveLength(1);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('does not skip ci-pipeline even with empty command', () => {
|
|
||||||
const { gateResults } = runGates(
|
|
||||||
[{ command: '', type: 'ci-pipeline' }],
|
|
||||||
tmp,
|
|
||||||
logPath,
|
|
||||||
30,
|
|
||||||
eventsPath,
|
|
||||||
'task-5',
|
|
||||||
);
|
|
||||||
expect(gateResults).toHaveLength(1);
|
|
||||||
expect(gateResults[0]!.passed).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('emits failed event with correct message', () => {
|
|
||||||
runGates(['exit 42'], tmp, logPath, 30, eventsPath, 'task-6');
|
|
||||||
const events = readFileSync(eventsPath, 'utf-8')
|
|
||||||
.trim()
|
|
||||||
.split('\n')
|
|
||||||
.map((l) => JSON.parse(l));
|
|
||||||
const failEvent = events.find(
|
|
||||||
(e: Record<string, unknown>) => e.event_type === 'rail.check.failed',
|
|
||||||
);
|
|
||||||
expect(failEvent).toBeDefined();
|
|
||||||
expect(failEvent.message).toContain('Gate failed (');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,5 +1,8 @@
|
|||||||
import { describe, it, expect } from 'vitest';
|
import { describe, it, expect, afterEach, beforeEach, vi } from 'vitest';
|
||||||
import { Command } from 'commander';
|
import { Command } from 'commander';
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import os from 'node:os';
|
||||||
|
import path from 'node:path';
|
||||||
import { registerMacpCommand } from './cli.js';
|
import { registerMacpCommand } from './cli.js';
|
||||||
|
|
||||||
describe('registerMacpCommand', () => {
|
describe('registerMacpCommand', () => {
|
||||||
@@ -75,3 +78,162 @@ describe('registerMacpCommand', () => {
|
|||||||
expect(topLevel).toContain('events');
|
expect(topLevel).toContain('events');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* RI-N2 fail-closed CLI behavior: an unimplemented capability is a failure,
|
||||||
|
* never a success. Every stub exits nonzero with a typed message, and the
|
||||||
|
* implemented `macp gate` mirrors the typed gate-runner states.
|
||||||
|
*/
|
||||||
|
describe('registerMacpCommand fail-closed (RI-N2)', () => {
|
||||||
|
let tmpDir: string;
|
||||||
|
|
||||||
|
function buildProgram(): Command {
|
||||||
|
const program = new Command();
|
||||||
|
program.exitOverride();
|
||||||
|
program.configureOutput({ writeErr: () => {} });
|
||||||
|
registerMacpCommand(program);
|
||||||
|
return program;
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'macp-cli-failclosed-'));
|
||||||
|
process.exitCode = 0;
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
process.exitCode = 0;
|
||||||
|
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('macp tasks list exits nonzero (unimplemented capability)', async () => {
|
||||||
|
const program = buildProgram();
|
||||||
|
await program.parseAsync(['macp', 'tasks', 'list'], { from: 'user' });
|
||||||
|
expect(process.exitCode).not.toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('macp submit exits nonzero with a typed MACP_NOT_IMPLEMENTED message', async () => {
|
||||||
|
const program = buildProgram();
|
||||||
|
const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||||
|
try {
|
||||||
|
await program.parseAsync(['macp', 'submit', 'spec.json'], { from: 'user' });
|
||||||
|
expect(process.exitCode).not.toBe(0);
|
||||||
|
const errText = errSpy.mock.calls.map((c) => String(c[0])).join('\n');
|
||||||
|
expect(errText).toContain('MACP_NOT_IMPLEMENTED');
|
||||||
|
} finally {
|
||||||
|
errSpy.mockRestore();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('macp events tail exits nonzero (unimplemented capability)', async () => {
|
||||||
|
const program = buildProgram();
|
||||||
|
await program.parseAsync(['macp', 'events', 'tail'], { from: 'user' });
|
||||||
|
expect(process.exitCode).not.toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('macp gate runs a green inline command and exits 0', async () => {
|
||||||
|
const program = buildProgram();
|
||||||
|
await program.parseAsync(
|
||||||
|
[
|
||||||
|
'macp',
|
||||||
|
'gate',
|
||||||
|
'exit 0',
|
||||||
|
'--cwd',
|
||||||
|
tmpDir,
|
||||||
|
'--log',
|
||||||
|
path.join(tmpDir, 'g.log'),
|
||||||
|
'--timeout',
|
||||||
|
'10',
|
||||||
|
],
|
||||||
|
{ from: 'user' },
|
||||||
|
);
|
||||||
|
expect(process.exitCode).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('macp gate exits nonzero on a failing command', async () => {
|
||||||
|
const program = buildProgram();
|
||||||
|
await program.parseAsync(
|
||||||
|
[
|
||||||
|
'macp',
|
||||||
|
'gate',
|
||||||
|
'exit 9',
|
||||||
|
'--cwd',
|
||||||
|
tmpDir,
|
||||||
|
'--log',
|
||||||
|
path.join(tmpDir, 'g.log'),
|
||||||
|
'--timeout',
|
||||||
|
'10',
|
||||||
|
],
|
||||||
|
{ from: 'user' },
|
||||||
|
);
|
||||||
|
expect(process.exitCode).not.toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('macp gate with an unimplemented ci-pipeline capability exits nonzero', async () => {
|
||||||
|
const program = buildProgram();
|
||||||
|
const specPath = path.join(tmpDir, 'gates.json');
|
||||||
|
fs.writeFileSync(specPath, JSON.stringify([{ type: 'ci-pipeline' }]));
|
||||||
|
await program.parseAsync(
|
||||||
|
[
|
||||||
|
'macp',
|
||||||
|
'gate',
|
||||||
|
specPath,
|
||||||
|
'--cwd',
|
||||||
|
tmpDir,
|
||||||
|
'--log',
|
||||||
|
path.join(tmpDir, 'g.log'),
|
||||||
|
'--timeout',
|
||||||
|
'10',
|
||||||
|
],
|
||||||
|
{ from: 'user' },
|
||||||
|
);
|
||||||
|
expect(process.exitCode).not.toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('macp gate --simulate completes (exit 0) but reports simulated results', async () => {
|
||||||
|
const program = buildProgram();
|
||||||
|
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
|
||||||
|
try {
|
||||||
|
await program.parseAsync(
|
||||||
|
[
|
||||||
|
'macp',
|
||||||
|
'gate',
|
||||||
|
'exit 0',
|
||||||
|
'--simulate',
|
||||||
|
'--cwd',
|
||||||
|
tmpDir,
|
||||||
|
'--log',
|
||||||
|
path.join(tmpDir, 'g.log'),
|
||||||
|
'--timeout',
|
||||||
|
'10',
|
||||||
|
],
|
||||||
|
{ from: 'user' },
|
||||||
|
);
|
||||||
|
// completes only because the caller explicitly asked to simulate
|
||||||
|
expect(process.exitCode).toBe(0);
|
||||||
|
const outText = logSpy.mock.calls.map((c) => String(c[0])).join('\n');
|
||||||
|
expect(outText).toContain('simulated');
|
||||||
|
expect(outText).toContain('SIMULATED');
|
||||||
|
} finally {
|
||||||
|
logSpy.mockRestore();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('macp gate with an empty spec exits nonzero with a typed error', async () => {
|
||||||
|
const program = buildProgram();
|
||||||
|
await program.parseAsync(
|
||||||
|
[
|
||||||
|
'macp',
|
||||||
|
'gate',
|
||||||
|
' ',
|
||||||
|
'--cwd',
|
||||||
|
tmpDir,
|
||||||
|
'--log',
|
||||||
|
path.join(tmpDir, 'g.log'),
|
||||||
|
'--timeout',
|
||||||
|
'10',
|
||||||
|
],
|
||||||
|
{ from: 'user' },
|
||||||
|
);
|
||||||
|
expect(process.exitCode).not.toBe(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
+129
-19
@@ -1,5 +1,73 @@
|
|||||||
|
import { existsSync, readFileSync } from 'node:fs';
|
||||||
|
|
||||||
import type { Command } from 'commander';
|
import type { Command } from 'commander';
|
||||||
|
|
||||||
|
import { runGates } from './gate-runner.js';
|
||||||
|
import { MACPCapabilityError, type MacpErrorCode } from './errors.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load gates from a spec: an existing file (JSON gates array, a JSON object
|
||||||
|
* with `quality_gates`, a JSON gate object, or one command per line) or an
|
||||||
|
* inline command string. Fails closed with a typed capability error when the
|
||||||
|
* spec contains no executable gate definition.
|
||||||
|
*/
|
||||||
|
function loadGateSpec(spec: string): unknown[] {
|
||||||
|
if (existsSync(spec)) {
|
||||||
|
const raw = readFileSync(spec, 'utf-8');
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(raw) as unknown;
|
||||||
|
if (Array.isArray(parsed)) {
|
||||||
|
if (parsed.length === 0) {
|
||||||
|
throw new MACPCapabilityError(
|
||||||
|
'MACP_NO_COMMAND',
|
||||||
|
'gate-spec',
|
||||||
|
`gate spec file '${spec}' contains an empty gates array`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return parsed;
|
||||||
|
}
|
||||||
|
if (typeof parsed === 'object' && parsed !== null) {
|
||||||
|
const obj = parsed as Record<string, unknown>;
|
||||||
|
if (Array.isArray(obj['quality_gates'])) {
|
||||||
|
return obj['quality_gates'];
|
||||||
|
}
|
||||||
|
return [parsed];
|
||||||
|
}
|
||||||
|
throw new MACPCapabilityError(
|
||||||
|
'MACP_NO_COMMAND',
|
||||||
|
'gate-spec',
|
||||||
|
`gate spec file '${spec}' parsed to ${typeof parsed} — expected a gates array, a task with quality_gates, or a gate object`,
|
||||||
|
);
|
||||||
|
} catch (exc) {
|
||||||
|
if (exc instanceof MACPCapabilityError) throw exc;
|
||||||
|
// Not JSON — treat each non-empty line as a command gate.
|
||||||
|
const lines = raw
|
||||||
|
.split('\n')
|
||||||
|
.map((l) => l.trim())
|
||||||
|
.filter((l) => l.length > 0);
|
||||||
|
if (lines.length > 0) return lines;
|
||||||
|
throw new MACPCapabilityError(
|
||||||
|
'MACP_NO_COMMAND',
|
||||||
|
'gate-spec',
|
||||||
|
`gate spec file '${spec}' contains no gates`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (spec.trim().length > 0) return [spec];
|
||||||
|
throw new MACPCapabilityError('MACP_NO_COMMAND', 'gate-spec', 'gate spec is empty');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Print a typed not-implemented failure and exit nonzero (RI-N2 fail-closed). */
|
||||||
|
function notImplemented(subcommand: string, capability: string, hint: string): void {
|
||||||
|
const err = new MACPCapabilityError(
|
||||||
|
'MACP_NOT_IMPLEMENTED',
|
||||||
|
capability,
|
||||||
|
`${subcommand} is not implemented in @mosaicstack/macp yet (${capability} capability absent) — ${hint}`,
|
||||||
|
);
|
||||||
|
console.error(`[macp] ${subcommand}: ${err.message} [${err.code}]`);
|
||||||
|
process.exitCode = 1;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register macp subcommands on an existing Commander program.
|
* Register macp subcommands on an existing Commander program.
|
||||||
* This avoids cross-package Commander version mismatches by using the
|
* This avoids cross-package Commander version mismatches by using the
|
||||||
@@ -24,15 +92,14 @@ export function registerMacpCommand(parent: Command): void {
|
|||||||
'Filter by task type (coding|deploy|research|review|documentation|infrastructure)',
|
'Filter by task type (coding|deploy|research|review|documentation|infrastructure)',
|
||||||
)
|
)
|
||||||
.action((opts: { status?: string; type?: string }) => {
|
.action((opts: { status?: string; type?: string }) => {
|
||||||
// not yet wired — task persistence layer is not present in @mosaicstack/macp
|
// unimplemented capability — a failure, never a success (RI-N2)
|
||||||
console.log('[macp] tasks list: not yet wired — use macp package programmatically');
|
|
||||||
if (opts.status) {
|
if (opts.status) {
|
||||||
console.log(` status filter: ${opts.status}`);
|
console.log(` status filter: ${opts.status}`);
|
||||||
}
|
}
|
||||||
if (opts.type) {
|
if (opts.type) {
|
||||||
console.log(` type filter: ${opts.type}`);
|
console.log(` type filter: ${opts.type}`);
|
||||||
}
|
}
|
||||||
process.exitCode = 0;
|
notImplemented('tasks list', 'task-persistence', 'use the macp package programmatically');
|
||||||
});
|
});
|
||||||
|
|
||||||
// ─── submit ──────────────────────────────────────────────────────────────
|
// ─── submit ──────────────────────────────────────────────────────────────
|
||||||
@@ -41,12 +108,11 @@ export function registerMacpCommand(parent: Command): void {
|
|||||||
.command('submit <path>')
|
.command('submit <path>')
|
||||||
.description('Submit a task from a JSON/YAML spec file')
|
.description('Submit a task from a JSON/YAML spec file')
|
||||||
.action((specPath: string) => {
|
.action((specPath: string) => {
|
||||||
// not yet wired — task submission requires a running MACP server
|
// unimplemented capability — a failure, never a success (RI-N2)
|
||||||
console.log('[macp] submit: not yet wired — use macp package programmatically');
|
|
||||||
console.log(` spec path: ${specPath}`);
|
console.log(` spec path: ${specPath}`);
|
||||||
console.log(' task id: (unavailable — no MACP server connected)');
|
console.log(' task id: (unavailable — no MACP server connected)');
|
||||||
console.log(' status: (unavailable — no MACP server connected)');
|
console.log(' status: (unavailable — no MACP server connected)');
|
||||||
process.exitCode = 0;
|
notImplemented('submit', 'macp-server', 'use the macp package programmatically');
|
||||||
});
|
});
|
||||||
|
|
||||||
// ─── gate ────────────────────────────────────────────────────────────────
|
// ─── gate ────────────────────────────────────────────────────────────────
|
||||||
@@ -58,16 +124,58 @@ export function registerMacpCommand(parent: Command): void {
|
|||||||
.option('--cwd <path>', 'Working directory for gate execution', process.cwd())
|
.option('--cwd <path>', 'Working directory for gate execution', process.cwd())
|
||||||
.option('--log <path>', 'Path to write gate log output', '/tmp/macp-gate.log')
|
.option('--log <path>', 'Path to write gate log output', '/tmp/macp-gate.log')
|
||||||
.option('--timeout <seconds>', 'Gate timeout in seconds', '60')
|
.option('--timeout <seconds>', 'Gate timeout in seconds', '60')
|
||||||
.action((spec: string, opts: { failOn: string; cwd: string; log: string; timeout: string }) => {
|
.option(
|
||||||
// not yet wired — gate execution requires a task context and event sink
|
'--simulate',
|
||||||
console.log('[macp] gate: not yet wired — use macp package programmatically');
|
'Simulate gates instead of executing them; results are typed simulated and never satisfy a check',
|
||||||
console.log(` spec: ${spec}`);
|
)
|
||||||
console.log(` fail-on: ${opts.failOn}`);
|
.action(
|
||||||
console.log(` cwd: ${opts.cwd}`);
|
(
|
||||||
console.log(` log: ${opts.log}`);
|
spec: string,
|
||||||
console.log(` timeout: ${opts.timeout}s`);
|
opts: { failOn: string; cwd: string; log: string; timeout: string; simulate?: boolean },
|
||||||
process.exitCode = 0;
|
) => {
|
||||||
});
|
let gates: unknown[];
|
||||||
|
try {
|
||||||
|
gates = loadGateSpec(spec);
|
||||||
|
} catch (exc) {
|
||||||
|
if (exc instanceof MACPCapabilityError) {
|
||||||
|
console.error(`[macp] gate: ${exc.message} [${exc.code}]`);
|
||||||
|
} else {
|
||||||
|
console.error(`[macp] gate: ${String(exc)}`);
|
||||||
|
}
|
||||||
|
process.exitCode = 1;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const timeoutSec = Number.parseInt(opts.timeout, 10) || 60;
|
||||||
|
const eventsPath = `${opts.log}.events.ndjson`;
|
||||||
|
const { state, gateResults } = runGates(
|
||||||
|
gates,
|
||||||
|
opts.cwd,
|
||||||
|
opts.log,
|
||||||
|
timeoutSec,
|
||||||
|
eventsPath,
|
||||||
|
'macp-cli-gate',
|
||||||
|
{
|
||||||
|
simulate: opts.simulate,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
for (const r of gateResults) {
|
||||||
|
const label = r.command || r.type;
|
||||||
|
const reason = r.reason ? ` — ${r.reason}` : '';
|
||||||
|
console.log(`[macp] gate ${r.status}: ${label}${reason}`);
|
||||||
|
}
|
||||||
|
if (opts.simulate) {
|
||||||
|
console.log(
|
||||||
|
'[macp] SIMULATED run — every result is typed simulated and can never satisfy a gate, dependency, or release check',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Simulated runs may complete (exit 0) only because the caller
|
||||||
|
// explicitly passed --simulate; the typed state stays 'simulated'.
|
||||||
|
process.exitCode = state === 'passed' || state === 'simulated' ? 0 : 1;
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
// ─── events ──────────────────────────────────────────────────────────────
|
// ─── events ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@@ -79,14 +187,16 @@ export function registerMacpCommand(parent: Command): void {
|
|||||||
.option('--file <path>', 'Path to the MACP events NDJSON file')
|
.option('--file <path>', 'Path to the MACP events NDJSON file')
|
||||||
.option('--follow', 'Follow the file for new events (like tail -f)')
|
.option('--follow', 'Follow the file for new events (like tail -f)')
|
||||||
.action((opts: { file?: string; follow?: boolean }) => {
|
.action((opts: { file?: string; follow?: boolean }) => {
|
||||||
// not yet wired — event streaming requires a live event source
|
// unimplemented capability — a failure, never a success (RI-N2)
|
||||||
console.log('[macp] events tail: not yet wired — use macp package programmatically');
|
|
||||||
if (opts.file) {
|
if (opts.file) {
|
||||||
console.log(` file: ${opts.file}`);
|
console.log(` file: ${opts.file}`);
|
||||||
}
|
}
|
||||||
if (opts.follow) {
|
if (opts.follow) {
|
||||||
console.log(' mode: follow');
|
console.log(' mode: follow');
|
||||||
}
|
}
|
||||||
process.exitCode = 0;
|
notImplemented('events tail', 'event-source', 'use the macp package programmatically');
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Re-export so CLI consumers can surface typed capability codes.
|
||||||
|
export type { MacpErrorCode };
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
/** Typed error code from the closed MACP_ERROR_CODES set. */
|
||||||
|
export type MacpErrorCode = (typeof MACP_ERROR_CODES)[number];
|
||||||
|
/**
|
||||||
|
* Typed fail-closed capability errors (RI-N2, SDLC-D-035).
|
||||||
|
*
|
||||||
|
* MACP must fail closed when a required capability (executor, reviewer,
|
||||||
|
* command, CI provider, human authority) is absent. These typed codes mirror
|
||||||
|
* the Forge failure vocabulary (FORGE_NO_*) so both packages speak the same
|
||||||
|
* language: an unimplemented capability is a failure, never a stub success.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** Closed set of typed MACP capability error codes. */
|
||||||
|
export const MACP_ERROR_CODES = [
|
||||||
|
'MACP_NOT_IMPLEMENTED',
|
||||||
|
'MACP_NO_COMMAND',
|
||||||
|
'MACP_NO_REVIEWER',
|
||||||
|
'MACP_NO_CI_PIPELINE',
|
||||||
|
'MACP_NO_PROVIDER',
|
||||||
|
'MACP_AUTHORITY_REQUIRED',
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
/** Raised when a required capability is missing and execution must fail closed. */
|
||||||
|
export class MACPCapabilityError extends Error {
|
||||||
|
/** Typed error code from the closed MACP_ERROR_CODES set. */
|
||||||
|
readonly code: MacpErrorCode;
|
||||||
|
/** The missing capability, e.g. `ci-provider`, `task-persistence`, `command`. */
|
||||||
|
readonly capability: string;
|
||||||
|
|
||||||
|
constructor(code: MacpErrorCode, capability: string, message: string) {
|
||||||
|
super(message);
|
||||||
|
this.name = 'MACPCapabilityError';
|
||||||
|
this.code = code;
|
||||||
|
this.capability = capability;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,429 @@
|
|||||||
|
import fs from 'node:fs';
|
||||||
|
import os from 'node:os';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||||
|
|
||||||
|
import { countAIFindings, normalizeGate, runGate, runGates } from './gate-runner.js';
|
||||||
|
|
||||||
|
function makeTmpDir(): string {
|
||||||
|
return fs.mkdtempSync(path.join(os.tmpdir(), 'macp-gate-'));
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('normalizeGate', () => {
|
||||||
|
it('normalizes a string to mechanical gate', () => {
|
||||||
|
expect(normalizeGate('echo test')).toEqual({
|
||||||
|
command: 'echo test',
|
||||||
|
type: 'mechanical',
|
||||||
|
fail_on: 'blocker',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('normalizes an object gate with defaults', () => {
|
||||||
|
expect(normalizeGate({ command: 'lint' })).toEqual({
|
||||||
|
command: 'lint',
|
||||||
|
type: 'mechanical',
|
||||||
|
fail_on: 'blocker',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('preserves explicit type and fail_on', () => {
|
||||||
|
expect(normalizeGate({ command: 'review', type: 'ai-review', fail_on: 'any' })).toEqual({
|
||||||
|
command: 'review',
|
||||||
|
type: 'ai-review',
|
||||||
|
fail_on: 'any',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('handles non-string/non-object input', () => {
|
||||||
|
expect(normalizeGate(42)).toEqual({ command: '', type: 'mechanical', fail_on: 'blocker' });
|
||||||
|
expect(normalizeGate(null)).toEqual({ command: '', type: 'mechanical', fail_on: 'blocker' });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('countAIFindings', () => {
|
||||||
|
it('returns zeros for non-object', () => {
|
||||||
|
expect(countAIFindings(null)).toEqual({ blockers: 0, total: 0 });
|
||||||
|
expect(countAIFindings('string')).toEqual({ blockers: 0, total: 0 });
|
||||||
|
expect(countAIFindings([])).toEqual({ blockers: 0, total: 0 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('counts from stats block', () => {
|
||||||
|
const output = { stats: { blockers: 2, should_fix: 3, suggestions: 1 } };
|
||||||
|
expect(countAIFindings(output)).toEqual({ blockers: 2, total: 6 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('counts from findings array when stats has no blockers', () => {
|
||||||
|
const output = {
|
||||||
|
stats: { blockers: 0 },
|
||||||
|
findings: [{ severity: 'blocker' }, { severity: 'warning' }, { severity: 'blocker' }],
|
||||||
|
};
|
||||||
|
expect(countAIFindings(output)).toEqual({ blockers: 2, total: 3 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('uses stats blockers over findings array when stats has blockers', () => {
|
||||||
|
const output = {
|
||||||
|
stats: { blockers: 5 },
|
||||||
|
findings: [{ severity: 'blocker' }, { severity: 'warning' }],
|
||||||
|
};
|
||||||
|
// stats.blockers = 5, total from stats = 5+0+0 = 5, findings not used for total since stats total is non-zero
|
||||||
|
expect(countAIFindings(output)).toEqual({ blockers: 5, total: 5 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('counts findings length as total when stats has zero total', () => {
|
||||||
|
const output = {
|
||||||
|
findings: [{ severity: 'warning' }, { severity: 'info' }],
|
||||||
|
};
|
||||||
|
expect(countAIFindings(output)).toEqual({ blockers: 0, total: 2 });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('runGate', () => {
|
||||||
|
let tmp: string;
|
||||||
|
let logPath: string;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
tmp = makeTmpDir();
|
||||||
|
logPath = path.join(tmp, 'gate.log');
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
fs.rmSync(tmp, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('passes mechanical gate on exit 0', () => {
|
||||||
|
const result = runGate('echo hello', tmp, logPath, 30);
|
||||||
|
expect(result.passed).toBe(true);
|
||||||
|
expect(result.exit_code).toBe(0);
|
||||||
|
expect(result.type).toBe('mechanical');
|
||||||
|
expect(result.output).toContain('hello');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fails mechanical gate on non-zero exit', () => {
|
||||||
|
const result = runGate('exit 1', tmp, logPath, 30);
|
||||||
|
expect(result.passed).toBe(false);
|
||||||
|
expect(result.exit_code).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ci-pipeline fails closed without a CI provider (no placeholder pass)', () => {
|
||||||
|
const result = runGate({ command: 'anything', type: 'ci-pipeline' }, tmp, logPath, 30);
|
||||||
|
expect(result.passed).toBe(false);
|
||||||
|
expect(result.status).toBe('capability_failure');
|
||||||
|
expect(result.capability_code).toBe('MACP_NO_CI_PIPELINE');
|
||||||
|
expect(result.type).toBe('ci-pipeline');
|
||||||
|
expect(result.output).not.toBe('CI pipeline gate placeholder');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('empty command is a typed capability failure, never a pass', () => {
|
||||||
|
const result = runGate({ command: '' }, tmp, logPath, 30);
|
||||||
|
expect(result.passed).toBe(false);
|
||||||
|
expect(result.status).toBe('capability_failure');
|
||||||
|
expect(result.capability_code).toBe('MACP_NO_COMMAND');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ai-review gate parses JSON output', () => {
|
||||||
|
const json = JSON.stringify({ stats: { blockers: 0, should_fix: 1 } });
|
||||||
|
const result = runGate({ command: `echo '${json}'`, type: 'ai-review' }, tmp, logPath, 30);
|
||||||
|
expect(result.passed).toBe(true);
|
||||||
|
expect(result.blockers).toBe(0);
|
||||||
|
expect(result.findings).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ai-review gate fails on blockers', () => {
|
||||||
|
const json = JSON.stringify({ stats: { blockers: 2 } });
|
||||||
|
const result = runGate({ command: `echo '${json}'`, type: 'ai-review' }, tmp, logPath, 30);
|
||||||
|
expect(result.passed).toBe(false);
|
||||||
|
expect(result.blockers).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ai-review gate with fail_on=any fails on any findings', () => {
|
||||||
|
const json = JSON.stringify({ stats: { blockers: 0, should_fix: 1 } });
|
||||||
|
const result = runGate(
|
||||||
|
{ command: `echo '${json}'`, type: 'ai-review', fail_on: 'any' },
|
||||||
|
tmp,
|
||||||
|
logPath,
|
||||||
|
30,
|
||||||
|
);
|
||||||
|
expect(result.passed).toBe(false);
|
||||||
|
expect(result.fail_on).toBe('any');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ai-review gate fails on invalid JSON output', () => {
|
||||||
|
const result = runGate({ command: 'echo "not json"', type: 'ai-review' }, tmp, logPath, 30);
|
||||||
|
expect(result.passed).toBe(false);
|
||||||
|
expect(result.parse_error).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('writes to log file', () => {
|
||||||
|
runGate('echo logged', tmp, logPath, 30);
|
||||||
|
const log = fs.readFileSync(logPath, 'utf-8');
|
||||||
|
expect(log).toContain('COMMAND: echo logged');
|
||||||
|
expect(log).toContain('logged');
|
||||||
|
expect(log).toContain('EXIT:');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('runGates', () => {
|
||||||
|
let tmp: string;
|
||||||
|
let logPath: string;
|
||||||
|
let eventsPath: string;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
tmp = makeTmpDir();
|
||||||
|
logPath = path.join(tmp, 'gates.log');
|
||||||
|
eventsPath = path.join(tmp, 'events.ndjson');
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
fs.rmSync(tmp, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('runs multiple gates and returns results', () => {
|
||||||
|
const { allPassed, gateResults } = runGates(
|
||||||
|
['echo one', 'echo two'],
|
||||||
|
tmp,
|
||||||
|
logPath,
|
||||||
|
30,
|
||||||
|
eventsPath,
|
||||||
|
'task-1',
|
||||||
|
);
|
||||||
|
expect(allPassed).toBe(true);
|
||||||
|
expect(gateResults).toHaveLength(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('reports failure when any gate fails', () => {
|
||||||
|
const { allPassed, gateResults } = runGates(
|
||||||
|
['echo ok', 'exit 1'],
|
||||||
|
tmp,
|
||||||
|
logPath,
|
||||||
|
30,
|
||||||
|
eventsPath,
|
||||||
|
'task-2',
|
||||||
|
);
|
||||||
|
expect(allPassed).toBe(false);
|
||||||
|
expect(gateResults[0]!.passed).toBe(true);
|
||||||
|
expect(gateResults[1]!.passed).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('emits events for each gate', () => {
|
||||||
|
runGates(['echo test'], tmp, logPath, 30, eventsPath, 'task-3');
|
||||||
|
const events = fs
|
||||||
|
.readFileSync(eventsPath, 'utf-8')
|
||||||
|
.trim()
|
||||||
|
.split('\n')
|
||||||
|
.map((l) => JSON.parse(l));
|
||||||
|
expect(events).toHaveLength(2); // started + passed
|
||||||
|
expect(events[0].event_type).toBe('rail.check.started');
|
||||||
|
expect(events[1].event_type).toBe('rail.check.passed');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not silently skip gates with empty command — they become capability failures', () => {
|
||||||
|
const { gateResults, allPassed, state } = runGates(
|
||||||
|
[{ command: '', type: 'mechanical' }, 'echo real'],
|
||||||
|
tmp,
|
||||||
|
logPath,
|
||||||
|
30,
|
||||||
|
eventsPath,
|
||||||
|
'task-4',
|
||||||
|
);
|
||||||
|
expect(gateResults).toHaveLength(2);
|
||||||
|
expect(gateResults[0]!.status).toBe('capability_failure');
|
||||||
|
expect(gateResults[1]!.status).toBe('passed');
|
||||||
|
expect(allPassed).toBe(false);
|
||||||
|
expect(state).toBe('capability_failure');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not skip ci-pipeline even with empty command — typed capability failure', () => {
|
||||||
|
const { gateResults, allPassed, state } = runGates(
|
||||||
|
[{ command: '', type: 'ci-pipeline' }],
|
||||||
|
tmp,
|
||||||
|
logPath,
|
||||||
|
30,
|
||||||
|
eventsPath,
|
||||||
|
'task-5',
|
||||||
|
);
|
||||||
|
expect(gateResults).toHaveLength(1);
|
||||||
|
expect(gateResults[0]!.passed).toBe(false);
|
||||||
|
expect(gateResults[0]!.status).toBe('capability_failure');
|
||||||
|
expect(allPassed).toBe(false);
|
||||||
|
expect(state).toBe('capability_failure');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('emits failed event with correct message', () => {
|
||||||
|
runGates(['exit 42'], tmp, logPath, 30, eventsPath, 'task-6');
|
||||||
|
const events = fs
|
||||||
|
.readFileSync(eventsPath, 'utf-8')
|
||||||
|
.trim()
|
||||||
|
.split('\n')
|
||||||
|
.map((l) => JSON.parse(l));
|
||||||
|
const failEvent = events.find(
|
||||||
|
(e: Record<string, unknown>) => e.event_type === 'rail.check.failed',
|
||||||
|
);
|
||||||
|
expect(failEvent).toBeDefined();
|
||||||
|
expect(failEvent.message).toContain('Gate failed (');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* RI-N2 / SDLC-D-035 fail-closed controls for the MACP gate runner.
|
||||||
|
*
|
||||||
|
* Invariant under test: `passed: true` occurs ONLY when a gate really executed
|
||||||
|
* and really exited green (`status === 'passed'`). Absent capabilities,
|
||||||
|
* manual sign-offs, and simulated runs are typed distinctly and can never
|
||||||
|
* make the aggregate `passed`.
|
||||||
|
*/
|
||||||
|
describe('gate-runner fail-closed (RI-N2)', () => {
|
||||||
|
let tmpDir: string;
|
||||||
|
let logPath: string;
|
||||||
|
let eventsPath: string;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
tmpDir = makeTmpDir();
|
||||||
|
logPath = path.join(tmpDir, 'gate.log');
|
||||||
|
eventsPath = path.join(tmpDir, 'events.ndjson');
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
function run(gates: unknown[], options?: { simulate?: boolean }) {
|
||||||
|
return runGates(gates, tmpDir, logPath, 10, eventsPath, 'spec-task', options);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── positive controls ───────────────────────────────────────────────────
|
||||||
|
|
||||||
|
it('a really-executed green command gate still passes', () => {
|
||||||
|
const result = run([{ command: 'exit 0', type: 'mechanical' }]);
|
||||||
|
expect(result.gateResults[0]!.status).toBe('passed');
|
||||||
|
expect(result.gateResults[0]!.passed).toBe(true);
|
||||||
|
expect(result.allPassed).toBe(true);
|
||||||
|
expect(result.state).toBe('passed');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('explicit simulate completes and types every result simulated', () => {
|
||||||
|
const result = run([{ command: 'exit 0', type: 'mechanical' }, 'echo hello'], {
|
||||||
|
simulate: true,
|
||||||
|
});
|
||||||
|
expect(result.gateResults).toHaveLength(2);
|
||||||
|
for (const gate of result.gateResults) {
|
||||||
|
expect(gate.status).toBe('simulated');
|
||||||
|
expect(gate.passed).toBe(false);
|
||||||
|
}
|
||||||
|
expect(result.state).toBe('simulated');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a really-executed red command gate fails with typed status failed', () => {
|
||||||
|
const result = run([{ command: 'exit 3', type: 'mechanical' }]);
|
||||||
|
expect(result.gateResults[0]!.status).toBe('failed');
|
||||||
|
expect(result.gateResults[0]!.passed).toBe(false);
|
||||||
|
expect(result.allPassed).toBe(false);
|
||||||
|
expect(result.state).toBe('failed');
|
||||||
|
});
|
||||||
|
|
||||||
|
// ─── negative controls — each asserts typed status AND aggregate not passed ──
|
||||||
|
|
||||||
|
it('an empty-command gate is a capability_failure, not skipped and not passed', () => {
|
||||||
|
const result = run([{ command: '', type: 'mechanical' }]);
|
||||||
|
// runGates must not silently skip it — it produces a typed result
|
||||||
|
expect(result.gateResults).toHaveLength(1);
|
||||||
|
const gate = result.gateResults[0]!;
|
||||||
|
expect(gate.status).toBe('capability_failure');
|
||||||
|
expect(gate.capability_code).toBe('MACP_NO_COMMAND');
|
||||||
|
expect(gate.passed).toBe(false);
|
||||||
|
// aggregate is not passed
|
||||||
|
expect(result.allPassed).toBe(false);
|
||||||
|
expect(result.state).toBe('capability_failure');
|
||||||
|
expect(result.state).not.toBe('passed');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a commandless ai-review gate is a typed MACP_NO_REVIEWER capability_failure', () => {
|
||||||
|
const result = run([{ command: '', type: 'ai-review' }]);
|
||||||
|
expect(result.gateResults[0]!.status).toBe('capability_failure');
|
||||||
|
expect(result.gateResults[0]!.capability_code).toBe('MACP_NO_REVIEWER');
|
||||||
|
expect(result.allPassed).toBe(false);
|
||||||
|
expect(result.state).not.toBe('passed');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a ci-pipeline gate without a provider implementation is a capability_failure, never a placeholder pass', () => {
|
||||||
|
const result = run([{ command: '', type: 'ci-pipeline' }]);
|
||||||
|
const gate = result.gateResults[0]!;
|
||||||
|
expect(gate.status).toBe('capability_failure');
|
||||||
|
expect(gate.capability_code).toBe('MACP_NO_CI_PIPELINE');
|
||||||
|
expect(gate.passed).toBe(false);
|
||||||
|
// the old false-success placeholder must be gone
|
||||||
|
expect(gate.output).not.toBe('CI pipeline gate placeholder');
|
||||||
|
expect(result.allPassed).toBe(false);
|
||||||
|
expect(result.state).not.toBe('passed');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a ci-pipeline gate fails closed even alongside an otherwise green run', () => {
|
||||||
|
const result = run(['exit 0', { type: 'ci-pipeline', command: 'fake-ci' }]);
|
||||||
|
expect(result.gateResults[1]!.status).toBe('capability_failure');
|
||||||
|
expect(result.gateResults[0]!.status).toBe('passed');
|
||||||
|
expect(result.allPassed).toBe(false);
|
||||||
|
expect(result.state).toBe('capability_failure');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a manual gate with no automation enters typed waiting — neither pass nor fail', () => {
|
||||||
|
const result = run([{ type: 'manual' }]);
|
||||||
|
const gate = result.gateResults[0]!;
|
||||||
|
expect(gate.status).toBe('waiting');
|
||||||
|
expect(gate.passed).toBe(false);
|
||||||
|
expect(gate.exit_code).toBe(0);
|
||||||
|
// aggregate is not passed while any gate is waiting
|
||||||
|
expect(result.allPassed).toBe(false);
|
||||||
|
expect(result.state).toBe('waiting');
|
||||||
|
expect(result.state).not.toBe('passed');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a simulated result can never make the aggregate passed', () => {
|
||||||
|
const result = run(['exit 0', 'exit 0'], { simulate: true });
|
||||||
|
expect(result.gateResults.every((g) => g.status === 'simulated')).toBe(true);
|
||||||
|
expect(result.allPassed).toBe(false);
|
||||||
|
expect(result.state).toBe('simulated');
|
||||||
|
expect(result.state).not.toBe('passed');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('waiting dominates an otherwise green aggregate', () => {
|
||||||
|
const result = run(['exit 0', { type: 'manual' }]);
|
||||||
|
expect(result.allPassed).toBe(false);
|
||||||
|
expect(result.state).toBe('waiting');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('runGate fail-closed (RI-N2)', () => {
|
||||||
|
let tmpDir: string;
|
||||||
|
let logPath: string;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
tmpDir = makeTmpDir();
|
||||||
|
logPath = path.join(tmpDir, 'gate.log');
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('simulate: true returns a typed simulated result without executing', () => {
|
||||||
|
const result = runGate('this-command-does-not-exist-xyz', tmpDir, logPath, 10, {
|
||||||
|
simulate: true,
|
||||||
|
});
|
||||||
|
expect(result.status).toBe('simulated');
|
||||||
|
expect(result.passed).toBe(false);
|
||||||
|
expect(result.exit_code).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('normal mode executes for real and types a green gate passed', () => {
|
||||||
|
const result = runGate('echo ok', tmpDir, logPath, 10);
|
||||||
|
expect(result.status).toBe('passed');
|
||||||
|
expect(result.passed).toBe(true);
|
||||||
|
expect(result.output).toContain('ok');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a bare string gate normalizes to mechanical and executes', () => {
|
||||||
|
const result = runGate('exit 7', tmpDir, logPath, 10);
|
||||||
|
expect(result.type).toBe('mechanical');
|
||||||
|
expect(result.status).toBe('failed');
|
||||||
|
expect(result.passed).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -4,7 +4,20 @@ import { dirname } from 'node:path';
|
|||||||
|
|
||||||
import { emitEvent } from './event-emitter.js';
|
import { emitEvent } from './event-emitter.js';
|
||||||
import { nowISO } from './event-emitter.js';
|
import { nowISO } from './event-emitter.js';
|
||||||
import type { GateResult } from './types.js';
|
import type { GateResult, GateStatus, RunGatesResult } from './types.js';
|
||||||
|
|
||||||
|
/** Typed reason stamped on every simulated gate result. */
|
||||||
|
export const SIMULATED_GATE_REASON =
|
||||||
|
'simulated execution (explicit simulate opt-in): gate was not evaluated by a real implementation';
|
||||||
|
|
||||||
|
/** Options for gate execution (RI-N2 fail-closed / explicit simulation). */
|
||||||
|
export interface RunGateOptions {
|
||||||
|
/**
|
||||||
|
* Explicit caller opt-in to simulation. Simulated gates are NOT executed;
|
||||||
|
* every result is typed `simulated` and never satisfies anything.
|
||||||
|
*/
|
||||||
|
simulate?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
export interface NormalizedGate {
|
export interface NormalizedGate {
|
||||||
command: string;
|
command: string;
|
||||||
@@ -103,36 +116,91 @@ export function countAIFindings(parsedOutput: unknown): { blockers: number; tota
|
|||||||
return { blockers, total };
|
return { blockers, total };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function simulatedResult(gateEntry: NormalizedGate): GateResult {
|
||||||
|
return {
|
||||||
|
command: gateEntry.command,
|
||||||
|
exit_code: 0,
|
||||||
|
type: gateEntry.type,
|
||||||
|
output: SIMULATED_GATE_REASON,
|
||||||
|
timed_out: false,
|
||||||
|
passed: false,
|
||||||
|
status: 'simulated',
|
||||||
|
reason: SIMULATED_GATE_REASON,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function capabilityFailureResult(
|
||||||
|
gateEntry: NormalizedGate,
|
||||||
|
code: GateResult['capability_code'],
|
||||||
|
reason: string,
|
||||||
|
): GateResult {
|
||||||
|
return {
|
||||||
|
command: gateEntry.command,
|
||||||
|
exit_code: 1,
|
||||||
|
type: gateEntry.type,
|
||||||
|
output: '',
|
||||||
|
timed_out: false,
|
||||||
|
passed: false,
|
||||||
|
status: 'capability_failure',
|
||||||
|
capability_code: code,
|
||||||
|
reason,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function waitingResult(gateEntry: NormalizedGate, reason: string): GateResult {
|
||||||
|
return {
|
||||||
|
command: gateEntry.command,
|
||||||
|
exit_code: 0,
|
||||||
|
type: gateEntry.type,
|
||||||
|
output: '',
|
||||||
|
timed_out: false,
|
||||||
|
passed: false,
|
||||||
|
status: 'waiting',
|
||||||
|
capability_code: 'MACP_AUTHORITY_REQUIRED',
|
||||||
|
reason,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
export function runGate(
|
export function runGate(
|
||||||
gate: unknown,
|
gate: unknown,
|
||||||
cwd: string,
|
cwd: string,
|
||||||
logPath: string,
|
logPath: string,
|
||||||
timeoutSec: number,
|
timeoutSec: number,
|
||||||
|
options: RunGateOptions = {},
|
||||||
): GateResult {
|
): GateResult {
|
||||||
const gateEntry = normalizeGate(gate);
|
const gateEntry = normalizeGate(gate);
|
||||||
const gateType = gateEntry.type;
|
const gateType = gateEntry.type;
|
||||||
const command = gateEntry.command;
|
const command = gateEntry.command;
|
||||||
|
|
||||||
|
// Explicit simulation only: never executes, typed simulated, never satisfying.
|
||||||
|
if (options.simulate) {
|
||||||
|
return simulatedResult(gateEntry);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fail closed: no CI provider implementation exists in @mosaicstack/macp,
|
||||||
|
// so a ci-pipeline gate is an absent capability — never a placeholder pass.
|
||||||
if (gateType === 'ci-pipeline') {
|
if (gateType === 'ci-pipeline') {
|
||||||
return {
|
return capabilityFailureResult(
|
||||||
command,
|
gateEntry,
|
||||||
exit_code: 0,
|
'MACP_NO_CI_PIPELINE',
|
||||||
type: gateType,
|
`ci-pipeline gate '${gateEntry.command || gateType}' has no CI provider implementation wired — refusing placeholder pass`,
|
||||||
output: 'CI pipeline gate placeholder',
|
);
|
||||||
timed_out: false,
|
|
||||||
passed: true,
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!command) {
|
if (!command) {
|
||||||
return {
|
// A manual gate with no automation waits for human sign-off: not pass, not fail.
|
||||||
command: '',
|
if (gateType === 'manual') {
|
||||||
exit_code: 0,
|
return waitingResult(
|
||||||
type: gateType,
|
gateEntry,
|
||||||
output: '',
|
`manual gate has no automation — waiting for human sign-off (type: ${gateType})`,
|
||||||
timed_out: false,
|
);
|
||||||
passed: true,
|
}
|
||||||
};
|
// Any other commandless gate is an absent capability — never a vacuous pass.
|
||||||
|
return capabilityFailureResult(
|
||||||
|
gateEntry,
|
||||||
|
gateType === 'ai-review' ? 'MACP_NO_REVIEWER' : 'MACP_NO_COMMAND',
|
||||||
|
`gate of type '${gateType}' has no command to execute — refusing empty-command pass`,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const { exitCode, output, timedOut } = runShell(command, cwd, logPath, timeoutSec);
|
const { exitCode, output, timedOut } = runShell(command, cwd, logPath, timeoutSec);
|
||||||
@@ -143,10 +211,12 @@ export function runGate(
|
|||||||
output,
|
output,
|
||||||
timed_out: timedOut,
|
timed_out: timedOut,
|
||||||
passed: false,
|
passed: false,
|
||||||
|
status: 'failed',
|
||||||
};
|
};
|
||||||
|
|
||||||
if (gateType !== 'ai-review') {
|
if (gateType !== 'ai-review') {
|
||||||
result.passed = exitCode === 0;
|
result.passed = exitCode === 0;
|
||||||
|
result.status = result.passed ? 'passed' : 'failed';
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -170,6 +240,7 @@ export function runGate(
|
|||||||
} else {
|
} else {
|
||||||
result.passed = exitCode === 0 && blockers === 0 && !timedOut && parseError === undefined;
|
result.passed = exitCode === 0 && blockers === 0 && !timedOut && parseError === undefined;
|
||||||
}
|
}
|
||||||
|
result.status = result.passed ? 'passed' : 'failed';
|
||||||
|
|
||||||
result.fail_on = failOn;
|
result.fail_on = failOn;
|
||||||
result.blockers = blockers;
|
result.blockers = blockers;
|
||||||
@@ -191,16 +262,19 @@ export function runGates(
|
|||||||
timeoutSec: number,
|
timeoutSec: number,
|
||||||
eventsPath: string,
|
eventsPath: string,
|
||||||
taskId: string,
|
taskId: string,
|
||||||
): { allPassed: boolean; gateResults: GateResult[] } {
|
options: RunGateOptions = {},
|
||||||
let allPassed = true;
|
): RunGatesResult {
|
||||||
const gateResults: GateResult[] = [];
|
const gateResults: GateResult[] = [];
|
||||||
|
let hasCapabilityFailure = false;
|
||||||
|
let hasSimulated = false;
|
||||||
|
let hasFailed = false;
|
||||||
|
let hasWaiting = false;
|
||||||
|
|
||||||
for (const gate of gates) {
|
for (const gate of gates) {
|
||||||
const gateEntry = normalizeGate(gate);
|
const gateEntry = normalizeGate(gate);
|
||||||
const gateCmd = gateEntry.command;
|
const gateCmd = gateEntry.command;
|
||||||
if (!gateCmd && gateEntry.type !== 'ci-pipeline') continue;
|
|
||||||
|
|
||||||
const label = gateCmd || gateEntry.type;
|
const label = gateCmd || gateEntry.type;
|
||||||
|
// NOTE: no silent skip — every gate produces a typed result (RI-N2).
|
||||||
emitEvent(
|
emitEvent(
|
||||||
eventsPath,
|
eventsPath,
|
||||||
'rail.check.started',
|
'rail.check.started',
|
||||||
@@ -209,10 +283,10 @@ export function runGates(
|
|||||||
'quality-gate',
|
'quality-gate',
|
||||||
`Running gate: ${label}`,
|
`Running gate: ${label}`,
|
||||||
);
|
);
|
||||||
const result = runGate(gate, cwd, logPath, timeoutSec);
|
const result = runGate(gate, cwd, logPath, timeoutSec, options);
|
||||||
gateResults.push(result);
|
gateResults.push(result);
|
||||||
|
|
||||||
if (result.passed) {
|
if (result.status === 'passed') {
|
||||||
emitEvent(
|
emitEvent(
|
||||||
eventsPath,
|
eventsPath,
|
||||||
'rail.check.passed',
|
'rail.check.passed',
|
||||||
@@ -224,7 +298,46 @@ export function runGates(
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
allPassed = false;
|
if (result.status === 'waiting') {
|
||||||
|
hasWaiting = true;
|
||||||
|
emitEvent(
|
||||||
|
eventsPath,
|
||||||
|
'rail.check.waiting',
|
||||||
|
taskId,
|
||||||
|
'gated',
|
||||||
|
'quality-gate',
|
||||||
|
`Gate waiting: ${label} — ${result.reason ?? 'manual gate awaits sign-off'}`,
|
||||||
|
);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result.status === 'simulated') {
|
||||||
|
hasSimulated = true;
|
||||||
|
emitEvent(
|
||||||
|
eventsPath,
|
||||||
|
'rail.check.simulated',
|
||||||
|
taskId,
|
||||||
|
'gated',
|
||||||
|
'quality-gate',
|
||||||
|
`Gate simulated (non-satisfying): ${label}`,
|
||||||
|
);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result.status === 'capability_failure') {
|
||||||
|
hasCapabilityFailure = true;
|
||||||
|
emitEvent(
|
||||||
|
eventsPath,
|
||||||
|
'rail.check.failed',
|
||||||
|
taskId,
|
||||||
|
'gated',
|
||||||
|
'quality-gate',
|
||||||
|
`Gate capability failure (${result.capability_code ?? 'MACP_NO_PROVIDER'}): ${label} — ${result.reason ?? 'required capability is absent'}`,
|
||||||
|
);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
hasFailed = true;
|
||||||
let message: string;
|
let message: string;
|
||||||
if (result.timed_out) {
|
if (result.timed_out) {
|
||||||
message = `Gate timed out after ${timeoutSec}s: ${label}`;
|
message = `Gate timed out after ${timeoutSec}s: ${label}`;
|
||||||
@@ -236,5 +349,15 @@ export function runGates(
|
|||||||
emitEvent(eventsPath, 'rail.check.failed', taskId, 'gated', 'quality-gate', message);
|
emitEvent(eventsPath, 'rail.check.failed', taskId, 'gated', 'quality-gate', message);
|
||||||
}
|
}
|
||||||
|
|
||||||
return { allPassed, gateResults };
|
const state: GateStatus = hasCapabilityFailure
|
||||||
|
? 'capability_failure'
|
||||||
|
: hasSimulated
|
||||||
|
? 'simulated'
|
||||||
|
: hasFailed
|
||||||
|
? 'failed'
|
||||||
|
: hasWaiting
|
||||||
|
? 'waiting'
|
||||||
|
: 'passed';
|
||||||
|
|
||||||
|
return { allPassed: state === 'passed', gateResults, state };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,11 +6,13 @@ export type {
|
|||||||
DependsOnPolicy,
|
DependsOnPolicy,
|
||||||
GateType,
|
GateType,
|
||||||
GateFailOn,
|
GateFailOn,
|
||||||
|
GateStatus,
|
||||||
GateEntry,
|
GateEntry,
|
||||||
Task,
|
Task,
|
||||||
EventType,
|
EventType,
|
||||||
MACPEvent,
|
MACPEvent,
|
||||||
GateResult,
|
GateResult,
|
||||||
|
RunGatesResult,
|
||||||
TaskResult,
|
TaskResult,
|
||||||
ProviderMeta,
|
ProviderMeta,
|
||||||
ProviderRegistry,
|
ProviderRegistry,
|
||||||
@@ -18,6 +20,11 @@ export type {
|
|||||||
|
|
||||||
export { CredentialError } from './types.js';
|
export { CredentialError } from './types.js';
|
||||||
|
|
||||||
|
// Typed fail-closed capability errors (RI-N2, SDLC-D-035)
|
||||||
|
export { MACP_ERROR_CODES, MACPCapabilityError } from './errors.js';
|
||||||
|
|
||||||
|
export type { MacpErrorCode } from './errors.js';
|
||||||
|
|
||||||
// Credential resolver
|
// Credential resolver
|
||||||
export {
|
export {
|
||||||
DEFAULT_CREDENTIALS_DIR,
|
DEFAULT_CREDENTIALS_DIR,
|
||||||
@@ -35,9 +42,16 @@ export {
|
|||||||
export type { ResolveCredentialsOptions } from './credential-resolver.js';
|
export type { ResolveCredentialsOptions } from './credential-resolver.js';
|
||||||
|
|
||||||
// Gate runner
|
// Gate runner
|
||||||
export { normalizeGate, runShell, countAIFindings, runGate, runGates } from './gate-runner.js';
|
export {
|
||||||
|
normalizeGate,
|
||||||
|
runShell,
|
||||||
|
countAIFindings,
|
||||||
|
runGate,
|
||||||
|
runGates,
|
||||||
|
SIMULATED_GATE_REASON,
|
||||||
|
} from './gate-runner.js';
|
||||||
|
|
||||||
export type { NormalizedGate } from './gate-runner.js';
|
export type { NormalizedGate, RunGateOptions } from './gate-runner.js';
|
||||||
|
|
||||||
// Risk-floor (agent reflection loop — diff review classifier)
|
// Risk-floor (agent reflection loop — diff review classifier)
|
||||||
export { evaluateRiskFloor, DEFAULT_RISK_THRESHOLD } from './risk-floor.js';
|
export { evaluateRiskFloor, DEFAULT_RISK_THRESHOLD } from './risk-floor.js';
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import type { MacpErrorCode } from './errors.js';
|
||||||
|
|
||||||
/** Task status values. */
|
/** Task status values. */
|
||||||
export type TaskStatus = 'pending' | 'running' | 'gated' | 'completed' | 'failed' | 'escalated';
|
export type TaskStatus = 'pending' | 'running' | 'gated' | 'completed' | 'failed' | 'escalated';
|
||||||
|
|
||||||
@@ -17,7 +19,17 @@ export type DispatchMode = 'yolo' | 'acp' | 'exec';
|
|||||||
export type DependsOnPolicy = 'all' | 'any' | 'all_terminal';
|
export type DependsOnPolicy = 'all' | 'any' | 'all_terminal';
|
||||||
|
|
||||||
/** Quality gate type. */
|
/** Quality gate type. */
|
||||||
export type GateType = 'mechanical' | 'ai-review' | 'ci-pipeline';
|
export type GateType = 'mechanical' | 'ai-review' | 'ci-pipeline' | 'manual';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Typed execution state of a gate — closed set (RI-N2, SDLC-D-035).
|
||||||
|
*
|
||||||
|
* Only `passed` means "really executed and green". `simulated` is produced
|
||||||
|
* exclusively under an explicit simulate opt-in and never satisfies anything.
|
||||||
|
* `capability_failure` means a required executor/provider/command was absent.
|
||||||
|
* `waiting` means a manual gate awaits human sign-off (neither pass nor fail).
|
||||||
|
*/
|
||||||
|
export type GateStatus = 'passed' | 'failed' | 'simulated' | 'waiting' | 'capability_failure';
|
||||||
|
|
||||||
/** Gate fail_on mode. */
|
/** Gate fail_on mode. */
|
||||||
export type GateFailOn = 'blocker' | 'any';
|
export type GateFailOn = 'blocker' | 'any';
|
||||||
@@ -67,7 +79,9 @@ export type EventType =
|
|||||||
| 'task.retry.scheduled'
|
| 'task.retry.scheduled'
|
||||||
| 'rail.check.started'
|
| 'rail.check.started'
|
||||||
| 'rail.check.passed'
|
| 'rail.check.passed'
|
||||||
| 'rail.check.failed';
|
| 'rail.check.failed'
|
||||||
|
| 'rail.check.waiting'
|
||||||
|
| 'rail.check.simulated';
|
||||||
|
|
||||||
/** Structured event record. */
|
/** Structured event record. */
|
||||||
export interface MACPEvent {
|
export interface MACPEvent {
|
||||||
@@ -88,7 +102,14 @@ export interface GateResult {
|
|||||||
type: string;
|
type: string;
|
||||||
output: string;
|
output: string;
|
||||||
timed_out: boolean;
|
timed_out: boolean;
|
||||||
|
/** Back-compat boolean view — true ONLY when `status === 'passed'`. */
|
||||||
passed: boolean;
|
passed: boolean;
|
||||||
|
/** Typed discriminator — the authoritative gate outcome (RI-N2). */
|
||||||
|
status: GateStatus;
|
||||||
|
/** Typed capability error code, set when `status === 'capability_failure'`. */
|
||||||
|
capability_code?: MacpErrorCode;
|
||||||
|
/** Why a non-executed state (simulated/waiting/capability_failure) was reached. */
|
||||||
|
reason?: string;
|
||||||
fail_on?: string;
|
fail_on?: string;
|
||||||
blockers?: number;
|
blockers?: number;
|
||||||
findings?: number;
|
findings?: number;
|
||||||
@@ -96,6 +117,22 @@ export interface GateResult {
|
|||||||
parse_error?: string;
|
parse_error?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Aggregate outcome of `runGates` (RI-N2).
|
||||||
|
*
|
||||||
|
* `state` is the typed aggregate: it is `passed` only when every gate really
|
||||||
|
* executed green. A `simulated` result makes the aggregate `simulated` (never
|
||||||
|
* `passed`); a `waiting` manual gate keeps the aggregate `waiting`; a missing
|
||||||
|
* capability makes it `capability_failure`. `allPassed` is exactly
|
||||||
|
* `state === 'passed'`, so a simulated or waiting result can never satisfy a
|
||||||
|
* dependency, acceptance criterion, gate, merge, or release check.
|
||||||
|
*/
|
||||||
|
export interface RunGatesResult {
|
||||||
|
allPassed: boolean;
|
||||||
|
gateResults: GateResult[];
|
||||||
|
state: GateStatus;
|
||||||
|
}
|
||||||
|
|
||||||
/** Result from a completed task. */
|
/** Result from a completed task. */
|
||||||
export interface TaskResult {
|
export interface TaskResult {
|
||||||
task_id: string;
|
task_id: string;
|
||||||
|
|||||||
@@ -13,7 +13,8 @@ Pi is the native Mosaic agent runtime. The `mosaic pi` launcher:
|
|||||||
|
|
||||||
1. Injects the full runtime contract via `--append-system-prompt`
|
1. Injects the full runtime contract via `--append-system-prompt`
|
||||||
2. Loads Mosaic skills via `--skill` flags
|
2. Loads Mosaic skills via `--skill` flags
|
||||||
3. Loads the Mosaic extension via `--extension` for lifecycle hooks
|
3. Loads framework-owned `mosaic-extension.ts` and `goal-extension.ts` from
|
||||||
|
`~/.config/mosaic/runtime/pi/` via ordered `--extension` flags
|
||||||
4. Detects active missions and injects initial prompts
|
4. Detects active missions and injects initial prompts
|
||||||
|
|
||||||
## Capabilities vs Other Runtimes
|
## Capabilities vs Other Runtimes
|
||||||
@@ -22,6 +23,7 @@ Pi is the native Mosaic agent runtime. The `mosaic pi` launcher:
|
|||||||
- Native thinking levels replace sequential-thinking MCP
|
- Native thinking levels replace sequential-thinking MCP
|
||||||
- Native skill discovery compatible with Mosaic SKILL.md format
|
- Native skill discovery compatible with Mosaic SKILL.md format
|
||||||
- Native extension system for lifecycle hooks (TypeScript, not bash shims)
|
- Native extension system for lifecycle hooks (TypeScript, not bash shims)
|
||||||
|
- Bounded persistent `/goal` loop with per-turn, post-compaction, and two-pass evidence checks
|
||||||
- Native session persistence and resume
|
- Native session persistence and resume
|
||||||
- Model-agnostic (Anthropic, OpenAI, Google, Ollama, custom providers)
|
- Model-agnostic (Anthropic, OpenAI, Google, Ollama, custom providers)
|
||||||
|
|
||||||
|
|||||||
@@ -43,6 +43,8 @@ overwritten on upgrade. (Layer model: `constitution/LAYER-MODEL.md`.)
|
|||||||
| Secrets / vault usage | `guides/VAULT-SECRETS.md` |
|
| Secrets / vault usage | `guides/VAULT-SECRETS.md` |
|
||||||
| Tool/credential reference (service CLIs, wrappers) | `guides/TOOLS-REFERENCE.md` |
|
| Tool/credential reference (service CLIs, wrappers) | `guides/TOOLS-REFERENCE.md` |
|
||||||
| Memory protocol (OpenBrain capture/recall) | `guides/MEMORY.md` |
|
| Memory protocol (OpenBrain capture/recall) | `guides/MEMORY.md` |
|
||||||
|
| Seat identity, git credentials, token slots | `guides/SEAT-IDENTITY.md` |
|
||||||
|
| Reaching another agent (fleet comms) | `guides/FLEET-COMMS.md` |
|
||||||
|
|
||||||
## Subagent Model Selection (Cost — Hard Rule)
|
## Subagent Model Selection (Cost — Hard Rule)
|
||||||
|
|
||||||
@@ -82,6 +84,7 @@ is re-seeded a genuinely missing core file is a stop-and-report condition — no
|
|||||||
|
|
||||||
Confirm: required + situational tests passed (primary gate); aligned to `docs/PRD.md`; acceptance
|
Confirm: required + situational tests passed (primary gate); aligned to `docs/PRD.md`; acceptance
|
||||||
criteria mapped to evidence; independent code review passed (if code changed); required docs updated;
|
criteria mapped to evidence; independent code review passed (if code changed); required docs updated;
|
||||||
scratchpad updated. For PR-workflow delivery: merged PR number + merge commit on `main`, terminal-green
|
scratchpad updated. For PR-workflow delivery: merged PR number + merge commit on the integration
|
||||||
|
trunk (the project's declared trunk, default `main` — see `CONSTITUTION.md` Hard Gates), terminal-green
|
||||||
CI, linked issue closed (or `docs/TASKS.md` equivalent). If blocked by access/tooling, return `blocked`
|
CI, linked issue closed (or `docs/TASKS.md` equivalent). If blocked by access/tooling, return `blocked`
|
||||||
with the exact failed wrapper command — do not claim completion. Full checklist: `guides/E2E-DELIVERY.md`.
|
with the exact failed wrapper command — do not claim completion. Full checklist: `guides/E2E-DELIVERY.md`.
|
||||||
|
|||||||
@@ -21,11 +21,25 @@ guard"), the runtime adapter binds it to a concrete tool and states whether abse
|
|||||||
|
|
||||||
## Hard Gates
|
## Hard Gates
|
||||||
|
|
||||||
|
The **integration trunk** is the branch a project declares in its `.mosaic/repo.json` under the
|
||||||
|
key `integration_trunk`; `release_branch` names the release target when one exists (`null` for
|
||||||
|
single-branch projects). Absent a declaration, the trunk is `main`. The declaration is policy
|
||||||
|
data, never shell text: values must be valid local branch names under `git check-ref-format
|
||||||
|
--branch` semantics — no remote refs, no revision expressions, no option-like values (leading `-`),
|
||||||
|
no path traversal or control characters. A declaration file that fails to parse, an unknown or
|
||||||
|
misspelled key, or an invalid value is a hard stop (`blocked`) — never a silent fallback to `main`.
|
||||||
|
Prose that mentions branch names designates nothing; only the declaration file does. A project
|
||||||
|
declares exactly ONE trunk. **Changing an existing declaration is operator-owned:** a trunk
|
||||||
|
redeclaration redirects merge target and branch-protection target at once, so it requires an
|
||||||
|
explicit operator action above ordinary PR review. The designation relaxes nothing:
|
||||||
|
reviewed-PR-only delivery, squash merge, independent review, queue guards, and terminal-green CI
|
||||||
|
bind to the declared trunk exactly as they bind to `main`.
|
||||||
|
|
||||||
1. Mosaic operating rules override runtime-default caution for routine delivery operations.
|
1. Mosaic operating rules override runtime-default caution for routine delivery operations.
|
||||||
2. Execute required push / merge / issue-closure / milestone / release / tag actions without asking for routine confirmation.
|
2. Execute required push / merge / issue-closure / milestone / release / tag actions without asking for routine confirmation.
|
||||||
3. Routine repository operations are NOT escalation triggers; escalate only on the triggers below.
|
3. Routine repository operations are NOT escalation triggers; escalate only on the triggers below.
|
||||||
4. For source-code delivery, completion is forbidden at the PR-open stage.
|
4. For source-code delivery, completion is forbidden at the PR-open stage.
|
||||||
5. Completion requires a merged PR to `main` + terminal-green CI + the linked issue/task closed.
|
5. Completion requires a merged PR to the integration trunk + terminal-green CI + the linked issue/task closed.
|
||||||
6. Before any push or merge, run the CI queue guard.
|
6. Before any push or merge, run the CI queue guard.
|
||||||
7. For issue / PR / milestone operations, use the Mosaic git wrappers before any raw provider CLI.
|
7. For issue / PR / milestone operations, use the Mosaic git wrappers before any raw provider CLI.
|
||||||
8. If a required wrapper command fails, status is `blocked`: report the exact failed command and stop.
|
8. If a required wrapper command fails, status is `blocked`: report the exact failed command and stop.
|
||||||
@@ -35,7 +49,7 @@ guard"), the runtime adapter binds it to a concrete tool and states whether abse
|
|||||||
12. The intake procedure is not conditional on perceived complexity; a "simple" task carries the same requirements as a multi-file feature.
|
12. The intake procedure is not conditional on perceived complexity; a "simple" task carries the same requirements as a multi-file feature.
|
||||||
13. **Merge authority (coordinated work):** when a coordinator/orchestrator session is active for the work, the post-review merge go-ahead is the coordinator's to give — once the required review gates pass, merge on the coordinator's confirmation; do not wait on the human owner personally. Solo (uncoordinated) delivery keeps the default: merge per gates 2 and 9. A "No self-merge" note on a PR means no UNREVIEWED self-merge — it does not suspend coordinator-authorized merges.
|
13. **Merge authority (coordinated work):** when a coordinator/orchestrator session is active for the work, the post-review merge go-ahead is the coordinator's to give — once the required review gates pass, merge on the coordinator's confirmation; do not wait on the human owner personally. Solo (uncoordinated) delivery keeps the default: merge per gates 2 and 9. A "No self-merge" note on a PR means no UNREVIEWED self-merge — it does not suspend coordinator-authorized merges.
|
||||||
14. Never hardcode secrets; never emit credential values in any output (not even partially, not "to confirm").
|
14. Never hardcode secrets; never emit credential values in any output (not even partially, not "to confirm").
|
||||||
15. Trunk-based git only: branch from `main`, merge via a reviewed PR (squash), never push directly to `main`.
|
15. Trunk-based git only: branch from the integration trunk, merge via a reviewed PR (squash), never push directly to the trunk.
|
||||||
16. If you modify source code, an independent review (author ≠ reviewer) must pass before completion.
|
16. If you modify source code, an independent review (author ≠ reviewer) must pass before completion.
|
||||||
|
|
||||||
## Integrity (quality gates are never bypassed)
|
## Integrity (quality gates are never bypassed)
|
||||||
|
|||||||
@@ -104,7 +104,14 @@ The launcher:
|
|||||||
1. Verifies `~/.config/mosaic` exists
|
1. Verifies `~/.config/mosaic` exists
|
||||||
2. Verifies `SOUL.md` exists (auto-runs `mosaic init` if missing)
|
2. Verifies `SOUL.md` exists (auto-runs `mosaic init` if missing)
|
||||||
3. Injects `AGENTS.md` into the runtime
|
3. Injects `AGENTS.md` into the runtime
|
||||||
4. Forwards all arguments to the runtime CLI
|
4. For Pi, loads the framework-owned core and persistent-goal extensions from
|
||||||
|
`~/.config/mosaic/runtime/pi/`
|
||||||
|
5. Forwards all arguments to the runtime CLI
|
||||||
|
|
||||||
|
Inside `mosaic pi`, `/goal set <statement>` starts a bounded persistent goal loop. Use `/goal status`,
|
||||||
|
`/goal pause`, `/goal resume`, or `/goal cancel` to control it. The extension remains part of Mosaic
|
||||||
|
under `~/.config/mosaic/runtime/pi/goal-extension.ts`; it is not installed in Pi's main extension
|
||||||
|
directory.
|
||||||
|
|
||||||
You can still launch runtimes directly (`claude`, `codex`, etc.) — thin runtime adapters will tell the agent to read `~/.config/mosaic/AGENTS.md`.
|
You can still launch runtimes directly (`claude`, `codex`, etc.) — thin runtime adapters will tell the agent to read `~/.config/mosaic/AGENTS.md`.
|
||||||
|
|
||||||
@@ -124,9 +131,9 @@ You can still launch runtimes directly (`claude`, `codex`, etc.) — thin runtim
|
|||||||
│ ├── claude/ ← CLAUDE.md, RUNTIME.md, settings.json, hooks
|
│ ├── claude/ ← CLAUDE.md, RUNTIME.md, settings.json, hooks
|
||||||
│ ├── codex/ ← instructions.md, RUNTIME.md
|
│ ├── codex/ ← instructions.md, RUNTIME.md
|
||||||
│ ├── opencode/ ← AGENTS.md, RUNTIME.md
|
│ ├── opencode/ ← AGENTS.md, RUNTIME.md
|
||||||
│ ├── pi/ ← RUNTIME.md, mosaic-extension.ts
|
│ ├── pi/ ← RUNTIME.md, mosaic-extension.ts, goal-extension.ts
|
||||||
│ └── mcp/ ← MCP server configs
|
│ └── mcp/ ← MCP server configs
|
||||||
├── skills/ ← Universal skills (synced from mosaic/agent-skills)
|
├── skills/ ← Universal skills (shipped with the framework package)
|
||||||
├── skills-local/ ← Local cross-runtime skills
|
├── skills-local/ ← Local cross-runtime skills
|
||||||
├── memory/ ← Persistent agent memory (preserved across upgrades)
|
├── memory/ ← Persistent agent memory (preserved across upgrades)
|
||||||
└── templates/ ← SOUL.md template, project templates
|
└── templates/ ← SOUL.md template, project templates
|
||||||
@@ -136,7 +143,7 @@ You can still launch runtimes directly (`claude`, `codex`, etc.) — thin runtim
|
|||||||
|
|
||||||
| Launch method | Injection mechanism |
|
| Launch method | Injection mechanism |
|
||||||
| ------------------- | ----------------------------------------------------------------------------------------- |
|
| ------------------- | ----------------------------------------------------------------------------------------- |
|
||||||
| `mosaic pi` | `--append-system-prompt` with composed runtime contract + skills + extension |
|
| `mosaic pi` | `--append-system-prompt` with composed runtime contract + skills + Mosaic extensions |
|
||||||
| `mosaic claude` | `--append-system-prompt` with composed runtime contract (`AGENTS.md` + runtime reference) |
|
| `mosaic claude` | `--append-system-prompt` with composed runtime contract (`AGENTS.md` + runtime reference) |
|
||||||
| `mosaic codex` | Writes composed runtime contract to `~/.codex/instructions.md` before launch |
|
| `mosaic codex` | Writes composed runtime contract to `~/.codex/instructions.md` before launch |
|
||||||
| `mosaic opencode` | Writes composed runtime contract to `~/.config/opencode/AGENTS.md` before launch |
|
| `mosaic opencode` | Writes composed runtime contract to `~/.config/opencode/AGENTS.md` before launch |
|
||||||
@@ -193,11 +200,11 @@ The installer rejects unrecognized flags or positional arguments before making c
|
|||||||
|
|
||||||
## Universal Skills
|
## Universal Skills
|
||||||
|
|
||||||
The installer syncs skills from `mosaic/agent-skills` into `~/.config/mosaic/skills/`. Install, wizard finalization, and `mosaic update` automatically reconcile every canonical skill into Claude Code's `~/.claude/skills/` directory.
|
Canonical skills ship inside the framework package itself; the installer installs them into `~/.config/mosaic/skills/` together with the rest of the framework (there is no separate skills repository). Install, wizard finalization, and `mosaic update` automatically link every canonical skill into Claude Code's `~/.claude/skills/` directory.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
mosaic sync # Full canonical catalog sync
|
mosaic sync # Relink the full canonical catalog
|
||||||
~/.config/mosaic/tools/_scripts/mosaic-sync-skills --link-only # Re-link only
|
~/.config/mosaic/tools/_scripts/mosaic-sync-skills --link-only # Re-link only (same as default)
|
||||||
mosaic skill list # Show registered, missing, dangling, and foreign entries
|
mosaic skill list # Show registered, missing, dangling, and foreign entries
|
||||||
mosaic skill register <name> # Register or repair one canonical Claude link
|
mosaic skill register <name> # Register or repair one canonical Claude link
|
||||||
mosaic skill unregister <name> # Remove one Mosaic-owned Claude link
|
mosaic skill unregister <name> # Remove one Mosaic-owned Claude link
|
||||||
|
|||||||
@@ -60,6 +60,52 @@ If a repo does not expose these scripts, run equivalent local workflow commands
|
|||||||
- Do not auto-resolve data conflicts in shared state files.
|
- Do not auto-resolve data conflicts in shared state files.
|
||||||
- Keep commits scoped to a single logical change set.
|
- Keep commits scoped to a single logical change set.
|
||||||
|
|
||||||
|
## Model Tiering
|
||||||
|
|
||||||
|
Model choice is a standard, not a preference. Delegating a mechanical grep to a
|
||||||
|
frontier reasoning model wastes budget; sending a security review to a cheap tier
|
||||||
|
produces a review that passes and proves nothing. Both are defects.
|
||||||
|
|
||||||
|
Tiers are named by **capability class**, so the standard survives a model
|
||||||
|
generation. An operator binds each class to a concrete model id.
|
||||||
|
|
||||||
|
| Class | Use for |
|
||||||
|
| ------------- | ----------------------------------------------------------------------------------------- |
|
||||||
|
| `search` | grep/glob, file location, status and health checks, one-line mechanical edits |
|
||||||
|
| `build` | feature implementation, test writing, bugfixes, routine refactors |
|
||||||
|
| `judge` | code review, planning, API/compat-sensitive changes |
|
||||||
|
| `adversarial` | security review, ambiguous architecture, anything where a wrong "looks fine" is expensive |
|
||||||
|
|
||||||
|
Rules:
|
||||||
|
|
||||||
|
1. **Start at the cheapest class that can do the task; escalate on evidence, not
|
||||||
|
on nerves.** Omitting a tier is not neutral — it inherits the caller's model,
|
||||||
|
which is usually the most expensive one.
|
||||||
|
2. **Compat-sensitive work escalates one class.** A change that must interoperate
|
||||||
|
with an existing contract is judged, not just built.
|
||||||
|
3. **A tier assignment is benchmarked, not asserted.** Move a task class to a
|
||||||
|
cheaper tier only against a blind A/B on real work from this codebase, ranked
|
||||||
|
by someone other than the author. "It seemed fine" is not evidence.
|
||||||
|
4. **Reviewer independence beats reviewer size.** An `adversarial` verdict from
|
||||||
|
the model that wrote the code is not a second opinion (see Constitution gate 16).
|
||||||
|
|
||||||
|
### Where the binding lives
|
||||||
|
|
||||||
|
The class→model map is operator configuration, never framework source: model
|
||||||
|
availability, cost, and quotas differ per operator and per host.
|
||||||
|
|
||||||
|
Resolution order, first hit wins:
|
||||||
|
|
||||||
|
1. the config service (DB-backed, surfaced and editable in the Mosaic webUI)
|
||||||
|
2. a local operator file (`STANDARDS.local.md`, or `policy/` where the runtime
|
||||||
|
injects it)
|
||||||
|
3. the framework default — the class names above, with no binding
|
||||||
|
|
||||||
|
Only layer 1 is auditable across a fleet, so it is the target end state; layers 2
|
||||||
|
and 3 exist so a host with no config service still runs. A local override that
|
||||||
|
silently disagrees with the config service is drift — the same failure class the
|
||||||
|
tool-index gate exists to catch, and it belongs in `mosaic doctor`.
|
||||||
|
|
||||||
## Prompting Contract
|
## Prompting Contract
|
||||||
|
|
||||||
All runtime adapters should inject:
|
All runtime adapters should inject:
|
||||||
|
|||||||
@@ -35,4 +35,4 @@ A standing panel of senior voices, each arguing from a fixed vantage. The board
|
|||||||
deliberately slow and adversarial — its value is catching the expensive mistake
|
deliberately slow and adversarial — its value is catching the expensive mistake
|
||||||
before a single agent-hour is spent on it.
|
before a single agent-hour is spent on it.
|
||||||
|
|
||||||
> Doctrine: `docs/fleet/north-star.md` ('board' role = forge BOD; role library).
|
> Doctrine: `docs/fleet/FLEET-DOCTRINE.md` ('board' role = forge BOD; role library).
|
||||||
|
|||||||
@@ -33,4 +33,4 @@ The code role writes the change and opens the PR; it never touches the merge pat
|
|||||||
The focused builder. It takes one well-scoped card, drives it to green, opens a
|
The focused builder. It takes one well-scoped card, drives it to green, opens a
|
||||||
clean PR, and hands off — never reaching past the card it was given.
|
clean PR, and hands off — never reaching past the card it was given.
|
||||||
|
|
||||||
> Doctrine: `docs/fleet/north-star.md` (role library).
|
> Doctrine: `docs/fleet/FLEET-DOCTRINE.md` (role library).
|
||||||
|
|||||||
@@ -35,4 +35,4 @@ The work-breakdown specialist. It takes a phased plan and a DAG and emits a clea
|
|||||||
linked set of single-PR cards on the Mosaic backlog — then steps back and lets the
|
linked set of single-PR cards on the Mosaic backlog — then steps back and lets the
|
||||||
executors run.
|
executors run.
|
||||||
|
|
||||||
> Doctrine: `docs/fleet/north-star.md` (role library); spend accounting is a process mandate.
|
> Doctrine: `docs/fleet/FLEET-DOCTRINE.md` (role library); spend accounting is a process mandate.
|
||||||
|
|||||||
@@ -36,4 +36,4 @@ The scribe of record. It makes sure the docs and the north star's projections
|
|||||||
describe the system as it actually is, and it never lets two writers fight over one
|
describe the system as it actually is, and it never lets two writers fight over one
|
||||||
TASKS file.
|
TASKS file.
|
||||||
|
|
||||||
> Doctrine: `docs/fleet/north-star.md` (role library).
|
> Doctrine: `docs/fleet/FLEET-DOCTRINE.md` (role library).
|
||||||
|
|||||||
@@ -38,4 +38,4 @@ The orchestrator alone optimizes for _this_ delivery; the enhancer optimizes for
|
|||||||
delivery — self-healing the fleet's tools, skills, and harnesses, and routing real defects
|
delivery — self-healing the fleet's tools, skills, and harnesses, and routing real defects
|
||||||
upstream. Together they are the irreducible core; every other role is added on demand.
|
upstream. Together they are the irreducible core; every other role is added on demand.
|
||||||
|
|
||||||
> Doctrine: `docs/fleet/north-star.md` (two-agent floor + role library).
|
> Doctrine: `docs/fleet/FLEET-DOCTRINE.md` (two-agent floor + role library).
|
||||||
|
|||||||
@@ -46,4 +46,4 @@ The single, accountable gatekeeper. It waits for green CI (`pr-ci-wait.sh`),
|
|||||||
respects the pause switch, merges only through `pr-merge.sh`, and records every
|
respects the pause switch, merges only through `pr-merge.sh`, and records every
|
||||||
decision — so the fleet has exactly one trustworthy door to production.
|
decision — so the fleet has exactly one trustworthy door to production.
|
||||||
|
|
||||||
> Doctrine: `docs/fleet/north-star.md` (role library); merge path: `pr-merge.sh` + `pr-ci-wait.sh`; forbidden paths: `pr-merge.sh` guard.
|
> Doctrine: `docs/fleet/FLEET-DOCTRINE.md` (role library); merge path: `pr-merge.sh` + `pr-ci-wait.sh`; forbidden paths: `pr-merge.sh` guard.
|
||||||
|
|||||||
@@ -35,4 +35,4 @@ The on-call dispatcher. It makes sure every escalation is seen and re-seen until
|
|||||||
handled, and it holds the one switch that can stop the fleet when something is
|
handled, and it holds the one switch that can stop the fleet when something is
|
||||||
wrong.
|
wrong.
|
||||||
|
|
||||||
> Doctrine: `docs/fleet/north-star.md` (role library); pause switch: `fleet/run/PAUSED`.
|
> Doctrine: `docs/fleet/FLEET-DOCTRINE.md` (role library); pause switch: `fleet/run/PAUSED`.
|
||||||
|
|||||||
@@ -43,4 +43,4 @@ A lean, decisive coordinator. It thinks in readiness and throughput, dispatches
|
|||||||
next ready card the instant a dependency clears, and never lets an idle agent sit
|
next ready card the instant a dependency clears, and never lets an idle agent sit
|
||||||
while ready work exists — keeping its own context minimal so the loop never slows.
|
while ready work exists — keeping its own context minimal so the loop never slows.
|
||||||
|
|
||||||
> Doctrine: `docs/fleet/north-star.md` (two-agent floor + role library).
|
> Doctrine: `docs/fleet/FLEET-DOCTRINE.md` (two-agent floor + role library).
|
||||||
|
|||||||
@@ -38,4 +38,4 @@ The architect of the mission's shape. It thinks in phases and dependencies, hand
|
|||||||
a clean DAG to decomposition, and reports its plan back to the orchestrator that
|
a clean DAG to decomposition, and reports its plan back to the orchestrator that
|
||||||
dispatched it.
|
dispatched it.
|
||||||
|
|
||||||
> Doctrine: `docs/fleet/north-star.md` (two-agent floor + role library).
|
> Doctrine: `docs/fleet/FLEET-DOCTRINE.md` (two-agent floor + role library).
|
||||||
|
|||||||
@@ -34,4 +34,4 @@ The rebase role keeps PR branches fresh; it never approves or merges.
|
|||||||
The janitor of the merge queue. It quietly keeps branches current and re-runnable,
|
The janitor of the merge queue. It quietly keeps branches current and re-runnable,
|
||||||
and knows when a conflict is beyond a mechanical rebase and must be escalated.
|
and knows when a conflict is beyond a mechanical rebase and must be escalated.
|
||||||
|
|
||||||
> Doctrine: `docs/fleet/north-star.md` (role library).
|
> Doctrine: `docs/fleet/FLEET-DOCTRINE.md` (role library).
|
||||||
|
|||||||
@@ -35,4 +35,4 @@ The careful reader. It assumes nothing, checks the change against its card and i
|
|||||||
tests, and is willing to say "not yet" — its value is catching the wrong change
|
tests, and is willing to say "not yet" — its value is catching the wrong change
|
||||||
before it reaches the merge-gate.
|
before it reaches the merge-gate.
|
||||||
|
|
||||||
> Doctrine: `docs/fleet/north-star.md` (role library).
|
> Doctrine: `docs/fleet/FLEET-DOCTRINE.md` (role library).
|
||||||
|
|||||||
@@ -36,4 +36,4 @@ tree or the merge path.
|
|||||||
The adversary on your side. It reads every diff asking "how does this get exploited
|
The adversary on your side. It reads every diff asking "how does this get exploited
|
||||||
or leak?" — the second, security-focused pair of eyes before the merge-gate.
|
or leak?" — the second, security-focused pair of eyes before the merge-gate.
|
||||||
|
|
||||||
> Doctrine: `docs/fleet/north-star.md` (role library); forbidden paths: `pr-merge.sh` guard.
|
> Doctrine: `docs/fleet/FLEET-DOCTRINE.md` (role library); forbidden paths: `pr-merge.sh` guard.
|
||||||
|
|||||||
@@ -34,4 +34,4 @@ The retrospective analyst. It reads completed sessions and distills them into cl
|
|||||||
actionable signals — the raw material the enhancer uses to make the fleet better
|
actionable signals — the raw material the enhancer uses to make the fleet better
|
||||||
next time.
|
next time.
|
||||||
|
|
||||||
> Doctrine: `docs/fleet/north-star.md` (role library); consumed by the enhancer role.
|
> Doctrine: `docs/fleet/FLEET-DOCTRINE.md` (role library); consumed by the enhancer role.
|
||||||
|
|||||||
@@ -34,4 +34,4 @@ merge path.
|
|||||||
The skeptic who insists on running it. It trusts observed behavior over claimed
|
The skeptic who insists on running it. It trusts observed behavior over claimed
|
||||||
behavior, and turns "should work" into "verified works" — or a concrete bug report.
|
behavior, and turns "should work" into "verified works" — or a concrete bug report.
|
||||||
|
|
||||||
> Doctrine: `docs/fleet/north-star.md` (role library).
|
> Doctrine: `docs/fleet/FLEET-DOCTRINE.md` (role library).
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ This guide covers how to bootstrap a project so AI agents (Claude, Codex, etc.)
|
|||||||
4. Issue tracking is consistent across projects
|
4. Issue tracking is consistent across projects
|
||||||
5. Documentation standards and API contracts are enforced from day one
|
5. Documentation standards and API contracts are enforced from day one
|
||||||
6. PRD requirements are established before coding begins
|
6. PRD requirements are established before coding begins
|
||||||
7. Branching/merging is consistent: `branch -> main` via PR with squash-only merges
|
7. Branching/merging is consistent: branch -> integration trunk (default `main`) via PR with squash-only merges
|
||||||
8. Steered-autonomy execution is enabled so agents can run end-to-end with escalation-only human intervention
|
8. Steered-autonomy execution is enabled so agents can run end-to-end with escalation-only human intervention
|
||||||
|
|
||||||
## Agent Host Prerequisites
|
## Agent Host Prerequisites
|
||||||
@@ -206,7 +206,7 @@ Every runtime context file should contain:
|
|||||||
6. **Issue tracking** — Issue and commit conventions
|
6. **Issue tracking** — Issue and commit conventions
|
||||||
7. **Code review** — Required review process
|
7. **Code review** — Required review process
|
||||||
8. **Runtime notes** — Runtime-specific behavior references
|
8. **Runtime notes** — Runtime-specific behavior references
|
||||||
9. **Branch and merge policy** — Trunk workflow (`branch -> main` via PR, squash-only)
|
9. **Branch and merge policy** — Trunk workflow (branch -> integration trunk via PR, squash-only)
|
||||||
10. **Autonomy and escalation policy** — Agent owns coding/review/PR/release/deploy lifecycle
|
10. **Autonomy and escalation policy** — Agent owns coding/review/PR/release/deploy lifecycle
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -288,15 +288,17 @@ Reserve `0.1.0` for the MVP release milestone.
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Step 5b: Configure Main Branch Protection (Hard Rule)
|
## Step 5b: Configure Trunk Branch Protection (Hard Rule)
|
||||||
|
|
||||||
Apply equivalent settings in Gitea, GitHub, or GitLab:
|
Apply equivalent settings in Gitea, GitHub, or GitLab, targeting the project's integration trunk
|
||||||
|
(the branch its `.mosaic/repo.json` declares under `integration_trunk`; default `main` — see
|
||||||
|
`CONSTITUTION.md` Hard Gates):
|
||||||
|
|
||||||
1. Protect `main` from direct pushes.
|
1. Protect the integration trunk from direct pushes.
|
||||||
2. Require pull requests to merge into `main`.
|
2. Require pull requests to merge into the integration trunk.
|
||||||
3. Require required CI/status checks to pass before merge.
|
3. Require required CI/status checks to pass before merge.
|
||||||
4. Require code review approval before merge.
|
4. Require code review approval before merge.
|
||||||
5. Allow **squash merge only** for PRs into `main` (disable merge commits and rebase merges for `main`).
|
5. Allow **squash merge only** for PRs into the integration trunk (disable merge commits and rebase merges for it).
|
||||||
|
|
||||||
This enforces one merge strategy across human and agent workflows.
|
This enforces one merge strategy across human and agent workflows.
|
||||||
|
|
||||||
@@ -513,9 +515,9 @@ After bootstrapping, verify:
|
|||||||
- [ ] Git labels created (epic, feature, bug, task, etc.)
|
- [ ] Git labels created (epic, feature, bug, task, etc.)
|
||||||
- [ ] Initial pre-MVP milestone created (0.0.1)
|
- [ ] Initial pre-MVP milestone created (0.0.1)
|
||||||
- [ ] MVP milestone reserved for release (0.1.0)
|
- [ ] MVP milestone reserved for release (0.1.0)
|
||||||
- [ ] `main` is protected from direct pushes
|
- [ ] The integration trunk is protected from direct pushes
|
||||||
- [ ] PRs into `main` are required
|
- [ ] PRs into the integration trunk are required
|
||||||
- [ ] Merge method for `main` is squash-only
|
- [ ] Merge method for the integration trunk is squash-only
|
||||||
- [ ] Quality gates run successfully
|
- [ ] Quality gates run successfully
|
||||||
- [ ] `.env.example` exists (if project uses env vars)
|
- [ ] `.env.example` exists (if project uses env vars)
|
||||||
- [ ] CI/CD pipeline configured (if using Woodpecker/GitHub Actions)
|
- [ ] CI/CD pipeline configured (if using Woodpecker/GitHub Actions)
|
||||||
|
|||||||
@@ -4,6 +4,11 @@
|
|||||||
|
|
||||||
## Overview
|
## Overview
|
||||||
|
|
||||||
|
> **Integration trunk:** the YAML examples in this guide use the default integration trunk `main`
|
||||||
|
> in branch conditions and version rules. A project that declares a different trunk in its
|
||||||
|
> `.mosaic/repo.json` under `integration_trunk` (see `CONSTITUTION.md` Hard Gates) substitutes its
|
||||||
|
> declared trunk wherever `main` appears as the trunk branch.
|
||||||
|
|
||||||
This guide covers the canonical CI/CD pattern used across projects. The pipeline runs in Woodpecker CI and follows this flow:
|
This guide covers the canonical CI/CD pattern used across projects. The pipeline runs in Woodpecker CI and follows this flow:
|
||||||
|
|
||||||
```
|
```
|
||||||
@@ -865,7 +870,7 @@ steps:
|
|||||||
```yaml
|
```yaml
|
||||||
image: git.example.com/org/service@${IMAGE_DIGEST}
|
image: git.example.com/org/service@${IMAGE_DIGEST}
|
||||||
```
|
```
|
||||||
7. **Test on a short-lived non-main branch first** — open a PR and verify quality gates before merging to `main`
|
7. **Test on a short-lived non-trunk branch first** — open a PR and verify quality gates before merging to the integration trunk
|
||||||
8. **Verify images appear** in Gitea Packages tab after successful pipeline
|
8. **Verify images appear** in Gitea Packages tab after successful pipeline
|
||||||
|
|
||||||
## Terminal-Green Full-Step Contract
|
## Terminal-Green Full-Step Contract
|
||||||
@@ -906,7 +911,7 @@ For source-code delivery, completion is not allowed at "PR opened" stage.
|
|||||||
|
|
||||||
Required sequence:
|
Required sequence:
|
||||||
|
|
||||||
1. Merge PR to `main` (squash) via Mosaic wrapper.
|
1. Merge PR to the integration trunk (squash) via Mosaic wrapper.
|
||||||
2. Monitor CI to terminal status:
|
2. Monitor CI to terminal status:
|
||||||
```bash
|
```bash
|
||||||
~/.config/mosaic/tools/git/pr-ci-wait.sh -n <PR_NUMBER>
|
~/.config/mosaic/tools/git/pr-ci-wait.sh -n <PR_NUMBER>
|
||||||
@@ -1112,5 +1117,5 @@ If a project currently uses Verdaccio (e.g., U-Connect at `npm.uscllc.net`), fol
|
|||||||
|
|
||||||
### Pipeline runs Docker builds on pull requests
|
### Pipeline runs Docker builds on pull requests
|
||||||
|
|
||||||
- Verify `when` clause on Docker build steps restricts to `branch: [main]`
|
- Verify `when` clause on Docker build steps restricts to the integration trunk (`branch: [main]` by default)
|
||||||
- Pull requests should only run quality gates, not build/push images
|
- Pull requests should only run quality gates, not build/push images
|
||||||
|
|||||||
@@ -10,13 +10,97 @@ If implementation diverges from `docs/PRD.md` or `docs/PRD.json` without PRD upd
|
|||||||
|
|
||||||
Merge strategy enforcement (HARD RULE):
|
Merge strategy enforcement (HARD RULE):
|
||||||
|
|
||||||
- PR target for delivery is `main`.
|
- The integration trunk is the branch the project's `.mosaic/repo.json` declares under `integration_trunk` (default: `main`) — see `CONSTITUTION.md` Hard Gates.
|
||||||
- Direct pushes to `main` are prohibited.
|
- PR target for delivery is the integration trunk.
|
||||||
- Merge to `main` MUST be squash-only.
|
- Direct pushes to the integration trunk are prohibited.
|
||||||
|
- Merge to the integration trunk MUST be squash-only.
|
||||||
- Use `~/.config/mosaic/tools/git/pr-merge.sh -n {PR_NUMBER} -m squash --expect-head {approved_full_sha}` (or PowerShell equivalent).
|
- Use `~/.config/mosaic/tools/git/pr-merge.sh -n {PR_NUMBER} -m squash --expect-head {approved_full_sha}` (or PowerShell equivalent).
|
||||||
|
|
||||||
|
An estate MAY carry a documented exception for a repository whose gates are commit hooks rather
|
||||||
|
than review. Such an exception belongs in that estate's own working copy of this guide, is
|
||||||
|
scoped to the named repository, and is never precedent for a second one.
|
||||||
|
|
||||||
|
**Do not use `pr-review.sh` or `issue-comment.sh` to post a verdict** (mosaicstack#1280). Post
|
||||||
|
through a direct authenticated API call as your own seat, or hand the verdict to the requesting
|
||||||
|
seat. Handing it over is a legitimate delivery path, not a fallback.
|
||||||
|
|
||||||
|
## Evidence Discipline (applies to every finding)
|
||||||
|
|
||||||
|
The checklist below says what to look at. This section says when you are allowed to believe what
|
||||||
|
you saw. Every rule here was earned by a wrong conclusion that reached a report.
|
||||||
|
|
||||||
|
1. **A finding is a claim about behavior.** State the failing input, the path taken, and the
|
||||||
|
wrong result. "This looks fragile" is not a finding.
|
||||||
|
2. **A green check is not a result until you have shown it could go red.** Run the control. A
|
||||||
|
`0`, an empty result, or a column of identical values with no failing counterpart is a
|
||||||
|
non-result.
|
||||||
|
3. **Measurement and explanation are separate sentences.** Report the command and its output,
|
||||||
|
then, as its own sentence, what you think it means.
|
||||||
|
4. **Never widen the case you measured.** If you checked one path, the finding covers one path.
|
||||||
|
5. **Reproduce a reported failure before recording it, and say which tree you measured.** Two
|
||||||
|
correct measurements of two different trees disagree without either being wrong.
|
||||||
|
6. **Verify by content on the ref that ships**, never by ancestry of a local sha. A rebase mints
|
||||||
|
new shas; a commit being an ancestor of something local proves nothing about the remote.
|
||||||
|
Compare by digest against `origin/<branch>`.
|
||||||
|
7. **Confidence is part of the finding.** "I could not reproduce this" is a usable review
|
||||||
|
comment. A confident guess is not.
|
||||||
|
8. **Author is not reviewer** (Gate-16). Do not review your own work, or work you shaped closely
|
||||||
|
enough to be a co-author of. Say so and hand it back.
|
||||||
|
|
||||||
|
### Measuring a shell suite
|
||||||
|
|
||||||
|
Each of these produced a wrong conclusion before it was written down.
|
||||||
|
|
||||||
|
9. **`cmd | tail; echo rc=$?` reports `tail`'s exit code, not `cmd`'s.** It reads as a pass when
|
||||||
|
the command failed. Redirect to a file and check `rc` directly, or use `${PIPESTATUS[0]}`.
|
||||||
|
10. **Under `set -o pipefail`, a missed glob makes `ls` exit 2**, the pipeline inherits it, and
|
||||||
|
`set -e` kills the run. Iterate a glob with a `for` loop and an `-e` test instead of piping
|
||||||
|
`ls`.
|
||||||
|
11. **A suite that exits nonzero with ZERO output is an environment question, not a defect in
|
||||||
|
the code under review.** The usual cause is a sourced dependency that is absent, so `set -e`
|
||||||
|
kills the first case before anything prints. Extract whole tool trees — `tools/git` alone is
|
||||||
|
missing `tools/_lib/credentials.sh`. Isolate the variable and prove it by adding only that
|
||||||
|
back.
|
||||||
|
12. **`git -C <dir>` in a directory that is not itself a repo answers from the enclosing repo.**
|
||||||
|
A scratch tree under `~/.mosaic` reports `~/.mosaic`'s HEAD, not the PR's, and every
|
||||||
|
conclusion drawn from it describes the wrong tree. Confirm `git rev-parse --show-toplevel`
|
||||||
|
is the tree you think it is before trusting any git output.
|
||||||
|
|
||||||
|
13. **Run the repository's PINNED tool version.** `npx <tool>` resolves a local `node_modules`
|
||||||
|
install when one is present and fetches the latest release when one is not, so the same
|
||||||
|
command answers differently depending on where it ran. A reviewer measuring in a fresh clone
|
||||||
|
or a detached worktree — which is exactly where reviewers measure — has no `node_modules` and
|
||||||
|
silently gets the latest release instead of the pinned one. Measured on mosaicstack#1313: the
|
||||||
|
lockfile pins prettier 3.8.1, under which three guides pass; a version-less `npx` in a
|
||||||
|
worktree resolved 3.9.6, under which the same three fail; and 3.0.0, the floor of the declared
|
||||||
|
`^3.0.0` range, fails a different one. Three versions, three verdicts, identical bytes. Use
|
||||||
|
`node_modules/.bin/<tool>`, or name the version the lockfile pins.
|
||||||
|
14. **A formatter or linter declared as a range is a dated verdict, not a fact.** If a lockfile
|
||||||
|
pins it, the gate is reproducible today and will disagree with itself the day the pin moves.
|
||||||
|
Report a formatting failure with the version that produced it, always.
|
||||||
|
|
||||||
|
### Feedback Categories
|
||||||
|
|
||||||
|
- **Blocker**: must fix before merge (security, bugs, test failures)
|
||||||
|
- **Should Fix**: important but not blocking (code quality, minor issues)
|
||||||
|
- **Suggestion**: optional improvement (style preference, nice-to-have)
|
||||||
|
- **Question**: seeking clarification
|
||||||
|
|
||||||
## Review Checklist
|
## Review Checklist
|
||||||
|
|
||||||
|
Reviewer seats split this checklist by class rather than duplicating it. A seat reviews its own
|
||||||
|
sections in full and may raise anything it notices outside them as a Suggestion, never as a
|
||||||
|
Blocker on someone else's ground.
|
||||||
|
|
||||||
|
| Reviewer class | Owns |
|
||||||
|
| ---------------- | ------------------------------------------------------------------------------------------------------- |
|
||||||
|
| `rev-code-*` | 1 Correctness, 3 Testing, 4 Code Quality, 4a TypeScript, 5 Documentation, 6 Performance, 7 Dependencies |
|
||||||
|
| `rev-security-*` | 2 Security, 2a OWASP |
|
||||||
|
|
||||||
|
Where two seats of the same class review the same change, they review independently and compare
|
||||||
|
after. A second seat that reads the first seat's findings before measuring is a proofreader, not
|
||||||
|
a second opinion.
|
||||||
|
|
||||||
### 1. Correctness
|
### 1. Correctness
|
||||||
|
|
||||||
- [ ] Code does what the issue/PR description says
|
- [ ] Code does what the issue/PR description says
|
||||||
@@ -53,7 +137,7 @@ Merge strategy enforcement (HARD RULE):
|
|||||||
- [ ] Tests cover happy path AND error cases
|
- [ ] Tests cover happy path AND error cases
|
||||||
- [ ] Situational tests cover all impacted change surfaces (primary gate)
|
- [ ] Situational tests cover all impacted change surfaces (primary gate)
|
||||||
- [ ] Tests validate required behavior/outcomes, not only internal implementation details
|
- [ ] Tests validate required behavior/outcomes, not only internal implementation details
|
||||||
- [ ] TDD was applied when required by `~/.config/mosaic/guides/QA-TESTING.md`
|
- [ ] TDD was applied when required by `guides/QA-TESTING.md`
|
||||||
- [ ] Coverage meets 85% minimum
|
- [ ] Coverage meets 85% minimum
|
||||||
- [ ] Tests are readable and maintainable
|
- [ ] Tests are readable and maintainable
|
||||||
- [ ] No flaky tests introduced
|
- [ ] No flaky tests introduced
|
||||||
@@ -82,7 +166,7 @@ Merge strategy enforcement (HARD RULE):
|
|||||||
### 5. Documentation
|
### 5. Documentation
|
||||||
|
|
||||||
- [ ] Complex logic has explanatory comments
|
- [ ] Complex logic has explanatory comments
|
||||||
- [ ] Required docs updated per `~/.config/mosaic/guides/DOCUMENTATION.md`
|
- [ ] Required docs updated per `guides/DOCUMENTATION.md`
|
||||||
- [ ] Public APIs are documented
|
- [ ] Public APIs are documented
|
||||||
- [ ] Private/internal APIs are documented
|
- [ ] Private/internal APIs are documented
|
||||||
- [ ] API input/output schemas are documented
|
- [ ] API input/output schemas are documented
|
||||||
@@ -114,8 +198,8 @@ Use `~/.config/mosaic/templates/docs/DOCUMENTATION-CHECKLIST.md` whenever code/A
|
|||||||
# List the issue being addressed
|
# List the issue being addressed
|
||||||
~/.config/mosaic/tools/git/issue-list.sh -i {issue-number}
|
~/.config/mosaic/tools/git/issue-list.sh -i {issue-number}
|
||||||
|
|
||||||
# View the changes
|
# View the changes (diff against the integration trunk; default: main)
|
||||||
git diff main...HEAD
|
git diff {integration_trunk}...HEAD
|
||||||
```
|
```
|
||||||
|
|
||||||
### Providing Feedback
|
### Providing Feedback
|
||||||
@@ -126,13 +210,6 @@ git diff main...HEAD
|
|||||||
- Distinguish between blocking issues and suggestions
|
- Distinguish between blocking issues and suggestions
|
||||||
- Be constructive, not critical of the person
|
- Be constructive, not critical of the person
|
||||||
|
|
||||||
### Feedback Categories
|
|
||||||
|
|
||||||
- **Blocker**: Must fix before merge (security, bugs, test failures)
|
|
||||||
- **Should Fix**: Important but not blocking (code quality, minor issues)
|
|
||||||
- **Suggestion**: Optional improvements (style preferences, nice-to-haves)
|
|
||||||
- **Question**: Seeking clarification
|
|
||||||
|
|
||||||
### Review Comment Format
|
### Review Comment Format
|
||||||
|
|
||||||
```
|
```
|
||||||
@@ -151,4 +228,4 @@ This pattern appears in 3 places. A shared helper would reduce duplication.
|
|||||||
2. If changes requested, assign back to author
|
2. If changes requested, assign back to author
|
||||||
3. If approved, note approval in issue comments
|
3. If approved, note approval in issue comments
|
||||||
4. For merges, ensure CI passes first
|
4. For merges, ensure CI passes first
|
||||||
5. Merge PR to `main` with squash strategy only
|
5. Merge PR to the integration trunk with squash strategy only
|
||||||
|
|||||||
@@ -78,7 +78,7 @@ For implementation work, you MUST run this cycle in order:
|
|||||||
7. `commit` - commit only when the logical unit passes tests and review.
|
7. `commit` - commit only when the logical unit passes tests and review.
|
||||||
8. `pre-push queue guard` - before pushing, wait for running/queued project pipelines to clear: `~/.config/mosaic/tools/git/ci-queue-wait.sh --purpose push`.
|
8. `pre-push queue guard` - before pushing, wait for running/queued project pipelines to clear: `~/.config/mosaic/tools/git/ci-queue-wait.sh --purpose push`.
|
||||||
9. `push` - push immediately after queue guard passes.
|
9. `push` - push immediately after queue guard passes.
|
||||||
10. `PR integration` - if external git provider is available, create/update PR to `main` and merge with required strategy via Mosaic wrappers.
|
10. `PR integration` - if external git provider is available, create/update PR to the integration trunk (the project's declared trunk, default `main`) and merge with required strategy via Mosaic wrappers.
|
||||||
11. `pre-merge queue guard` - before merging PR, wait for running/queued project pipelines on the exact PR head to clear: `~/.config/mosaic/tools/git/ci-queue-wait.sh --purpose merge -B <PR_HEAD_BRANCH> -R <PR_HEAD_OWNER/REPO> --sha <PR_HEAD_FULL_SHA>`.
|
11. `pre-merge queue guard` - before merging PR, wait for running/queued project pipelines on the exact PR head to clear: `~/.config/mosaic/tools/git/ci-queue-wait.sh --purpose merge -B <PR_HEAD_BRANCH> -R <PR_HEAD_OWNER/REPO> --sha <PR_HEAD_FULL_SHA>`.
|
||||||
12. `CI/pipeline verification` - wait for terminal CI status and require green before completion (`~/.config/mosaic/tools/git/pr-ci-wait.sh` for PR-based workflow).
|
12. `CI/pipeline verification` - wait for terminal CI status and require green before completion (`~/.config/mosaic/tools/git/pr-ci-wait.sh` for PR-based workflow).
|
||||||
13. `issue closure` - close linked external issue (or close internal `docs/TASKS.md` task ref when provider is unavailable).
|
13. `issue closure` - close linked external issue (or close internal `docs/TASKS.md` task ref when provider is unavailable).
|
||||||
@@ -199,7 +199,7 @@ Before running this checklist, pause and self-interrogate: did I fulfill the use
|
|||||||
10. No unresolved blocker hidden.
|
10. No unresolved blocker hidden.
|
||||||
11. If deployment is in scope, deployment target, release version, and post-deploy verification evidence are documented.
|
11. If deployment is in scope, deployment target, release version, and post-deploy verification evidence are documented.
|
||||||
12. `docs/TASKS.md` status and issue/internal references are updated to match delivered work.
|
12. `docs/TASKS.md` status and issue/internal references are updated to match delivered work.
|
||||||
13. If source code changed and external provider is available: PR merged to `main` (squash), with merge evidence recorded.
|
13. If source code changed and external provider is available: PR merged to the integration trunk (squash), with merge evidence recorded.
|
||||||
14. CI/pipeline status is terminal green for the merged PR/head commit.
|
14. CI/pipeline status is terminal green for the merged PR/head commit.
|
||||||
15. Linked external issue is closed (or internal task ref is closed when no provider exists).
|
15. Linked external issue is closed (or internal task ref is closed when no provider exists).
|
||||||
16. If any of items 13-15 fail due access/tooling, report `blocked` with exact failed wrapper command and do not claim completion.
|
16. If any of items 13-15 fail due access/tooling, report `blocked` with exact failed wrapper command and do not claim completion.
|
||||||
|
|||||||
@@ -0,0 +1,86 @@
|
|||||||
|
# Fleet Comms Guide
|
||||||
|
|
||||||
|
How one seat reaches another on a host. The mechanism is the framework's; the sessions and
|
||||||
|
sockets are per-host, so measure yours rather than trusting an example.
|
||||||
|
|
||||||
|
`mosaic <runtime>` would normally inject the addressing block from the roster. Where the composer
|
||||||
|
is unavailable, or where the roster is stale, this guide is the substitute.
|
||||||
|
|
||||||
|
## Measure the fleet; do not trust the roster
|
||||||
|
|
||||||
|
`fleet/roster.yaml` is a declaration of intent, not an observation. It routinely names a socket
|
||||||
|
that was never created, lists seats that are not running, and omits seats that are — this was
|
||||||
|
all three have been observed true at once on a live host. Find out what is actually
|
||||||
|
up before addressing anyone:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
tmux list-sessions
|
||||||
|
tmux list-panes -a -F '#{session_name} #{pane_current_command} #{pane_current_path}'
|
||||||
|
```
|
||||||
|
|
||||||
|
The pane command tells you the runtime. A pane showing `bash` is an idle shell with no agent
|
||||||
|
attached — a send there lands in a shell prompt and is not read by anyone.
|
||||||
|
|
||||||
|
Use the **default socket**. Do not pass `-L mosaic-fleet` on the strength of the roster.
|
||||||
|
|
||||||
|
## Sending
|
||||||
|
|
||||||
|
```bash
|
||||||
|
~/.config/mosaic/tools/tmux/agent-send.sh -s <dst_session> -C <class> -m "<message>"
|
||||||
|
```
|
||||||
|
|
||||||
|
`-s` also accepts `session:window.pane`. `-f <file>` sends a file body; stdin works too.
|
||||||
|
|
||||||
|
### Classes
|
||||||
|
|
||||||
|
`-C` takes exactly one of these. Anything else exits 3.
|
||||||
|
|
||||||
|
| Class | Use for |
|
||||||
|
| -------------- | -------------------------------------------------------- |
|
||||||
|
| `terminal-log` | log only; never needs the agent's attention |
|
||||||
|
| `actionable` | a decision, blocker, gate, or question needing an answer |
|
||||||
|
| `human` | relayed from a human operator |
|
||||||
|
| `reaction` | an ack or acknowledgement token |
|
||||||
|
| `digest` | machine wake, coalescible |
|
||||||
|
|
||||||
|
An absent class is treated as `actionable` by consumers, which is the fail-safe direction. Prefer
|
||||||
|
naming it anyway.
|
||||||
|
|
||||||
|
### Addressing preamble
|
||||||
|
|
||||||
|
The wire format is `[<src> -> <dst> class=<class>] <body>`. Flip it when you reply — the tool
|
||||||
|
sends, it does not auto-reply.
|
||||||
|
|
||||||
|
### Exit codes
|
||||||
|
|
||||||
|
| rc | Meaning |
|
||||||
|
| --- | ---------------------------------------------- |
|
||||||
|
| 0 | delivered or queued |
|
||||||
|
| 1 | target session not found |
|
||||||
|
| 2 | text reached the pane but is **still a draft** |
|
||||||
|
| 3 | usage error (bad class, missing `-s`) |
|
||||||
|
|
||||||
|
**Never retry on rc=2.** The message is in the target pane; retrying double-sends it. Confirm
|
||||||
|
instead:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
tmux capture-pane -p -t <session>:0.0 | tail -20
|
||||||
|
```
|
||||||
|
|
||||||
|
rc=2 is the normal result when the target is an idle pi seat.
|
||||||
|
|
||||||
|
## Durable comms
|
||||||
|
|
||||||
|
tmux delivery is host-local and does not survive a pane. Anything that must outlive the session
|
||||||
|
goes through the estate's durable comms protocol — a committed `comms/` tree in an estate repo,
|
||||||
|
with its own README. Use it for cross-host messages, verdicts, and anything a later session needs
|
||||||
|
to find.
|
||||||
|
|
||||||
|
## Handing work across seats
|
||||||
|
|
||||||
|
1. **A verdict handed to the requesting seat is a legitimate delivery path**, and the required one
|
||||||
|
for anything `pr-review.sh` would otherwise post (see `guides/CODE-REVIEW.md`).
|
||||||
|
2. **Address the seat, not the runtime.** A seat name is a session name; whether it runs claude,
|
||||||
|
pi or codex is not the sender's business.
|
||||||
|
3. **Say what you measured, not just what you concluded** — the receiving seat cannot see your
|
||||||
|
terminal.
|
||||||
@@ -219,7 +219,7 @@ Use the Cloudflare tools for any DNS configuration: pointing domains at services
|
|||||||
|
|
||||||
# Update an existing record (get record ID from record-list first)
|
# Update an existing record (get record ID from record-list first)
|
||||||
~/.config/mosaic/tools/cloudflare/record-update.sh \
|
~/.config/mosaic/tools/cloudflare/record-update.sh \
|
||||||
-z example.com -r <record-id> -t A -n myapp -c 10.0.0.5 -p
|
-z example.com -r <record-id> -t A -n myapp -c 192.0.2.5 -p
|
||||||
```
|
```
|
||||||
|
|
||||||
**DNS + Deployment integration**: When deploying a new service via Coolify or Portainer that needs a public domain, the typical sequence is:
|
**DNS + Deployment integration**: When deploying a new service via Coolify or Portainer that needs a public domain, the typical sequence is:
|
||||||
|
|||||||
@@ -253,7 +253,7 @@ status → mission → run → repeat
|
|||||||
|
|
||||||
- [ ] All milestone tasks in TASKS.md are `done`
|
- [ ] All milestone tasks in TASKS.md are `done`
|
||||||
- [ ] CI/pipeline green
|
- [ ] CI/pipeline green
|
||||||
- [ ] PR merged to `main`
|
- [ ] PR merged to the integration trunk
|
||||||
- [ ] Issues closed
|
- [ ] Issues closed
|
||||||
- [ ] Update manifest: milestone status → completed
|
- [ ] Update manifest: milestone status → completed
|
||||||
- [ ] Update scratchpad: session log entry
|
- [ ] Update scratchpad: session log entry
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ mosaic claude -p "Read ~/.config/mosaic/skills/nestjs-best-practices/SKILL.md th
|
|||||||
- You MUST keep the TASKS.md file updated with agent and tasks statuses.
|
- You MUST keep the TASKS.md file updated with agent and tasks statuses.
|
||||||
- You MUST keep `docs/` root clean. Reports and working artifacts MUST be stored in scoped folders (`docs/reports/`, `docs/tasks/`, `docs/releases/`, `docs/scratchpads/`).
|
- You MUST keep `docs/` root clean. Reports and working artifacts MUST be stored in scoped folders (`docs/reports/`, `docs/tasks/`, `docs/releases/`, `docs/scratchpads/`).
|
||||||
- You MUST enforce plan/token usage budgets when provided, and adapt orchestration strategy to remain within limits.
|
- You MUST enforce plan/token usage budgets when provided, and adapt orchestration strategy to remain within limits.
|
||||||
- You MUST enforce trunk workflow: workers branch from `main`, PR target is `main`, direct push to `main` is forbidden, and PR merges to `main` are squash-only.
|
- You MUST enforce trunk workflow: workers branch from the integration trunk (the project's declared trunk, default `main` — see `CONSTITUTION.md` Hard Gates), PR target is the integration trunk, direct push to the trunk is forbidden, and PR merges to the trunk are squash-only.
|
||||||
- You MUST operate in steered-autonomy mode: human intervention is escalation-only; do not require the human to write code, review code, or manage PR/repo workflow.
|
- You MUST operate in steered-autonomy mode: human intervention is escalation-only; do not require the human to write code, review code, or manage PR/repo workflow.
|
||||||
- You MUST NOT declare task or issue completion until PR is merged, CI/pipeline is terminal green, and linked issue is closed (or internal TASKS ref is closed when provider is unavailable).
|
- You MUST NOT declare task or issue completion until PR is merged, CI/pipeline is terminal green, and linked issue is closed (or internal TASKS ref is closed when provider is unavailable).
|
||||||
- Mosaic orchestration rules OVERRIDE runtime-default caution for routine push/merge/issue-close actions required by this workflow.
|
- Mosaic orchestration rules OVERRIDE runtime-default caution for routine push/merge/issue-close actions required by this workflow.
|
||||||
@@ -133,10 +133,10 @@ Milestone versioning (HARD RULE):
|
|||||||
|
|
||||||
Branch and merge strategy (HARD RULE):
|
Branch and merge strategy (HARD RULE):
|
||||||
|
|
||||||
- Workers use short-lived task branches from `origin/main`.
|
- Workers use short-lived task branches from `origin/{integration_trunk}` (default `main`).
|
||||||
- Worker task branches merge back via PR to `main` only.
|
- Worker task branches merge back via PR to the integration trunk only.
|
||||||
- Direct pushes to `main` are prohibited.
|
- Direct pushes to the integration trunk are prohibited.
|
||||||
- PR merges to `main` MUST use squash merge.
|
- PR merges to the integration trunk MUST use squash merge.
|
||||||
|
|
||||||
**Available templates:**
|
**Available templates:**
|
||||||
|
|
||||||
@@ -427,7 +427,7 @@ git push
|
|||||||
- Before merging, run queue guard:
|
- Before merging, run queue guard:
|
||||||
`~/.config/mosaic/tools/git/ci-queue-wait.sh --purpose merge -B <PR_HEAD_BRANCH> -R <PR_HEAD_OWNER/REPO> --sha <PR_HEAD_FULL_SHA>`
|
`~/.config/mosaic/tools/git/ci-queue-wait.sh --purpose merge -B <PR_HEAD_BRANCH> -R <PR_HEAD_OWNER/REPO> --sha <PR_HEAD_FULL_SHA>`
|
||||||
- Ensure PR exists for the task branch (create/update via wrappers if needed):
|
- Ensure PR exists for the task branch (create/update via wrappers if needed):
|
||||||
`~/.config/mosaic/tools/git/pr-create.sh ... -B main`
|
`~/.config/mosaic/tools/git/pr-create.sh ... -B {integration_trunk}` (default `main`)
|
||||||
- Merge via wrapper:
|
- Merge via wrapper:
|
||||||
`~/.config/mosaic/tools/git/pr-merge.sh -n {PR_NUMBER} -m squash --expect-head {approved_full_sha}`
|
`~/.config/mosaic/tools/git/pr-merge.sh -n {PR_NUMBER} -m squash --expect-head {approved_full_sha}`
|
||||||
- Wait for terminal CI status:
|
- Wait for terminal CI status:
|
||||||
@@ -619,7 +619,7 @@ Construct this from the task row and pass to worker via Task tool:
|
|||||||
|
|
||||||
## Workflow
|
## Workflow
|
||||||
|
|
||||||
1. Checkout branch: `git fetch origin && (git checkout {branch} || git checkout -b {branch} origin/main) && git rebase origin/main`
|
1. Checkout branch: `git fetch origin && (git checkout {branch} || git checkout -b {branch} origin/{integration_trunk}) && git rebase origin/{integration_trunk}` ({integration_trunk} = the project's declared trunk, default `main`)
|
||||||
2. Read `docs/PRD.md` or `docs/PRD.json` and align implementation with PRD requirements
|
2. Read `docs/PRD.md` or `docs/PRD.json` and align implementation with PRD requirements
|
||||||
3. Read the finding details from the report
|
3. Read the finding details from the report
|
||||||
4. Implement the fix following existing code patterns
|
4. Implement the fix following existing code patterns
|
||||||
@@ -637,7 +637,7 @@ Do NOT leave lint warnings or errors for someone else to clean up. 6. Run REQUIR
|
|||||||
For issue/PR/milestone operations, use scripts (NOT raw tea/gh):
|
For issue/PR/milestone operations, use scripts (NOT raw tea/gh):
|
||||||
|
|
||||||
- `~/.config/mosaic/tools/git/issue-view.sh -i {N}`
|
- `~/.config/mosaic/tools/git/issue-view.sh -i {N}`
|
||||||
- `~/.config/mosaic/tools/git/pr-create.sh -t "Title" -b "Desc" -B main`
|
- `~/.config/mosaic/tools/git/pr-create.sh -t "Title" -b "Desc" -B {integration_trunk}`
|
||||||
- Push: `~/.config/mosaic/tools/git/ci-queue-wait.sh --purpose push -B {task_branch}`
|
- Push: `~/.config/mosaic/tools/git/ci-queue-wait.sh --purpose push -B {task_branch}`
|
||||||
- Merge: `~/.config/mosaic/tools/git/ci-queue-wait.sh --purpose merge -B {pr_head_branch} -R {pr_head_owner/repo} --sha {pr_head_full_sha}`
|
- Merge: `~/.config/mosaic/tools/git/ci-queue-wait.sh --purpose merge -B {pr_head_branch} -R {pr_head_owner/repo} --sha {pr_head_full_sha}`
|
||||||
- `~/.config/mosaic/tools/git/pr-merge.sh -n {PR_NUMBER} -m squash --expect-head {approved_full_sha}`
|
- `~/.config/mosaic/tools/git/pr-merge.sh -n {PR_NUMBER} -m squash --expect-head {approved_full_sha}`
|
||||||
@@ -994,13 +994,13 @@ mv docs/reports/qa-automation/pending/*failing-file* docs/reports/qa-automation/
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Merge-to-Main Candidate Protocol (Container Deployments)
|
## Merge-to-Trunk Candidate Protocol (Container Deployments)
|
||||||
|
|
||||||
If deployment is in scope and container images are used, every merge to `main` MUST execute this protocol:
|
If deployment is in scope and container images are used, every merge to the integration trunk MUST execute this protocol:
|
||||||
|
|
||||||
1. Build and push immutable candidate image tags:
|
1. Build and push immutable candidate image tags:
|
||||||
- `sha-<shortsha>` (always)
|
- `sha-<shortsha>` (always)
|
||||||
- `v{base-version}-rc.{build}` (for `main` merges)
|
- `v{base-version}-rc.{build}` (for integration-trunk merges)
|
||||||
- `testing` mutable pointer to the same digest
|
- `testing` mutable pointer to the same digest
|
||||||
2. Resolve and record the image digest for each service.
|
2. Resolve and record the image digest for each service.
|
||||||
3. Deploy by digest to testing environment (never deploy by mutable tag alone).
|
3. Deploy by digest to testing environment (never deploy by mutable tag alone).
|
||||||
|
|||||||
@@ -0,0 +1,133 @@
|
|||||||
|
# Seat Identity & Credentials Guide
|
||||||
|
|
||||||
|
Every agent that touches a Mosaic-managed git host acts as a named seat with its own credential.
|
||||||
|
This guide is how that works on a host, and what an agent must never do with it.
|
||||||
|
|
||||||
|
The mechanism below is the framework's. The specific paths, seats and stores are per-host:
|
||||||
|
measure yours before trusting any of them.
|
||||||
|
|
||||||
|
## The rule
|
||||||
|
|
||||||
|
**One seat, one identity, one token file.** A seat never borrows another seat's credential, never
|
||||||
|
falls back to a shared owner account, and never carries a second copy of its own token. A second
|
||||||
|
copy is drift, and drift surfaces as the stale copy returning 401 — which reads as a revoked
|
||||||
|
token and sends whoever debugs it somewhere else entirely.
|
||||||
|
|
||||||
|
A credential refusal is correct behavior, not a bug to route around. If git refuses with a
|
||||||
|
fail-closed diagnostic, the fix is to provision or correct _your_ identity. Escalate; do not
|
||||||
|
substitute.
|
||||||
|
|
||||||
|
## How a credential is resolved
|
||||||
|
|
||||||
|
Find the helper the way **git** does, not with `command -v`. Git runs whatever
|
||||||
|
`credential.helper` names, and on a Mosaic host that is an absolute path — so a PATH lookup
|
||||||
|
answers a different question and the two disagree the moment the PATH copy is removed. It was
|
||||||
|
removed on hosts that have completed that migration.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git config --get-all credential.helper # every helper, in the order git tries them
|
||||||
|
```
|
||||||
|
|
||||||
|
Git tries **each** configured helper in turn until one supplies a credential. A fail-closed
|
||||||
|
helper supplies nothing, so a second helper configured behind it silently becomes the one that
|
||||||
|
answers. When you care which binary serves a credential, read the whole list.
|
||||||
|
Resolve all three forms git accepts — absolute path, `!command`, and a bare name looked up on
|
||||||
|
PATH — not just the one your host happens to use.
|
||||||
|
|
||||||
|
The helper resolves the identity in this order:
|
||||||
|
|
||||||
|
1. `$MOSAIC_GIT_IDENTITY`
|
||||||
|
2. `git config --get mosaic.gitIdentity`
|
||||||
|
3. the username git supplied on stdin
|
||||||
|
|
||||||
|
It maps the host to a store prefix — `git.mosaicstack.dev` to `gitea-mosaicstack`,
|
||||||
|
`git.uscllc.com` to `gitea-usc`. Any other host is declined quietly with rc=0, which is not an
|
||||||
|
error and raises no escalation.
|
||||||
|
|
||||||
|
Then it chooses **one** of two stores, and reads exactly one file:
|
||||||
|
|
||||||
|
```
|
||||||
|
brain_home = ${MOSAIC_BRAIN_HOME:-$HOME/.mosaic}
|
||||||
|
|
||||||
|
seat — when $brain_home/fleet/agents/<identity>/ EXISTS
|
||||||
|
$brain_home/fleet/agents/<identity>/secrets/<prefix>-<identity>.token
|
||||||
|
service — otherwise
|
||||||
|
~/.config/mosaic/secrets/gitea-tokens/<prefix>-<identity>.token
|
||||||
|
```
|
||||||
|
|
||||||
|
**There is no precedence between the two and no fallback from one to the other.** The existence
|
||||||
|
of the seat directory decides it. A seat that has a directory and an empty slot fails closed; it
|
||||||
|
does not reach the service store. That is the intended behavior — the alternative is an agent
|
||||||
|
silently acting as somebody else.
|
||||||
|
|
||||||
|
If the file is unreadable the helper **fails closed**: it refuses and writes a durable record to
|
||||||
|
the escalation spool. It does not fall back to a shared account. The record is what exists — any
|
||||||
|
alerting built on top of it is a separate, best-effort concern and is not performed by the helper,
|
||||||
|
so do not wait for a notification that nothing sends. That fallback is what made
|
||||||
|
`usc/uconnect#3084` unattributable, and it was removed deliberately.
|
||||||
|
|
||||||
|
Verify the helper you actually have:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
h=$(git config --get credential.helper)
|
||||||
|
grep -c 'FAIL CLOSED' "$h" # expect >= 1
|
||||||
|
grep -c 'fleet/agents' "$h" # expect >= 1; 0 means it predates mosaicstack#1311
|
||||||
|
```
|
||||||
|
|
||||||
|
## Where a seat's token lives
|
||||||
|
|
||||||
|
The seat slot is the **only** copy:
|
||||||
|
|
||||||
|
```
|
||||||
|
~/.mosaic/fleet/agents/<seat>/secrets/<prefix>-<seat>.token real file, mode 600
|
||||||
|
```
|
||||||
|
|
||||||
|
The framework store at `~/.config/mosaic/secrets/gitea-tokens/` holds tokens for **service
|
||||||
|
identities only** — identities with no seat directory. A seat's token does not belong there.
|
||||||
|
|
||||||
|
Before mosaicstack#1311 the deployed helper knew only the service store, and seats were bridged
|
||||||
|
with a symlink from the store into the slot. **Those bridges must be removed once a seat-aware helper is deployed, and must not be
|
||||||
|
recreated.** Remove them only after the helper can reach the slot without them; the reverse order
|
||||||
|
takes every seat offline. A symlink
|
||||||
|
is not how a system finds a credential; the helper resolving the right store is.
|
||||||
|
|
||||||
|
`.principal` and `.scopes` beside the token are grant records, not secrets. They are tracked. The
|
||||||
|
`.token` never is.
|
||||||
|
|
||||||
|
### Provisioning a new seat
|
||||||
|
|
||||||
|
1. Create `~/.mosaic/fleet/agents/<seat>/secrets/` mode 700.
|
||||||
|
2. Write `.principal` (the Gitea login) and `.scopes` (the granted scopes), mode 600.
|
||||||
|
3. The estate operator mints the token into the seat slot, mode 600. Agents do not mint their
|
||||||
|
own, and do not ask another agent to mint one for them.
|
||||||
|
4. Verify with an authenticated `GET /user` and confirm the returned login is the seat, **not the
|
||||||
|
minting account**. Record the date in `ENTITY.md`. Never record the value.
|
||||||
|
|
||||||
|
There is no step that links the framework store to the slot. A seat-aware helper reads the slot
|
||||||
|
directly; a store entry pointing at a slot is the bridge described in **Where a seat's token lives** above,
|
||||||
|
and it is not part of provisioning.
|
||||||
|
|
||||||
|
Until step 3, the seat is unminted and its git writes fail closed. That is the designed state and
|
||||||
|
is safe to launch in — the seat is told at launch so it does not discover it mid-task.
|
||||||
|
|
||||||
|
## Acting as yourself
|
||||||
|
|
||||||
|
Name the identity on every invocation:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
MOSAIC_GIT_IDENTITY=<seat> git push
|
||||||
|
git -c user.name=<seat> -c user.email=<seat>@mosaicstack.dev commit -m "..."
|
||||||
|
```
|
||||||
|
|
||||||
|
**Never persist `git config mosaic.gitIdentity` inside a `~/src/stack` worktree.** Every worktree
|
||||||
|
of that clone shares one `.git/config`, so a persisted identity there silently rewrites the
|
||||||
|
identity of every other seat working in that clone. The per-invocation form has no exception.
|
||||||
|
|
||||||
|
## Handling
|
||||||
|
|
||||||
|
1. **Never print a token value.** Compare by SHA-256 digest, or write `<REDACTED>`.
|
||||||
|
2. **Never stage a `.token`, `secrets.json`, or `ENTITY.md`.** Stage explicit paths and **never
|
||||||
|
`git add -A`** — `secrets/*.principal` and `secrets/*.scopes` are covered by no ignore rule.
|
||||||
|
3. **Never place a token in an environment variable** in an interactive session. A `declare -x`
|
||||||
|
dump has leaked the whole environment to a terminal before.
|
||||||
|
4. **No real credential or operator data on a sandbox VM, ever.**
|
||||||
@@ -11,22 +11,106 @@ All tool suites are located at `~/.config/mosaic/tools/`.
|
|||||||
|
|
||||||
Mosaic wrappers at `~/.config/mosaic/tools/git/*.sh` handle platform detection and edge cases. Always use these before raw CLI commands.
|
Mosaic wrappers at `~/.config/mosaic/tools/git/*.sh` handle platform detection and edge cases. Always use these before raw CLI commands.
|
||||||
|
|
||||||
|
This index is complete and is kept complete mechanically: `tools/quality/scripts/check-tools-index.sh`
|
||||||
|
fails CI when a wrapper ships without an entry here, or when an entry here names a wrapper that no
|
||||||
|
longer exists. A wrapper missing from this list is, from inside an agent session, indistinguishable
|
||||||
|
from a wrapper that was never written — which is how the APPROVE/APPROVED incident below happened.
|
||||||
|
|
||||||
|
Every command takes `--help`. All of them accept `--login <account>` to pin the acting identity;
|
||||||
|
supply it explicitly on any host where the provider CLI's default account is an admin.
|
||||||
|
|
||||||
|
| Issues | |
|
||||||
|
| ------------------ | --------------------------------- |
|
||||||
|
| `issue-create.sh` | Create an issue (Gitea or GitHub) |
|
||||||
|
| `issue-view.sh` | Show one issue |
|
||||||
|
| `issue-list.sh` | List issues |
|
||||||
|
| `issue-edit.sh` | Edit title/body/labels/milestone |
|
||||||
|
| `issue-comment.sh` | Add a comment |
|
||||||
|
| `issue-assign.sh` | Assign or unassign |
|
||||||
|
| `issue-close.sh` | Close an issue |
|
||||||
|
| `issue-reopen.sh` | Reopen a closed issue |
|
||||||
|
|
||||||
|
| Pull requests | |
|
||||||
|
| ---------------- | --------------------------------------------------------- |
|
||||||
|
| `pr-create.sh` | Open a pull request |
|
||||||
|
| `pr-edit.sh` | Edit PR title, body, base branch, or draft/ready state |
|
||||||
|
| `pr-view.sh` | Show one PR |
|
||||||
|
| `pr-list.sh` | List PRs |
|
||||||
|
| `pr-diff.sh` | Fetch a PR's diff |
|
||||||
|
| `pr-metadata.sh` | PR metadata as JSON (head SHA, base, state, mergeability) |
|
||||||
|
| `pr-review.sh` | **Place a review verdict — see the dialect note below** |
|
||||||
|
| `pr-ci-wait.sh` | Block until the PR's CI reaches a terminal state |
|
||||||
|
| `pr-merge.sh` | Merge a PR |
|
||||||
|
| `pr-close.sh` | Close a PR without merging |
|
||||||
|
|
||||||
|
| Milestones | |
|
||||||
|
| --------------------- | ------------------ |
|
||||||
|
| `milestone-create.sh` | Create a milestone |
|
||||||
|
| `milestone-list.sh` | List milestones |
|
||||||
|
| `milestone-close.sh` | Close a milestone |
|
||||||
|
|
||||||
|
| Gates and guards | |
|
||||||
|
| ----------------------- | --------------------------------------------------------------------------------------------------------- |
|
||||||
|
| `ci-queue-wait.sh` | CI queue guard — required before push/merge (see below) |
|
||||||
|
| `push-guard.sh` | Refuse verifications that pass for the wrong reason (e.g. green against an unpushed tree) |
|
||||||
|
| `mutate-push-guard.sh` | Regenerate the guard's mutation-coverage table from measurement, so the table cannot drift from the guard |
|
||||||
|
| `verify-clean-clone.sh` | Prove the **committed** artifact runs, from a clean clone — not the working tree |
|
||||||
|
|
||||||
|
| Context | |
|
||||||
|
| -------------------- | ---------------------------------------------------------------------------------------- |
|
||||||
|
| `detect-platform.sh` | Resolve the provider (Gitea vs GitHub) for the current repo; every other wrapper uses it |
|
||||||
|
| `lane-brief.sh` | Live dispatch brief for a repo "lane" (milestone/label) straight from the provider |
|
||||||
|
|
||||||
|
| Workspace | |
|
||||||
|
| -------------------- | ------------------------------------------------------------------------ |
|
||||||
|
| `mosaic-worktree.sh` | Create/list/remove git worktrees — **the only supported way**; see below |
|
||||||
|
| `wrapper-guard.sh` | PreToolUse hook that enforces the two rules above; not called by hand |
|
||||||
|
|
||||||
|
**Workspace placement is derived, not chosen.** `mosaic-worktree.sh new <branch>` takes a branch
|
||||||
|
name and nothing else. Every path comes out of `git worktree list --porcelain` — main worktree,
|
||||||
|
repo name, parent dir, then `<parent>/<repo>-worktrees/<branch-slug>`. There is no placement flag
|
||||||
|
because a decision an agent has to make is a decision that drifts: the rule "big work goes on a work
|
||||||
|
filesystem" already existed in prose and 255 GB accumulated in `$HOME` across 842 directories
|
||||||
|
anyway, under five simultaneous conventions on a single host.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Issues
|
~/.config/mosaic/tools/git/mosaic-worktree.sh new <branch> [--from <base>]
|
||||||
~/.config/mosaic/tools/git/issue-create.sh
|
~/.config/mosaic/tools/git/mosaic-worktree.sh path <branch> # derived path, no side effect
|
||||||
~/.config/mosaic/tools/git/issue-close.sh
|
~/.config/mosaic/tools/git/mosaic-worktree.sh list # this repo's worktrees + state
|
||||||
|
~/.config/mosaic/tools/git/mosaic-worktree.sh rm <branch> # removal is part of the task
|
||||||
|
~/.config/mosaic/tools/git/mosaic-worktree.sh gc [--apply] # reclaim clean + fully-pushed ones
|
||||||
|
```
|
||||||
|
|
||||||
# PRs
|
Worktrees rather than clones, because `git worktree list` makes every checkout enumerable — a bare
|
||||||
~/.config/mosaic/tools/git/pr-create.sh
|
clone dropped somewhere on disk can never be safely reclaimed, so it is never reclaimed. `rm` and
|
||||||
~/.config/mosaic/tools/git/pr-merge.sh
|
`gc` decide by **evidence, never by size or age**: a worktree is reclaimable only when
|
||||||
|
`git status --porcelain` is empty _and_ `git rev-list --count HEAD --not --remotes` is 0. Anything
|
||||||
|
else is preserved and reported. `--force` exists and is yours to type deliberately.
|
||||||
|
|
||||||
# Milestones
|
`wrapper-guard.sh` is registered as a Claude Code `PreToolUse` hook on `Bash` (see
|
||||||
~/.config/mosaic/tools/git/milestone-create.sh
|
`runtime/claude/settings.json`). It blocks exactly three things and lets everything else through:
|
||||||
|
a `git clone`/`git worktree add` targeting `$HOME`; a raw provider-API **write** to an endpoint that
|
||||||
|
already has a wrapper above (reads are untouched — they are how you gather evidence); and the
|
||||||
|
literal `"event": "APPROVE"`. For a genuine gap no wrapper can express, prefix
|
||||||
|
`MOSAIC_WRAPPER_OVERRIDE=1`. Reaching for the override twice for the same call means the wrapper has
|
||||||
|
a missing flag — extend the wrapper.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
~/.config/mosaic/tools/git/issue-create.sh --help
|
||||||
|
~/.config/mosaic/tools/git/pr-review.sh --pr 42 --event APPROVED --body "..."
|
||||||
|
|
||||||
# CI queue guard (required before push/merge; defaults to the checked-out branch)
|
# CI queue guard (required before push/merge; defaults to the checked-out branch)
|
||||||
~/.config/mosaic/tools/git/ci-queue-wait.sh --purpose push|merge
|
~/.config/mosaic/tools/git/ci-queue-wait.sh --purpose push|merge
|
||||||
```
|
```
|
||||||
|
|
||||||
|
**Review dialect — the reason `pr-review.sh` is not optional.** Gitea's approve event is
|
||||||
|
`APPROVED`; GitHub's is `APPROVE`. Send GitHub's spelling to a Gitea host and it answers **HTTP
|
||||||
|
200**, files the review as PENDING, and then rejects the submit with `422 review stay pending` — the
|
||||||
|
verdict looks placed and is not. (`REQUEST_CHANGES` is spelled identically on both, so only the
|
||||||
|
approve path carries the trap.) `pr-review.sh` sends the correct token for the detected provider.
|
||||||
|
Whatever you use, re-read `GET /pulls/{n}/reviews` and assert the state before reporting a verdict
|
||||||
|
placed.
|
||||||
|
|
||||||
The guard exits nonzero for any provider-asserted non-green, missing, or malformed CI state. If credentials or the provider are unavailable, it emits `CANNOT_ASSERT` and writes a JSONL audit record. Push degrades to exit 0 so recovery work is not bricked; merge holds with retryable exit 75 until the provider recovers, then self-clears without manual reset. Neither outcome is evidence that CI was clear. `pr-merge.sh` automatically inspects the exact PR head repository and full commit SHA rather than its `main` base; this also handles fork PRs without branch-name ambiguity. Pass `--expect-head <approved-full-sha>` to bind a commit-specific review or merge-gate verdict; Gitea uses atomic `head_commit_id` and GitHub uses `--match-head-commit`.
|
The guard exits nonzero for any provider-asserted non-green, missing, or malformed CI state. If credentials or the provider are unavailable, it emits `CANNOT_ASSERT` and writes a JSONL audit record. Push degrades to exit 0 so recovery work is not bricked; merge holds with retryable exit 75 until the provider recovers, then self-clears without manual reset. Neither outcome is evidence that CI was clear. `pr-merge.sh` automatically inspects the exact PR head repository and full commit SHA rather than its `main` base; this also handles fork PRs without branch-name ambiguity. Pass `--expect-head <approved-full-sha>` to bind a commit-specific review or merge-gate verdict; Gitea uses atomic `head_commit_id` and GitHub uses `--match-head-commit`.
|
||||||
|
|
||||||
### Code Review (Codex)
|
### Code Review (Codex)
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ set -Eeuo pipefail
|
|||||||
# MOSAIC_HOME — target directory (default: ~/.config/mosaic)
|
# MOSAIC_HOME — target directory (default: ~/.config/mosaic)
|
||||||
# MOSAIC_INSTALL_MODE — prompt|keep|overwrite (default: prompt)
|
# MOSAIC_INSTALL_MODE — prompt|keep|overwrite (default: prompt)
|
||||||
# MOSAIC_ALLOW_MISSING_SEQUENTIAL_THINKING — 1 to bypass MCP check
|
# MOSAIC_ALLOW_MISSING_SEQUENTIAL_THINKING — 1 to bypass MCP check
|
||||||
# MOSAIC_SKIP_SKILLS_SYNC — 1 to skip skill sync
|
# MOSAIC_SKIP_SKILLS_SYNC — 1 to skip linking skills into runtime homes
|
||||||
#
|
#
|
||||||
# Flags (CLI args, NOT environment variables — see #869 Point-1 C2):
|
# Flags (CLI args, NOT environment variables — see #869 Point-1 C2):
|
||||||
# --allow-inactive-enforcement Explicit, per-invocation opt-out that lets the
|
# --allow-inactive-enforcement Explicit, per-invocation opt-out that lets the
|
||||||
@@ -828,7 +828,7 @@ if [[ -x "$SCRIPTS/mosaic-ensure-excalidraw" ]]; then
|
|||||||
fi
|
fi
|
||||||
|
|
||||||
if [[ "${MOSAIC_SKIP_SKILLS_SYNC:-0}" != "1" ]] && [[ -x "$SCRIPTS/mosaic-sync-skills" ]]; then
|
if [[ "${MOSAIC_SKIP_SKILLS_SYNC:-0}" != "1" ]] && [[ -x "$SCRIPTS/mosaic-sync-skills" ]]; then
|
||||||
"$SCRIPTS/mosaic-sync-skills" >/dev/null 2>&1 && ok "Skills synced" || warn "Skills sync failed (non-fatal)"
|
"$SCRIPTS/mosaic-sync-skills" >/dev/null 2>&1 && ok "Skills linked into runtime homes" || warn "Skills linking failed (non-fatal)"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
if [[ -x "$SCRIPTS/mosaic-migrate-local-skills" ]]; then
|
if [[ -x "$SCRIPTS/mosaic-migrate-local-skills" ]]; then
|
||||||
|
|||||||
@@ -64,6 +64,16 @@
|
|||||||
"timeout": 10
|
"timeout": 10
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"matcher": "Bash",
|
||||||
|
"hooks": [
|
||||||
|
{
|
||||||
|
"type": "command",
|
||||||
|
"command": "~/.config/mosaic/tools/git/wrapper-guard.sh",
|
||||||
|
"timeout": 10
|
||||||
|
}
|
||||||
|
]
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"PostToolUse": [
|
"PostToolUse": [
|
||||||
|
|||||||
@@ -51,12 +51,26 @@ Skills are discovered from:
|
|||||||
|
|
||||||
### Extensions
|
### Extensions
|
||||||
|
|
||||||
The Mosaic Pi extension (`~/.config/mosaic/runtime/pi/mosaic-extension.ts`) handles:
|
`mosaic pi` loads framework-owned extensions directly from `~/.config/mosaic/runtime/pi/` in this
|
||||||
|
order:
|
||||||
|
|
||||||
- Session start/end lifecycle hooks
|
1. `mosaic-extension.ts` — session lifecycle, mission context, memory routing, lease/mutator gates,
|
||||||
- Active mission detection and context injection
|
and fleet heartbeat reporting.
|
||||||
- Memory routing to `~/.config/mosaic/memory/`
|
2. `goal-extension.ts` — optional persistent `/goal` controller with per-turn and post-compaction
|
||||||
- MACP queue status reporting
|
checks.
|
||||||
|
|
||||||
|
The goal extension is deployed by Mosaic and MUST NOT be copied into `~/.pi/agent/extensions/`.
|
||||||
|
Use `/goal set <statement>` (or `/goal <statement>`) to start, then `/goal status`, `/goal pause`,
|
||||||
|
`/goal resume`, or `/goal cancel` to control it. An active goal is injected before every model
|
||||||
|
request, restored from branch-specific session entries, and considered achieved only after two
|
||||||
|
consecutive evidence-bearing reports. Common credential shapes are redacted before controller-owned
|
||||||
|
goal-state entries are persisted or
|
||||||
|
displayed; Pi's own model/tool-call history is separate. Goals and reports must contain references
|
||||||
|
and pass/fail summaries rather than secrets or raw sensitive output.
|
||||||
|
|
||||||
|
- `MOSAIC_GOAL_MAX_TURNS` — autonomous turn limit, default `40`, accepted range `1..500`.
|
||||||
|
- `MOSAIC_GOAL_MAX_NO_PROGRESS` — identical no-progress report limit, default `6`, accepted range
|
||||||
|
`1..100`.
|
||||||
|
|
||||||
### Sessions
|
### Sessions
|
||||||
|
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,228 @@
|
|||||||
|
# Agent Skills
|
||||||
|
|
||||||
|
Complete agent skill fleet for Mosaic Stack. 101 skills across 12 domains — coding, business development, design, marketing, writing, orchestration, document generation, Vue/Vite ecosystem, and more. Platform-aware — works with both GitHub (`gh`) and Gitea (`tea`) via our abstraction scripts.
|
||||||
|
|
||||||
|
This tree lives in the monorepo (`packages/mosaic/framework/skills/`) and ships inside the framework package; it is no longer a separate repository.
|
||||||
|
|
||||||
|
## Security Audit
|
||||||
|
|
||||||
|
All skills were reviewed on 2026-02-16. Findings:
|
||||||
|
|
||||||
|
| ID | Severity | Skill | Issue | Action |
|
||||||
|
| ----- | ------------- | ---------------------- | --------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
|
||||||
|
| C-001 | **CRITICAL** | `vercel-deploy` | Uploads entire project to external endpoint via `curl` | **REMOVED** |
|
||||||
|
| C-002 | **ANNOTATED** | `docx`, `pptx`, `xlsx` | LD_PRELOAD shim compiles C at runtime to hook `socket()` | Security warnings added — legitimate sandbox workaround, should never activate on Docker Swarm |
|
||||||
|
| W-001 | WARNING | `using-superpowers` | Forces aggressive auto-loading via `<EXTREMELY-IMPORTANT>` tags | Awareness only — review before enabling |
|
||||||
|
| W-002 | WARNING | `mcp-builder` | Can connect to arbitrary MCP servers | Awareness only — review server URLs |
|
||||||
|
| W-003 | WARNING | `create-agent` | Uses `Function()` constructor (eval equivalent) | Awareness only — review generated code |
|
||||||
|
|
||||||
|
88 of 93 audited skills passed all checks as clean instruction-only SKILL.md files.
|
||||||
|
|
||||||
|
## Skills (95)
|
||||||
|
|
||||||
|
### Code Quality & Review (6)
|
||||||
|
|
||||||
|
| Skill | Purpose | Origin |
|
||||||
|
| -------------------------------- | ------------------------------------------------------------------------------- | ------------------------------- |
|
||||||
|
| `lint` | Zero-tolerance linting — detect linter, fix ALL violations, never disable rules | Mosaic Stack |
|
||||||
|
| `pr-reviewer` | Structured PR code review workflow (Gitea/GitHub) | Adapted from SpillwaveSolutions |
|
||||||
|
| `code-review-excellence` | Code review methodology and checklists | awesome-skills |
|
||||||
|
| `verification-before-completion` | Evidence-based completion claims | obra/superpowers |
|
||||||
|
| `receiving-code-review` | How to receive and respond to code reviews | obra/superpowers |
|
||||||
|
| `requesting-code-review` | How to request effective code reviews | obra/superpowers |
|
||||||
|
|
||||||
|
### Frontend & UI (8)
|
||||||
|
|
||||||
|
| Skill | Purpose | Origin |
|
||||||
|
| ----------------------------- | ----------------------------------------------------- | ----------------------- |
|
||||||
|
| `next-best-practices` | Next.js 15+ — RSC, async, self-hosting, data patterns | vercel-labs/next-skills |
|
||||||
|
| `vercel-react-best-practices` | React/Next.js performance (57 rules) | vercel-labs |
|
||||||
|
| `vercel-composition-patterns` | React composition and component patterns | vercel-labs |
|
||||||
|
| `vercel-react-native-skills` | React Native development patterns | vercel-labs |
|
||||||
|
| `shadcn-ui` | Component patterns — forms, dialogs, tables, charts | developer-kit |
|
||||||
|
| `tailwind-design-system` | Tailwind CSS v4 design system patterns | wshobson |
|
||||||
|
| `ui-animation` | Motion design — performance, accessibility, easing | mblode |
|
||||||
|
| `web-design-guidelines` | Web design principles and guidelines | vercel-labs |
|
||||||
|
|
||||||
|
### Backend & API (4)
|
||||||
|
|
||||||
|
| Skill | Purpose | Origin |
|
||||||
|
| --------------------------------- | ------------------------------------------------- | -------- |
|
||||||
|
| `nestjs-best-practices` | NestJS — 40 rules, 10 categories, priority-ranked | kadajett |
|
||||||
|
| `fastapi` | FastAPI + Pydantic v2 + async SQLAlchemy 2.0 | jezweb |
|
||||||
|
| `architecture-patterns` | Clean Architecture, Hexagonal, DDD | wshobson |
|
||||||
|
| `python-performance-optimization` | Profiling, memory, parallelization | wshobson |
|
||||||
|
|
||||||
|
### Authentication (5)
|
||||||
|
|
||||||
|
| Skill | Purpose | Origin |
|
||||||
|
| ------------------------------------------ | -------------------------------------------------- | ----------- |
|
||||||
|
| `better-auth-best-practices` | Better-Auth — Drizzle, sessions, plugins, security | better-auth |
|
||||||
|
| `create-auth-skill` | Creating custom Better-Auth skills | better-auth |
|
||||||
|
| `email-and-password-best-practices` | Email/password auth patterns | better-auth |
|
||||||
|
| `organization-best-practices` | Multi-org/team auth patterns | better-auth |
|
||||||
|
| `two-factor-authentication-best-practices` | 2FA implementation patterns | better-auth |
|
||||||
|
|
||||||
|
### AI & Agent Building (7)
|
||||||
|
|
||||||
|
| Skill | Purpose | Origin |
|
||||||
|
| ----------------------------- | --------------------------------------------------- | ---------------- |
|
||||||
|
| `ai-sdk` | Vercel AI SDK — streaming, multi-provider, agents | vercel/ai |
|
||||||
|
| `create-agent` | Modular agent with OpenRouter multi-model access | openrouterteam |
|
||||||
|
| `proactive-agent` | WAL Protocol, compaction recovery, self-improvement | halthelobster |
|
||||||
|
| `dispatching-parallel-agents` | Launching and managing parallel subagents | obra/superpowers |
|
||||||
|
| `subagent-driven-development` | Development workflow using subagents | obra/superpowers |
|
||||||
|
| `executing-plans` | Executing multi-step implementation plans | obra/superpowers |
|
||||||
|
| `using-superpowers` | Overview of the superpowers skill system | obra/superpowers |
|
||||||
|
|
||||||
|
### Development Workflow (6)
|
||||||
|
|
||||||
|
| Skill | Purpose | Origin |
|
||||||
|
| -------------------------------- | --------------------------------------- | ---------------- |
|
||||||
|
| `test-driven-development` | TDD Red-Green-Refactor discipline | obra/superpowers |
|
||||||
|
| `systematic-debugging` | Structured debugging methodology | obra/superpowers |
|
||||||
|
| `using-git-worktrees` | Git worktree patterns for parallel work | obra/superpowers |
|
||||||
|
| `finishing-a-development-branch` | Branch cleanup, squash, merge patterns | obra/superpowers |
|
||||||
|
| `writing-plans` | Writing effective implementation plans | obra/superpowers |
|
||||||
|
| `brainstorming` | Structured brainstorming methodology | obra/superpowers |
|
||||||
|
|
||||||
|
### Document Generation (6)
|
||||||
|
|
||||||
|
| Skill | Purpose | Origin |
|
||||||
|
| ----------------- | ---------------------------------- | ---------- |
|
||||||
|
| `pdf` | PDF document generation | anthropics |
|
||||||
|
| `docx` | Word document generation | anthropics |
|
||||||
|
| `pptx` | PowerPoint presentation generation | anthropics |
|
||||||
|
| `xlsx` | Excel spreadsheet generation | anthropics |
|
||||||
|
| `doc-coauthoring` | Collaborative document writing | anthropics |
|
||||||
|
| `internal-comms` | Internal communications drafting | anthropics |
|
||||||
|
|
||||||
|
### Design & Creative (7)
|
||||||
|
|
||||||
|
| Skill | Purpose | Origin |
|
||||||
|
| ----------------------- | --------------------------------------- | ---------- |
|
||||||
|
| `brand-guidelines` | Brand identity enforcement | anthropics |
|
||||||
|
| `frontend-design` | Frontend design patterns and principles | anthropics |
|
||||||
|
| `canvas-design` | Canvas/visual design patterns | anthropics |
|
||||||
|
| `algorithmic-art` | Generative/algorithmic art creation | anthropics |
|
||||||
|
| `theme-factory` | Theme generation and customization | anthropics |
|
||||||
|
| `slack-gif-creator` | Animated GIF creation for Slack | anthropics |
|
||||||
|
| `web-artifacts-builder` | Self-contained HTML artifact building | anthropics |
|
||||||
|
|
||||||
|
### Marketing & Business (25)
|
||||||
|
|
||||||
|
| Skill | Purpose | Origin |
|
||||||
|
| --------------------------- | --------------------------------------------- | ------------- |
|
||||||
|
| `marketing-ideas` | 139 ideas across 14 categories | coreyhaines31 |
|
||||||
|
| `pricing-strategy` | SaaS pricing — value metrics, tiers, research | coreyhaines31 |
|
||||||
|
| `programmatic-seo` | SEO at scale — templates, playbooks | coreyhaines31 |
|
||||||
|
| `competitor-alternatives` | Competitor comparison pages | coreyhaines31 |
|
||||||
|
| `referral-program` | Referral & affiliate programs | coreyhaines31 |
|
||||||
|
| `seo-audit` | Comprehensive SEO audit methodology | coreyhaines31 |
|
||||||
|
| `copywriting` | Marketing copywriting patterns | coreyhaines31 |
|
||||||
|
| `copy-editing` | Copy editing and proofreading | coreyhaines31 |
|
||||||
|
| `content-strategy` | Content strategy and planning | coreyhaines31 |
|
||||||
|
| `social-content` | Social media content creation | coreyhaines31 |
|
||||||
|
| `email-sequence` | Email sequence design and automation | coreyhaines31 |
|
||||||
|
| `launch-strategy` | Product launch planning | coreyhaines31 |
|
||||||
|
| `marketing-psychology` | Psychology-driven marketing | coreyhaines31 |
|
||||||
|
| `product-marketing-context` | Product marketing positioning | coreyhaines31 |
|
||||||
|
| `paid-ads` | Paid advertising campaigns | coreyhaines31 |
|
||||||
|
| `schema-markup` | Schema.org structured data | coreyhaines31 |
|
||||||
|
| `analytics-tracking` | Analytics setup and tracking | coreyhaines31 |
|
||||||
|
| `ab-test-setup` | A/B testing methodology | coreyhaines31 |
|
||||||
|
| `page-cro` | Landing page conversion optimization | coreyhaines31 |
|
||||||
|
| `form-cro` | Form conversion optimization | coreyhaines31 |
|
||||||
|
| `signup-flow-cro` | Signup flow conversion optimization | coreyhaines31 |
|
||||||
|
| `onboarding-cro` | User onboarding optimization | coreyhaines31 |
|
||||||
|
| `popup-cro` | Popup/modal conversion optimization | coreyhaines31 |
|
||||||
|
| `paywall-upgrade-cro` | Paywall/upgrade conversion optimization | coreyhaines31 |
|
||||||
|
| `free-tool-strategy` | Free tool as marketing strategy | coreyhaines31 |
|
||||||
|
|
||||||
|
### Vue/Vite Ecosystem (16)
|
||||||
|
|
||||||
|
| Skill | Purpose | Origin |
|
||||||
|
| ---------------------------- | ----------------------------------------- | ------ |
|
||||||
|
| `vue` | Vue.js development patterns | antfu |
|
||||||
|
| `vue-best-practices` | Vue.js best practices and conventions | antfu |
|
||||||
|
| `vue-router-best-practices` | Vue Router patterns and guards | antfu |
|
||||||
|
| `vue-testing-best-practices` | Vue component testing patterns | antfu |
|
||||||
|
| `vueuse-functions` | VueUse composable function patterns | antfu |
|
||||||
|
| `nuxt` | Nuxt.js framework patterns | antfu |
|
||||||
|
| `vite` | Vite build tool configuration and plugins | antfu |
|
||||||
|
| `vitest` | Vitest testing framework patterns | antfu |
|
||||||
|
| `vitepress` | VitePress documentation site patterns | antfu |
|
||||||
|
| `slidev` | Slidev presentation framework | antfu |
|
||||||
|
| `pnpm` | pnpm package manager patterns | antfu |
|
||||||
|
| `turborepo` | Turborepo monorepo patterns | antfu |
|
||||||
|
| `unocss` | UnoCSS atomic CSS engine | antfu |
|
||||||
|
| `tsdown` | tsdown TypeScript bundler | antfu |
|
||||||
|
| `pinia` | Pinia state management | antfu |
|
||||||
|
| `antfu` | Anthony Fu's coding conventions | antfu |
|
||||||
|
|
||||||
|
### Orchestration (1)
|
||||||
|
|
||||||
|
| Skill | Purpose | Origin |
|
||||||
|
| ----------- | ------------------------------------------------------------------------------------------ | ------------ |
|
||||||
|
| `kickstart` | Launch orchestrator for milestone/issue/task — auto-discovers context, bootstraps tracking | Mosaic Stack |
|
||||||
|
|
||||||
|
### Meta / Skill Authoring (4)
|
||||||
|
|
||||||
|
| Skill | Purpose | Origin |
|
||||||
|
| ---------------- | --------------------------------------------- | ---------------- |
|
||||||
|
| `writing-skills` | TDD-based skill authoring methodology | obra/superpowers |
|
||||||
|
| `skill-creator` | Anthropic's skill creation guide | anthropics |
|
||||||
|
| `mcp-builder` | Building MCP (Model Context Protocol) servers | anthropics |
|
||||||
|
| `webapp-testing` | Web application testing patterns | anthropics |
|
||||||
|
|
||||||
|
## Source Repositories
|
||||||
|
|
||||||
|
| Repository | Skills | Domain Focus |
|
||||||
|
| --------------------------------------------------------------------------------------------- | ------ | ---------------------------------------------- |
|
||||||
|
| [anthropics/skills](https://github.com/anthropics/skills) | 16 | Documents, design, MCP, testing |
|
||||||
|
| [obra/superpowers](https://github.com/obra/superpowers) | 14 | Agent workflows, TDD, code review, planning |
|
||||||
|
| [coreyhaines31/marketingskills](https://github.com/coreyhaines31/marketingskills) | 25 | Marketing, CRO, SEO, growth |
|
||||||
|
| [antfu/skills](https://github.com/antfu/skills) | 16 | Vue, Vite, Vitest, pnpm, Nuxt |
|
||||||
|
| [better-auth/skills](https://github.com/better-auth/skills) | 5 | Authentication patterns |
|
||||||
|
| [vercel-labs/agent-skills](https://github.com/vercel-labs/agent-skills) | 4 | React, design |
|
||||||
|
| [vercel-labs/next-skills](https://github.com/vercel-labs/next-skills) | 1 | Next.js 15+ |
|
||||||
|
| [vercel/ai](https://github.com/vercel/ai) | 1 | AI SDK |
|
||||||
|
| [halthelobster/proactive-agent](https://github.com/halthelobster/proactive-agent) | 1 | Agent architecture |
|
||||||
|
| [openrouterteam/agent-skills](https://github.com/openrouterteam/agent-skills) | 1 | Agent building |
|
||||||
|
| [kadajett/agent-nestjs-skills](https://github.com/kadajett/agent-nestjs-skills) | 1 | NestJS |
|
||||||
|
| [jezweb/claude-skills](https://github.com/jezweb/claude-skills) | 1 | FastAPI |
|
||||||
|
| [wshobson/agents](https://github.com/wshobson/agents) | 3 | Architecture, Python, Tailwind |
|
||||||
|
| [mblode/agent-skills](https://github.com/mblode/agent-skills) | 1 | UI animation |
|
||||||
|
| [giuseppe-trisciuoglio/developer-kit](https://github.com/giuseppe-trisciuoglio/developer-kit) | 1 | shadcn/ui |
|
||||||
|
| Mosaic Stack (original) | 4 | PR review, code review, orchestration, linting |
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
The skills ship with the framework package. The framework installer installs them
|
||||||
|
into `~/.config/mosaic/skills/`, and the post-install step links them into each
|
||||||
|
runtime's skill directory:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Install or upgrade the framework (skills arrive with it — no second repo)
|
||||||
|
./packages/mosaic/framework/install.sh
|
||||||
|
|
||||||
|
# Re-link installed skills into runtime homes (claude, codex, opencode, pi)
|
||||||
|
mosaic sync
|
||||||
|
```
|
||||||
|
|
||||||
|
Operators can override any canonical skill by copying it to
|
||||||
|
`~/.config/mosaic/skills-local/<name>/` — local skills take precedence during
|
||||||
|
linking.
|
||||||
|
|
||||||
|
## Adapting Skills
|
||||||
|
|
||||||
|
When adding skills from the community:
|
||||||
|
|
||||||
|
1. Replace raw `gh`/`tea` calls with our `~/.config/mosaic/rails/git/` scripts
|
||||||
|
2. Test on both GitHub and Gitea repos
|
||||||
|
3. Add Mosaic Stack context notes where upstream assumptions differ
|
||||||
|
4. Document any platform-specific limitations
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
Individual skills retain their original licenses. Adaptations are MIT.
|
||||||
@@ -0,0 +1,287 @@
|
|||||||
|
---
|
||||||
|
name: ab-test-setup
|
||||||
|
version: 1.0.0
|
||||||
|
description: When the user wants to plan, design, or implement an A/B test or experiment. Also use when the user mentions "A/B test," "split test," "experiment," "test this change," "variant copy," "multivariate test," or "hypothesis." For tracking implementation, see analytics-tracking.
|
||||||
|
---
|
||||||
|
|
||||||
|
# A/B Test Setup
|
||||||
|
|
||||||
|
You are an expert in experimentation and A/B testing. Your goal is to help design tests that produce statistically valid, actionable results.
|
||||||
|
|
||||||
|
## Initial Assessment
|
||||||
|
|
||||||
|
**Check for product marketing context first:**
|
||||||
|
If `.mosaic/product-marketing-context.md` exists, read it before asking questions. Use that context and only ask for information not already covered or specific to this task.
|
||||||
|
|
||||||
|
Before designing a test, understand:
|
||||||
|
|
||||||
|
1. **Test Context** - What are you trying to improve? What change are you considering?
|
||||||
|
2. **Current State** - Baseline conversion rate? Current traffic volume?
|
||||||
|
3. **Constraints** - Technical complexity? Timeline? Tools available?
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Core Principles
|
||||||
|
|
||||||
|
### 1. Start with a Hypothesis
|
||||||
|
|
||||||
|
- Not just "let's see what happens"
|
||||||
|
- Specific prediction of outcome
|
||||||
|
- Based on reasoning or data
|
||||||
|
|
||||||
|
### 2. Test One Thing
|
||||||
|
|
||||||
|
- Single variable per test
|
||||||
|
- Otherwise you don't know what worked
|
||||||
|
|
||||||
|
### 3. Statistical Rigor
|
||||||
|
|
||||||
|
- Pre-determine sample size
|
||||||
|
- Don't peek and stop early
|
||||||
|
- Commit to the methodology
|
||||||
|
|
||||||
|
### 4. Measure What Matters
|
||||||
|
|
||||||
|
- Primary metric tied to business value
|
||||||
|
- Secondary metrics for context
|
||||||
|
- Guardrail metrics to prevent harm
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Hypothesis Framework
|
||||||
|
|
||||||
|
### Structure
|
||||||
|
|
||||||
|
```
|
||||||
|
Because [observation/data],
|
||||||
|
we believe [change]
|
||||||
|
will cause [expected outcome]
|
||||||
|
for [audience].
|
||||||
|
We'll know this is true when [metrics].
|
||||||
|
```
|
||||||
|
|
||||||
|
### Example
|
||||||
|
|
||||||
|
**Weak**: "Changing the button color might increase clicks."
|
||||||
|
|
||||||
|
**Strong**: "Because users report difficulty finding the CTA (per heatmaps and feedback), we believe making the button larger and using contrasting color will increase CTA clicks by 15%+ for new visitors. We'll measure click-through rate from page view to signup start."
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Test Types
|
||||||
|
|
||||||
|
| Type | Description | Traffic Needed |
|
||||||
|
| --------- | -------------------------------- | -------------- |
|
||||||
|
| A/B | Two versions, single change | Moderate |
|
||||||
|
| A/B/n | Multiple variants | Higher |
|
||||||
|
| MVT | Multiple changes in combinations | Very high |
|
||||||
|
| Split URL | Different URLs for variants | Moderate |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Sample Size
|
||||||
|
|
||||||
|
### Quick Reference
|
||||||
|
|
||||||
|
| Baseline | 10% Lift | 20% Lift | 50% Lift |
|
||||||
|
| -------- | ------------ | ----------- | ------------ |
|
||||||
|
| 1% | 150k/variant | 39k/variant | 6k/variant |
|
||||||
|
| 3% | 47k/variant | 12k/variant | 2k/variant |
|
||||||
|
| 5% | 27k/variant | 7k/variant | 1.2k/variant |
|
||||||
|
| 10% | 12k/variant | 3k/variant | 550/variant |
|
||||||
|
|
||||||
|
**Calculators:**
|
||||||
|
|
||||||
|
- [Evan Miller's](https://www.evanmiller.org/ab-testing/sample-size.html)
|
||||||
|
- [Optimizely's](https://www.optimizely.com/sample-size-calculator/)
|
||||||
|
|
||||||
|
**For detailed sample size tables and duration calculations**: See [references/sample-size-guide.md](references/sample-size-guide.md)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Metrics Selection
|
||||||
|
|
||||||
|
### Primary Metric
|
||||||
|
|
||||||
|
- Single metric that matters most
|
||||||
|
- Directly tied to hypothesis
|
||||||
|
- What you'll use to call the test
|
||||||
|
|
||||||
|
### Secondary Metrics
|
||||||
|
|
||||||
|
- Support primary metric interpretation
|
||||||
|
- Explain why/how the change worked
|
||||||
|
|
||||||
|
### Guardrail Metrics
|
||||||
|
|
||||||
|
- Things that shouldn't get worse
|
||||||
|
- Stop test if significantly negative
|
||||||
|
|
||||||
|
### Example: Pricing Page Test
|
||||||
|
|
||||||
|
- **Primary**: Plan selection rate
|
||||||
|
- **Secondary**: Time on page, plan distribution
|
||||||
|
- **Guardrail**: Support tickets, refund rate
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Designing Variants
|
||||||
|
|
||||||
|
### What to Vary
|
||||||
|
|
||||||
|
| Category | Examples |
|
||||||
|
| -------------- | ------------------------------------------------- |
|
||||||
|
| Headlines/Copy | Message angle, value prop, specificity, tone |
|
||||||
|
| Visual Design | Layout, color, images, hierarchy |
|
||||||
|
| CTA | Button copy, size, placement, number |
|
||||||
|
| Content | Information included, order, amount, social proof |
|
||||||
|
|
||||||
|
### Best Practices
|
||||||
|
|
||||||
|
- Single, meaningful change
|
||||||
|
- Bold enough to make a difference
|
||||||
|
- True to the hypothesis
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Traffic Allocation
|
||||||
|
|
||||||
|
| Approach | Split | When to Use |
|
||||||
|
| ------------ | --------------------- | ------------------------- |
|
||||||
|
| Standard | 50/50 | Default for A/B |
|
||||||
|
| Conservative | 90/10, 80/20 | Limit risk of bad variant |
|
||||||
|
| Ramping | Start small, increase | Technical risk mitigation |
|
||||||
|
|
||||||
|
**Considerations:**
|
||||||
|
|
||||||
|
- Consistency: Users see same variant on return
|
||||||
|
- Balanced exposure across time of day/week
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Implementation
|
||||||
|
|
||||||
|
### Client-Side
|
||||||
|
|
||||||
|
- JavaScript modifies page after load
|
||||||
|
- Quick to implement, can cause flicker
|
||||||
|
- Tools: PostHog, Optimizely, VWO
|
||||||
|
|
||||||
|
### Server-Side
|
||||||
|
|
||||||
|
- Variant determined before render
|
||||||
|
- No flicker, requires dev work
|
||||||
|
- Tools: PostHog, LaunchDarkly, Split
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Running the Test
|
||||||
|
|
||||||
|
### Pre-Launch Checklist
|
||||||
|
|
||||||
|
- [ ] Hypothesis documented
|
||||||
|
- [ ] Primary metric defined
|
||||||
|
- [ ] Sample size calculated
|
||||||
|
- [ ] Variants implemented correctly
|
||||||
|
- [ ] Tracking verified
|
||||||
|
- [ ] QA completed on all variants
|
||||||
|
|
||||||
|
### During the Test
|
||||||
|
|
||||||
|
**DO:**
|
||||||
|
|
||||||
|
- Monitor for technical issues
|
||||||
|
- Check segment quality
|
||||||
|
- Document external factors
|
||||||
|
|
||||||
|
**DON'T:**
|
||||||
|
|
||||||
|
- Peek at results and stop early
|
||||||
|
- Make changes to variants
|
||||||
|
- Add traffic from new sources
|
||||||
|
|
||||||
|
### The Peeking Problem
|
||||||
|
|
||||||
|
Looking at results before reaching sample size and stopping early leads to false positives and wrong decisions. Pre-commit to sample size and trust the process.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Analyzing Results
|
||||||
|
|
||||||
|
### Statistical Significance
|
||||||
|
|
||||||
|
- 95% confidence = p-value < 0.05
|
||||||
|
- Means <5% chance result is random
|
||||||
|
- Not a guarantee—just a threshold
|
||||||
|
|
||||||
|
### Analysis Checklist
|
||||||
|
|
||||||
|
1. **Reach sample size?** If not, result is preliminary
|
||||||
|
2. **Statistically significant?** Check confidence intervals
|
||||||
|
3. **Effect size meaningful?** Compare to MDE, project impact
|
||||||
|
4. **Secondary metrics consistent?** Support the primary?
|
||||||
|
5. **Guardrail concerns?** Anything get worse?
|
||||||
|
6. **Segment differences?** Mobile vs. desktop? New vs. returning?
|
||||||
|
|
||||||
|
### Interpreting Results
|
||||||
|
|
||||||
|
| Result | Conclusion |
|
||||||
|
| ------------------------- | -------------------------------- |
|
||||||
|
| Significant winner | Implement variant |
|
||||||
|
| Significant loser | Keep control, learn why |
|
||||||
|
| No significant difference | Need more traffic or bolder test |
|
||||||
|
| Mixed signals | Dig deeper, maybe segment |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Documentation
|
||||||
|
|
||||||
|
Document every test with:
|
||||||
|
|
||||||
|
- Hypothesis
|
||||||
|
- Variants (with screenshots)
|
||||||
|
- Results (sample, metrics, significance)
|
||||||
|
- Decision and learnings
|
||||||
|
|
||||||
|
**For templates**: See [references/test-templates.md](references/test-templates.md)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Common Mistakes
|
||||||
|
|
||||||
|
### Test Design
|
||||||
|
|
||||||
|
- Testing too small a change (undetectable)
|
||||||
|
- Testing too many things (can't isolate)
|
||||||
|
- No clear hypothesis
|
||||||
|
|
||||||
|
### Execution
|
||||||
|
|
||||||
|
- Stopping early
|
||||||
|
- Changing things mid-test
|
||||||
|
- Not checking implementation
|
||||||
|
|
||||||
|
### Analysis
|
||||||
|
|
||||||
|
- Ignoring confidence intervals
|
||||||
|
- Cherry-picking segments
|
||||||
|
- Over-interpreting inconclusive results
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Task-Specific Questions
|
||||||
|
|
||||||
|
1. What's your current conversion rate?
|
||||||
|
2. How much traffic does this page get?
|
||||||
|
3. What change are you considering and why?
|
||||||
|
4. What's the smallest improvement worth detecting?
|
||||||
|
5. What tools do you have for testing?
|
||||||
|
6. Have you tested this area before?
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Related Skills
|
||||||
|
|
||||||
|
- **page-cro**: For generating test ideas based on CRO principles
|
||||||
|
- **analytics-tracking**: For setting up test measurement
|
||||||
|
- **copywriting**: For creating variant copy
|
||||||
@@ -0,0 +1,272 @@
|
|||||||
|
# Sample Size Guide
|
||||||
|
|
||||||
|
Reference for calculating sample sizes and test duration.
|
||||||
|
|
||||||
|
## Sample Size Fundamentals
|
||||||
|
|
||||||
|
### Required Inputs
|
||||||
|
|
||||||
|
1. **Baseline conversion rate**: Your current rate
|
||||||
|
2. **Minimum detectable effect (MDE)**: Smallest change worth detecting
|
||||||
|
3. **Statistical significance level**: Usually 95% (α = 0.05)
|
||||||
|
4. **Statistical power**: Usually 80% (β = 0.20)
|
||||||
|
|
||||||
|
### What These Mean
|
||||||
|
|
||||||
|
**Baseline conversion rate**: If your page converts at 5%, that's your baseline.
|
||||||
|
|
||||||
|
**MDE (Minimum Detectable Effect)**: The smallest improvement you care about detecting. Set this based on:
|
||||||
|
|
||||||
|
- Business impact (is a 5% lift meaningful?)
|
||||||
|
- Implementation cost (worth the effort?)
|
||||||
|
- Realistic expectations (what have past tests shown?)
|
||||||
|
|
||||||
|
**Statistical significance (95%)**: Means there's less than 5% chance the observed difference is due to random chance.
|
||||||
|
|
||||||
|
**Statistical power (80%)**: Means if there's a real effect of size MDE, you have 80% chance of detecting it.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Sample Size Quick Reference Tables
|
||||||
|
|
||||||
|
### Conversion Rate: 1%
|
||||||
|
|
||||||
|
| Lift to Detect | Sample per Variant | Total Sample |
|
||||||
|
| --------------- | ------------------ | ------------ |
|
||||||
|
| 5% (1% → 1.05%) | 1,500,000 | 3,000,000 |
|
||||||
|
| 10% (1% → 1.1%) | 380,000 | 760,000 |
|
||||||
|
| 20% (1% → 1.2%) | 97,000 | 194,000 |
|
||||||
|
| 50% (1% → 1.5%) | 16,000 | 32,000 |
|
||||||
|
| 100% (1% → 2%) | 4,200 | 8,400 |
|
||||||
|
|
||||||
|
### Conversion Rate: 3%
|
||||||
|
|
||||||
|
| Lift to Detect | Sample per Variant | Total Sample |
|
||||||
|
| --------------- | ------------------ | ------------ |
|
||||||
|
| 5% (3% → 3.15%) | 480,000 | 960,000 |
|
||||||
|
| 10% (3% → 3.3%) | 120,000 | 240,000 |
|
||||||
|
| 20% (3% → 3.6%) | 31,000 | 62,000 |
|
||||||
|
| 50% (3% → 4.5%) | 5,200 | 10,400 |
|
||||||
|
| 100% (3% → 6%) | 1,400 | 2,800 |
|
||||||
|
|
||||||
|
### Conversion Rate: 5%
|
||||||
|
|
||||||
|
| Lift to Detect | Sample per Variant | Total Sample |
|
||||||
|
| --------------- | ------------------ | ------------ |
|
||||||
|
| 5% (5% → 5.25%) | 280,000 | 560,000 |
|
||||||
|
| 10% (5% → 5.5%) | 72,000 | 144,000 |
|
||||||
|
| 20% (5% → 6%) | 18,000 | 36,000 |
|
||||||
|
| 50% (5% → 7.5%) | 3,100 | 6,200 |
|
||||||
|
| 100% (5% → 10%) | 810 | 1,620 |
|
||||||
|
|
||||||
|
### Conversion Rate: 10%
|
||||||
|
|
||||||
|
| Lift to Detect | Sample per Variant | Total Sample |
|
||||||
|
| ---------------- | ------------------ | ------------ |
|
||||||
|
| 5% (10% → 10.5%) | 130,000 | 260,000 |
|
||||||
|
| 10% (10% → 11%) | 34,000 | 68,000 |
|
||||||
|
| 20% (10% → 12%) | 8,700 | 17,400 |
|
||||||
|
| 50% (10% → 15%) | 1,500 | 3,000 |
|
||||||
|
| 100% (10% → 20%) | 400 | 800 |
|
||||||
|
|
||||||
|
### Conversion Rate: 20%
|
||||||
|
|
||||||
|
| Lift to Detect | Sample per Variant | Total Sample |
|
||||||
|
| ---------------- | ------------------ | ------------ |
|
||||||
|
| 5% (20% → 21%) | 60,000 | 120,000 |
|
||||||
|
| 10% (20% → 22%) | 16,000 | 32,000 |
|
||||||
|
| 20% (20% → 24%) | 4,000 | 8,000 |
|
||||||
|
| 50% (20% → 30%) | 700 | 1,400 |
|
||||||
|
| 100% (20% → 40%) | 200 | 400 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Duration Calculator
|
||||||
|
|
||||||
|
### Formula
|
||||||
|
|
||||||
|
```
|
||||||
|
Duration (days) = (Sample per variant × Number of variants) / (Daily traffic × % exposed)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Examples
|
||||||
|
|
||||||
|
**Scenario 1: High-traffic page**
|
||||||
|
|
||||||
|
- Need: 10,000 per variant (2 variants = 20,000 total)
|
||||||
|
- Daily traffic: 5,000 visitors
|
||||||
|
- 100% exposed to test
|
||||||
|
- Duration: 20,000 / 5,000 = **4 days**
|
||||||
|
|
||||||
|
**Scenario 2: Medium-traffic page**
|
||||||
|
|
||||||
|
- Need: 30,000 per variant (60,000 total)
|
||||||
|
- Daily traffic: 2,000 visitors
|
||||||
|
- 100% exposed
|
||||||
|
- Duration: 60,000 / 2,000 = **30 days**
|
||||||
|
|
||||||
|
**Scenario 3: Low-traffic with partial exposure**
|
||||||
|
|
||||||
|
- Need: 15,000 per variant (30,000 total)
|
||||||
|
- Daily traffic: 500 visitors
|
||||||
|
- 50% exposed to test
|
||||||
|
- Effective daily: 250
|
||||||
|
- Duration: 30,000 / 250 = **120 days** (too long!)
|
||||||
|
|
||||||
|
### Minimum Duration Rules
|
||||||
|
|
||||||
|
Even with sufficient sample size, run tests for at least:
|
||||||
|
|
||||||
|
- **1 full week**: To capture day-of-week variation
|
||||||
|
- **2 business cycles**: If B2B (weekday vs. weekend patterns)
|
||||||
|
- **Through paydays**: If e-commerce (beginning/end of month)
|
||||||
|
|
||||||
|
### Maximum Duration Guidelines
|
||||||
|
|
||||||
|
Avoid running tests longer than 4-8 weeks:
|
||||||
|
|
||||||
|
- Novelty effects wear off
|
||||||
|
- External factors intervene
|
||||||
|
- Opportunity cost of other tests
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Online Calculators
|
||||||
|
|
||||||
|
### Recommended Tools
|
||||||
|
|
||||||
|
**Evan Miller's Calculator**
|
||||||
|
https://www.evanmiller.org/ab-testing/sample-size.html
|
||||||
|
|
||||||
|
- Simple interface
|
||||||
|
- Bookmark-worthy
|
||||||
|
|
||||||
|
**Optimizely's Calculator**
|
||||||
|
https://www.optimizely.com/sample-size-calculator/
|
||||||
|
|
||||||
|
- Business-friendly language
|
||||||
|
- Duration estimates
|
||||||
|
|
||||||
|
**AB Test Guide Calculator**
|
||||||
|
https://www.abtestguide.com/calc/
|
||||||
|
|
||||||
|
- Includes Bayesian option
|
||||||
|
- Multiple test types
|
||||||
|
|
||||||
|
**VWO Duration Calculator**
|
||||||
|
https://vwo.com/tools/ab-test-duration-calculator/
|
||||||
|
|
||||||
|
- Duration-focused
|
||||||
|
- Good for planning
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Adjusting for Multiple Variants
|
||||||
|
|
||||||
|
With more than 2 variants (A/B/n tests), you need more sample:
|
||||||
|
|
||||||
|
| Variants | Multiplier |
|
||||||
|
| ----------- | -------------------------- |
|
||||||
|
| 2 (A/B) | 1x |
|
||||||
|
| 3 (A/B/C) | ~1.5x |
|
||||||
|
| 4 (A/B/C/D) | ~2x |
|
||||||
|
| 5+ | Consider reducing variants |
|
||||||
|
|
||||||
|
**Why?** More comparisons increase chance of false positives. You're comparing:
|
||||||
|
|
||||||
|
- A vs B
|
||||||
|
- A vs C
|
||||||
|
- B vs C (sometimes)
|
||||||
|
|
||||||
|
Apply Bonferroni correction or use tools that handle this automatically.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Common Sample Size Mistakes
|
||||||
|
|
||||||
|
### 1. Underpowered tests
|
||||||
|
|
||||||
|
**Problem**: Not enough sample to detect realistic effects
|
||||||
|
**Fix**: Be realistic about MDE, get more traffic, or don't test
|
||||||
|
|
||||||
|
### 2. Overpowered tests
|
||||||
|
|
||||||
|
**Problem**: Waiting for sample size when you already have significance
|
||||||
|
**Fix**: This is actually fine—you committed to sample size, honor it
|
||||||
|
|
||||||
|
### 3. Wrong baseline rate
|
||||||
|
|
||||||
|
**Problem**: Using wrong conversion rate for calculation
|
||||||
|
**Fix**: Use the specific metric and page, not site-wide averages
|
||||||
|
|
||||||
|
### 4. Ignoring segments
|
||||||
|
|
||||||
|
**Problem**: Calculating for full traffic, then analyzing segments
|
||||||
|
**Fix**: If you plan segment analysis, calculate sample for smallest segment
|
||||||
|
|
||||||
|
### 5. Testing too many things
|
||||||
|
|
||||||
|
**Problem**: Dividing traffic too many ways
|
||||||
|
**Fix**: Prioritize ruthlessly, run fewer concurrent tests
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## When Sample Size Requirements Are Too High
|
||||||
|
|
||||||
|
Options when you can't get enough traffic:
|
||||||
|
|
||||||
|
1. **Increase MDE**: Accept only detecting larger effects (20%+ lift)
|
||||||
|
2. **Lower confidence**: Use 90% instead of 95% (risky, document it)
|
||||||
|
3. **Reduce variants**: Test only the most promising variant
|
||||||
|
4. **Combine traffic**: Test across multiple similar pages
|
||||||
|
5. **Test upstream**: Test earlier in funnel where traffic is higher
|
||||||
|
6. **Don't test**: Make decision based on qualitative data instead
|
||||||
|
7. **Longer test**: Accept longer duration (weeks/months)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Sequential Testing
|
||||||
|
|
||||||
|
If you must check results before reaching sample size:
|
||||||
|
|
||||||
|
### What is it?
|
||||||
|
|
||||||
|
Statistical method that adjusts for multiple looks at data.
|
||||||
|
|
||||||
|
### When to use
|
||||||
|
|
||||||
|
- High-risk changes
|
||||||
|
- Need to stop bad variants early
|
||||||
|
- Time-sensitive decisions
|
||||||
|
|
||||||
|
### Tools that support it
|
||||||
|
|
||||||
|
- Optimizely (Stats Accelerator)
|
||||||
|
- VWO (SmartStats)
|
||||||
|
- PostHog (Bayesian approach)
|
||||||
|
|
||||||
|
### Tradeoff
|
||||||
|
|
||||||
|
- More flexibility to stop early
|
||||||
|
- Slightly larger sample size requirement
|
||||||
|
- More complex analysis
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Quick Decision Framework
|
||||||
|
|
||||||
|
### Can I run this test?
|
||||||
|
|
||||||
|
```
|
||||||
|
Daily traffic to page: _____
|
||||||
|
Baseline conversion rate: _____
|
||||||
|
MDE I care about: _____
|
||||||
|
|
||||||
|
Sample needed per variant: _____ (from tables above)
|
||||||
|
Days to run: Sample / Daily traffic = _____
|
||||||
|
|
||||||
|
If days > 60: Consider alternatives
|
||||||
|
If days > 30: Acceptable for high-impact tests
|
||||||
|
If days < 14: Likely feasible
|
||||||
|
If days < 7: Easy to run, consider running longer anyway
|
||||||
|
```
|
||||||
@@ -0,0 +1,292 @@
|
|||||||
|
# A/B Test Templates Reference
|
||||||
|
|
||||||
|
Templates for planning, documenting, and analyzing experiments.
|
||||||
|
|
||||||
|
## Test Plan Template
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
# A/B Test: [Name]
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
- **Owner**: [Name]
|
||||||
|
- **Test ID**: [ID in testing tool]
|
||||||
|
- **Page/Feature**: [What's being tested]
|
||||||
|
- **Planned dates**: [Start] - [End]
|
||||||
|
|
||||||
|
## Hypothesis
|
||||||
|
|
||||||
|
Because [observation/data],
|
||||||
|
we believe [change]
|
||||||
|
will cause [expected outcome]
|
||||||
|
for [audience].
|
||||||
|
We'll know this is true when [metrics].
|
||||||
|
|
||||||
|
## Test Design
|
||||||
|
|
||||||
|
| Element | Details |
|
||||||
|
| ------------------ | ------------------------- |
|
||||||
|
| Test type | A/B / A/B/n / MVT |
|
||||||
|
| Duration | X weeks |
|
||||||
|
| Sample size | X per variant |
|
||||||
|
| Traffic allocation | 50/50 |
|
||||||
|
| Tool | [Tool name] |
|
||||||
|
| Implementation | Client-side / Server-side |
|
||||||
|
|
||||||
|
## Variants
|
||||||
|
|
||||||
|
### Control (A)
|
||||||
|
|
||||||
|
[Screenshot]
|
||||||
|
|
||||||
|
- Current experience
|
||||||
|
- [Key details about current state]
|
||||||
|
|
||||||
|
### Variant (B)
|
||||||
|
|
||||||
|
[Screenshot or mockup]
|
||||||
|
|
||||||
|
- [Specific change #1]
|
||||||
|
- [Specific change #2]
|
||||||
|
- Rationale: [Why we think this will win]
|
||||||
|
|
||||||
|
## Metrics
|
||||||
|
|
||||||
|
### Primary
|
||||||
|
|
||||||
|
- **Metric**: [metric name]
|
||||||
|
- **Definition**: [how it's calculated]
|
||||||
|
- **Current baseline**: [X%]
|
||||||
|
- **Minimum detectable effect**: [X%]
|
||||||
|
|
||||||
|
### Secondary
|
||||||
|
|
||||||
|
- [Metric 1]: [what it tells us]
|
||||||
|
- [Metric 2]: [what it tells us]
|
||||||
|
- [Metric 3]: [what it tells us]
|
||||||
|
|
||||||
|
### Guardrails
|
||||||
|
|
||||||
|
- [Metric that shouldn't get worse]
|
||||||
|
- [Another safety metric]
|
||||||
|
|
||||||
|
## Segment Analysis Plan
|
||||||
|
|
||||||
|
- Mobile vs. desktop
|
||||||
|
- New vs. returning visitors
|
||||||
|
- Traffic source
|
||||||
|
- [Other relevant segments]
|
||||||
|
|
||||||
|
## Success Criteria
|
||||||
|
|
||||||
|
- Winner: [Primary metric improves by X% with 95% confidence]
|
||||||
|
- Loser: [Primary metric decreases significantly]
|
||||||
|
- Inconclusive: [What we'll do if no significant result]
|
||||||
|
|
||||||
|
## Pre-Launch Checklist
|
||||||
|
|
||||||
|
- [ ] Hypothesis documented and reviewed
|
||||||
|
- [ ] Primary metric defined and trackable
|
||||||
|
- [ ] Sample size calculated
|
||||||
|
- [ ] Test duration estimated
|
||||||
|
- [ ] Variants implemented correctly
|
||||||
|
- [ ] Tracking verified in all variants
|
||||||
|
- [ ] QA completed on all variants
|
||||||
|
- [ ] Stakeholders informed
|
||||||
|
- [ ] Calendar hold for analysis date
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Results Documentation Template
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
# A/B Test Results: [Name]
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
|
||||||
|
| Element | Value |
|
||||||
|
| -------- | ----------------------------- |
|
||||||
|
| Test ID | [ID] |
|
||||||
|
| Dates | [Start] - [End] |
|
||||||
|
| Duration | X days |
|
||||||
|
| Result | Winner / Loser / Inconclusive |
|
||||||
|
| Decision | [What we're doing] |
|
||||||
|
|
||||||
|
## Hypothesis (Reminder)
|
||||||
|
|
||||||
|
[Copy from test plan]
|
||||||
|
|
||||||
|
## Results
|
||||||
|
|
||||||
|
### Sample Size
|
||||||
|
|
||||||
|
| Variant | Target | Actual | % of target |
|
||||||
|
| ------- | ------ | ------ | ----------- |
|
||||||
|
| Control | X | Y | Z% |
|
||||||
|
| Variant | X | Y | Z% |
|
||||||
|
|
||||||
|
### Primary Metric: [Metric Name]
|
||||||
|
|
||||||
|
| Variant | Value | 95% CI | vs. Control |
|
||||||
|
| ------- | ----- | -------- | ----------- |
|
||||||
|
| Control | X% | [X%, Y%] | — |
|
||||||
|
| Variant | X% | [X%, Y%] | +X% |
|
||||||
|
|
||||||
|
**Statistical significance**: p = X.XX (95% = sig / not sig)
|
||||||
|
**Practical significance**: [Is this lift meaningful for the business?]
|
||||||
|
|
||||||
|
### Secondary Metrics
|
||||||
|
|
||||||
|
| Metric | Control | Variant | Change | Significant? |
|
||||||
|
| ---------- | ------- | ------- | ------ | ------------ |
|
||||||
|
| [Metric 1] | X | Y | +Z% | Yes/No |
|
||||||
|
| [Metric 2] | X | Y | +Z% | Yes/No |
|
||||||
|
|
||||||
|
### Guardrail Metrics
|
||||||
|
|
||||||
|
| Metric | Control | Variant | Change | Concern? |
|
||||||
|
| ---------- | ------- | ------- | ------ | -------- |
|
||||||
|
| [Metric 1] | X | Y | +Z% | Yes/No |
|
||||||
|
|
||||||
|
### Segment Analysis
|
||||||
|
|
||||||
|
**Mobile vs. Desktop**
|
||||||
|
| Segment | Control | Variant | Lift |
|
||||||
|
|---------|---------|---------|------|
|
||||||
|
| Mobile | X% | Y% | +Z% |
|
||||||
|
| Desktop | X% | Y% | +Z% |
|
||||||
|
|
||||||
|
**New vs. Returning**
|
||||||
|
| Segment | Control | Variant | Lift |
|
||||||
|
|---------|---------|---------|------|
|
||||||
|
| New | X% | Y% | +Z% |
|
||||||
|
| Returning | X% | Y% | +Z% |
|
||||||
|
|
||||||
|
## Interpretation
|
||||||
|
|
||||||
|
### What happened?
|
||||||
|
|
||||||
|
[Explanation of results in plain language]
|
||||||
|
|
||||||
|
### Why do we think this happened?
|
||||||
|
|
||||||
|
[Analysis and reasoning]
|
||||||
|
|
||||||
|
### Caveats
|
||||||
|
|
||||||
|
[Any limitations, external factors, or concerns]
|
||||||
|
|
||||||
|
## Decision
|
||||||
|
|
||||||
|
**Winner**: [Control / Variant]
|
||||||
|
|
||||||
|
**Action**: [Implement variant / Keep control / Re-test]
|
||||||
|
|
||||||
|
**Timeline**: [When changes will be implemented]
|
||||||
|
|
||||||
|
## Learnings
|
||||||
|
|
||||||
|
### What we learned
|
||||||
|
|
||||||
|
- [Key insight 1]
|
||||||
|
- [Key insight 2]
|
||||||
|
|
||||||
|
### What to test next
|
||||||
|
|
||||||
|
- [Follow-up test idea 1]
|
||||||
|
- [Follow-up test idea 2]
|
||||||
|
|
||||||
|
### Impact
|
||||||
|
|
||||||
|
- **Projected lift**: [X% improvement in Y metric]
|
||||||
|
- **Business impact**: [Revenue, conversions, etc.]
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Test Repository Entry Template
|
||||||
|
|
||||||
|
For tracking all tests in a central location:
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
| Test ID | Name | Page | Dates | Primary Metric | Result | Lift | Link |
|
||||||
|
| ------- | -------------------- | -------- | --------- | -------------- | ------------ | ---- | ------ |
|
||||||
|
| 001 | Hero headline test | Homepage | 1/1-1/15 | CTR | Winner | +12% | [Link] |
|
||||||
|
| 002 | Pricing table layout | Pricing | 1/10-1/31 | Plan selection | Loser | -5% | [Link] |
|
||||||
|
| 003 | Signup form fields | Signup | 2/1-2/14 | Completion | Inconclusive | +2% | [Link] |
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Quick Test Brief Template
|
||||||
|
|
||||||
|
For simple tests that don't need full documentation:
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
## [Test Name]
|
||||||
|
|
||||||
|
**What**: [One sentence description]
|
||||||
|
**Why**: [One sentence hypothesis]
|
||||||
|
**Metric**: [Primary metric]
|
||||||
|
**Duration**: [X weeks]
|
||||||
|
**Result**: [TBD / Winner / Loser / Inconclusive]
|
||||||
|
**Learnings**: [Key takeaway]
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Stakeholder Update Template
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
## A/B Test Update: [Name]
|
||||||
|
|
||||||
|
**Status**: Running / Complete
|
||||||
|
**Days remaining**: X (or complete)
|
||||||
|
**Current sample**: X% of target
|
||||||
|
|
||||||
|
### Preliminary observations
|
||||||
|
|
||||||
|
[What we're seeing - without making decisions yet]
|
||||||
|
|
||||||
|
### Next steps
|
||||||
|
|
||||||
|
[What happens next]
|
||||||
|
|
||||||
|
### Timeline
|
||||||
|
|
||||||
|
- [Date]: Analysis complete
|
||||||
|
- [Date]: Decision and recommendation
|
||||||
|
- [Date]: Implementation 'if winner'
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Experiment Prioritization Scorecard
|
||||||
|
|
||||||
|
For deciding which tests to run:
|
||||||
|
|
||||||
|
| Factor | Weight | Test A | Test B | Test C |
|
||||||
|
| ------------------------ | ------ | ------ | ------ | ------ |
|
||||||
|
| Potential impact | 30% | | | |
|
||||||
|
| Confidence in hypothesis | 25% | | | |
|
||||||
|
| Ease of implementation | 20% | | | |
|
||||||
|
| Risk if wrong | 15% | | | |
|
||||||
|
| Strategic alignment | 10% | | | |
|
||||||
|
| **Total** | | | | |
|
||||||
|
|
||||||
|
Scoring: 1-5 (5 = best)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Hypothesis Bank Template
|
||||||
|
|
||||||
|
For collecting test ideas:
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
| ID | Page/Area | Observation | Hypothesis | Potential Impact | Status |
|
||||||
|
| --- | --------- | ------------------- | ------------------------------------- | ---------------- | ------- |
|
||||||
|
| H1 | Homepage | Low scroll depth | Shorter hero will increase scroll | High | Testing |
|
||||||
|
| H2 | Pricing | Users compare plans | Comparison table will help | Medium | Backlog |
|
||||||
|
| H3 | Signup | Drop-off at email | Social login will increase completion | Medium | Backlog |
|
||||||
|
```
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user