Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f3e1a761aa | ||
|
|
54adbd2b3d | ||
|
|
311b4dda59 |
@@ -1,106 +0,0 @@
|
||||
import { RequestMethod, type Type } from '@nestjs/common';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { AppModule } from '../app.module.js';
|
||||
import { HierarchyModule } from '../hierarchy/hierarchy.module.js';
|
||||
|
||||
/**
|
||||
* Hierarchy route-inventory baseline (contract 1 §6.3(a)).
|
||||
*
|
||||
* M4-1b-i ships the audit event + outbox machinery with NO mutation routes:
|
||||
* the hierarchy command family (controllers + DTOs) lands in M4-1b-ii once
|
||||
* contract 2 merges. This witness enumerates every route the AppModule graph
|
||||
* declares and pins that baseline, so a hierarchy route appearing before its
|
||||
* command-family witnesses exist fails here first. When M4-1b-ii lands, this
|
||||
* baseline is replaced by an exact inventory of the command family.
|
||||
*/
|
||||
|
||||
interface RouteEntry {
|
||||
method: string;
|
||||
path: string;
|
||||
controller: string;
|
||||
}
|
||||
|
||||
/** Module-metadata entry: a module class or a DynamicModule-shaped object. */
|
||||
type ModuleEntry =
|
||||
| Type<unknown>
|
||||
| { module: Type<unknown>; imports?: unknown[]; controllers?: Type<unknown>[] };
|
||||
|
||||
function collectControllers(root: ModuleEntry): Type<unknown>[] {
|
||||
const visited = new Set<unknown>();
|
||||
const controllers: Type<unknown>[] = [];
|
||||
const walk = (entry: ModuleEntry | undefined | null): void => {
|
||||
if (!entry || visited.has(entry)) return;
|
||||
visited.add(entry);
|
||||
const moduleClass = typeof entry === 'function' ? entry : entry.module;
|
||||
// Entries with no resolvable class (forwardRef wrappers, async dynamic
|
||||
// modules) carry no decorator metadata to read here.
|
||||
if (typeof moduleClass !== 'function') return;
|
||||
if (visited.has(moduleClass) && typeof entry !== 'function') return;
|
||||
visited.add(moduleClass);
|
||||
// 'controllers' / 'imports' are the metadata keys the @Module decorator writes.
|
||||
const declared = (Reflect.getMetadata('controllers', moduleClass) ?? []) as Type<unknown>[];
|
||||
controllers.push(...declared);
|
||||
if (typeof entry !== 'function' && entry.controllers) controllers.push(...entry.controllers);
|
||||
const imports = [
|
||||
...((Reflect.getMetadata('imports', moduleClass) ?? []) as ModuleEntry[]),
|
||||
...(typeof entry !== 'function' ? ((entry.imports ?? []) as ModuleEntry[]) : []),
|
||||
];
|
||||
for (const imported of imports) walk(imported);
|
||||
};
|
||||
walk(root);
|
||||
return controllers;
|
||||
}
|
||||
|
||||
function routesOf(controller: Type<unknown>): RouteEntry[] {
|
||||
// 'path' on the class is the @Controller prefix; 'path'/'method' on a
|
||||
// handler are written by the @Get/@Post/... route decorators.
|
||||
const base = (Reflect.getMetadata('path', controller) ?? '') as string | string[];
|
||||
const bases = Array.isArray(base) ? base : [base];
|
||||
const routes: RouteEntry[] = [];
|
||||
const prototype = controller.prototype as Record<string, unknown>;
|
||||
for (const name of Object.getOwnPropertyNames(prototype)) {
|
||||
if (name === 'constructor') continue;
|
||||
const handler = Object.getOwnPropertyDescriptor(prototype, name)?.value;
|
||||
if (typeof handler !== 'function') continue;
|
||||
const method = Reflect.getMetadata('method', handler) as number | undefined;
|
||||
if (method === undefined) continue;
|
||||
const sub = (Reflect.getMetadata('path', handler) ?? '/') as string;
|
||||
for (const prefix of bases) {
|
||||
const path = `/${prefix}/${sub}`.replace(/\/+/g, '/').replace(/(.)\/$/, '$1');
|
||||
routes.push({
|
||||
method: RequestMethod[method] ?? String(method),
|
||||
path,
|
||||
controller: controller.name,
|
||||
});
|
||||
}
|
||||
}
|
||||
return routes;
|
||||
}
|
||||
|
||||
describe('hierarchy route-inventory baseline (§6.3(a))', () => {
|
||||
const inventory = collectControllers(AppModule).flatMap(routesOf);
|
||||
|
||||
it('control: the enumeration sees the known route surface', () => {
|
||||
const paths = inventory.map((r) => `${r.method} ${r.path}`);
|
||||
expect(paths).toContain('GET /health');
|
||||
expect(paths).toContain('POST /api/workspaces');
|
||||
expect(paths).toContain('GET /api/teams');
|
||||
expect(inventory.length).toBeGreaterThan(20);
|
||||
});
|
||||
|
||||
it('declares zero hierarchy mutation routes before M4-1b-ii', () => {
|
||||
const hierarchyRoutes = inventory.filter((r) =>
|
||||
/hierarch|compan|estate|platform[-_]?project/i.test(r.path),
|
||||
);
|
||||
expect(
|
||||
hierarchyRoutes,
|
||||
'a hierarchy route landed without replacing the §6.3(a) baseline with a command-family inventory',
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it('HierarchyModule itself declares no controllers', () => {
|
||||
expect((Reflect.getMetadata('controllers', HierarchyModule) ?? []) as unknown[]).toEqual([]);
|
||||
const hierarchyControllers = collectControllers(HierarchyModule);
|
||||
expect(hierarchyControllers).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -24,7 +24,6 @@ import { GCModule } from './gc/gc.module.js';
|
||||
import { HarnessModule } from './harness/harness.module.js';
|
||||
import { ReloadModule } from './reload/reload.module.js';
|
||||
import { WorkspaceModule } from './workspace/workspace.module.js';
|
||||
import { HierarchyModule } from './hierarchy/hierarchy.module.js';
|
||||
import { QueueModule } from './queue/queue.module.js';
|
||||
import { FederationModule } from './federation/federation.module.js';
|
||||
import { ThrottlerGuard, ThrottlerModule } from '@nestjs/throttler';
|
||||
@@ -66,7 +65,6 @@ const federationEnabled = loadConfig(resolveGatewayConfigPath()).tier === 'feder
|
||||
QueueModule,
|
||||
ReloadModule,
|
||||
WorkspaceModule,
|
||||
HierarchyModule,
|
||||
...(federationEnabled ? [FederationModule] : []),
|
||||
],
|
||||
controllers: [HealthController],
|
||||
|
||||
@@ -1,247 +0,0 @@
|
||||
import { mkdtemp, rm } from 'node:fs/promises';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||
import { Test, type TestingModule } from '@nestjs/testing';
|
||||
import {
|
||||
companies,
|
||||
createPgliteDb,
|
||||
eq,
|
||||
estates,
|
||||
hierarchyAuditEvents,
|
||||
hierarchyOutbox,
|
||||
platformProjects,
|
||||
runPgliteMigrations,
|
||||
type DbHandle,
|
||||
} from '@mosaicstack/db';
|
||||
import { DB } from '../database/database.module.js';
|
||||
import {
|
||||
HierarchyAuditIdempotencyConflictError,
|
||||
HierarchyAuditRepository,
|
||||
HierarchyNodeNotFoundError,
|
||||
type AppendHierarchyEventInput,
|
||||
} from './hierarchy-audit.repository.js';
|
||||
|
||||
/**
|
||||
* Repository-level §6.4 witnesses for the hierarchy audit machinery
|
||||
* (contract 1 §5.2, REQ-AUD-001): same-transaction atomicity of state +
|
||||
* event + outbox, rollback leaving no residue, idempotent replay, snapshot
|
||||
* parent chains, events surviving target deletion, per-target ordering, and
|
||||
* the outbox claim/complete/release CAS. The schema-level constraints are
|
||||
* witnessed in packages/db/src/hierarchy-audit.witness.test.ts.
|
||||
*/
|
||||
describe('hierarchy audit repository integration', (): void => {
|
||||
let dataDir: string;
|
||||
let handle: DbHandle;
|
||||
let moduleRef: TestingModule;
|
||||
let repo: HierarchyAuditRepository;
|
||||
|
||||
const input = (
|
||||
overrides: Partial<AppendHierarchyEventInput> = {},
|
||||
): AppendHierarchyEventInput => ({
|
||||
actorId: 'user-actor',
|
||||
verb: 'create',
|
||||
targetKind: 'company',
|
||||
targetId: randomUUID(),
|
||||
targetSnapshot: { id: 'x', slug: 'x', name: 'x', parentChain: [] },
|
||||
correlationId: 'corr-1',
|
||||
idempotencyKey: `key-${randomUUID()}`,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
beforeAll(async (): Promise<void> => {
|
||||
dataDir = await mkdtemp(join(tmpdir(), 'mosaic-gateway-hierarchy-audit-'));
|
||||
handle = createPgliteDb(dataDir);
|
||||
await runPgliteMigrations(handle);
|
||||
moduleRef = await Test.createTestingModule({
|
||||
providers: [HierarchyAuditRepository, { provide: DB, useValue: handle.db }],
|
||||
}).compile();
|
||||
repo = moduleRef.get(HierarchyAuditRepository);
|
||||
});
|
||||
|
||||
afterAll(async (): Promise<void> => {
|
||||
await moduleRef.close();
|
||||
await handle.close();
|
||||
await rm(dataDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('commits state, event, and outbox record atomically in one transaction', async () => {
|
||||
const companyId = randomUUID();
|
||||
const key = `key-${randomUUID()}`;
|
||||
await handle.db.transaction(async (tx) => {
|
||||
await tx.insert(companies).values({ id: companyId, name: 'Atomic Co', slug: 'atomic-co' });
|
||||
const snapshot = await repo.snapshot(tx, 'company', companyId);
|
||||
const result = await repo.append(tx, {
|
||||
...input({ targetId: companyId, idempotencyKey: key }),
|
||||
targetSnapshot: { ...snapshot },
|
||||
});
|
||||
expect(result.replayed).toBe(false);
|
||||
expect(result.event.idempotencyKey).toBe(key);
|
||||
});
|
||||
const events = await handle.db
|
||||
.select()
|
||||
.from(hierarchyAuditEvents)
|
||||
.where(eq(hierarchyAuditEvents.idempotencyKey, key));
|
||||
expect(events).toHaveLength(1);
|
||||
const outbox = await handle.db
|
||||
.select()
|
||||
.from(hierarchyOutbox)
|
||||
.where(eq(hierarchyOutbox.eventId, events[0]!.id));
|
||||
expect(outbox).toHaveLength(1);
|
||||
expect(outbox[0]).toMatchObject({
|
||||
status: 'pending',
|
||||
idempotencyKey: key,
|
||||
correlationId: 'corr-1',
|
||||
});
|
||||
});
|
||||
|
||||
it('a rolled-back transaction leaves no state, no event, and no outbox record', async () => {
|
||||
const companyId = randomUUID();
|
||||
const key = `key-${randomUUID()}`;
|
||||
await expect(
|
||||
handle.db.transaction(async (tx) => {
|
||||
await tx.insert(companies).values({ id: companyId, name: 'Doomed Co', slug: 'doomed-co' });
|
||||
await repo.append(tx, input({ targetId: companyId, idempotencyKey: key }));
|
||||
throw new Error('deliberate rollback');
|
||||
}),
|
||||
).rejects.toThrow('deliberate rollback');
|
||||
const [companyRows, eventRows, outboxRows] = await Promise.all([
|
||||
handle.db.select().from(companies).where(eq(companies.id, companyId)),
|
||||
handle.db
|
||||
.select()
|
||||
.from(hierarchyAuditEvents)
|
||||
.where(eq(hierarchyAuditEvents.idempotencyKey, key)),
|
||||
handle.db.select().from(hierarchyOutbox).where(eq(hierarchyOutbox.idempotencyKey, key)),
|
||||
]);
|
||||
expect(companyRows).toHaveLength(0);
|
||||
expect(eventRows).toHaveLength(0);
|
||||
expect(outboxRows).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('replays a duplicate idempotency key without inserting a second event or outbox record', async () => {
|
||||
const first = input();
|
||||
const original = await handle.db.transaction(async (tx) => repo.append(tx, first));
|
||||
const replay = await handle.db.transaction(async (tx) => repo.append(tx, first));
|
||||
expect(original.replayed).toBe(false);
|
||||
expect(replay.replayed).toBe(true);
|
||||
expect(replay.event.id).toBe(original.event.id);
|
||||
const outbox = await handle.db
|
||||
.select()
|
||||
.from(hierarchyOutbox)
|
||||
.where(eq(hierarchyOutbox.eventId, original.event.id));
|
||||
expect(outbox).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('throws on a duplicate idempotency key carrying different event content', async () => {
|
||||
const first = input();
|
||||
await handle.db.transaction(async (tx) => repo.append(tx, first));
|
||||
await expect(
|
||||
handle.db.transaction(async (tx) =>
|
||||
repo.append(tx, { ...first, verb: 'rename', targetId: randomUUID() }),
|
||||
),
|
||||
).rejects.toThrow(HierarchyAuditIdempotencyConflictError);
|
||||
});
|
||||
|
||||
it('throws on a duplicate idempotency key whose transfer destination differs', async () => {
|
||||
const from = { kind: 'company' as const, id: randomUUID(), slug: 'src-co' };
|
||||
const to = { kind: 'company' as const, id: randomUUID(), slug: 'dst-co' };
|
||||
const first = input({
|
||||
verb: 'transfer',
|
||||
targetKind: 'estate',
|
||||
transferFrom: from,
|
||||
transferTo: to,
|
||||
});
|
||||
const original = await handle.db.transaction(async (tx) => repo.append(tx, first));
|
||||
expect(original.replayed).toBe(false);
|
||||
// Identical retry replays; a retry re-routed to a different destination must conflict.
|
||||
const replay = await handle.db.transaction(async (tx) => repo.append(tx, first));
|
||||
expect(replay.replayed).toBe(true);
|
||||
await expect(
|
||||
handle.db.transaction(async (tx) =>
|
||||
repo.append(tx, { ...first, transferTo: { ...to, id: randomUUID() } }),
|
||||
),
|
||||
).rejects.toThrow(HierarchyAuditIdempotencyConflictError);
|
||||
});
|
||||
|
||||
it('builds root-first parent chains and rejects unknown nodes', async () => {
|
||||
const companyId = randomUUID();
|
||||
const estateId = randomUUID();
|
||||
const projectId = randomUUID();
|
||||
await handle.db.transaction(async (tx) => {
|
||||
await tx.insert(companies).values({ id: companyId, name: 'Chain Co', slug: 'chain-co' });
|
||||
await tx
|
||||
.insert(estates)
|
||||
.values({ id: estateId, name: 'Chain Estate', slug: 'chain-estate', companyId });
|
||||
await tx
|
||||
.insert(platformProjects)
|
||||
.values({ id: projectId, name: 'Chain Project', slug: 'chain-project', estateId });
|
||||
});
|
||||
const snapshot = await repo.snapshot(handle.db, 'platform_project', projectId);
|
||||
expect(snapshot).toMatchObject({ id: projectId, slug: 'chain-project', name: 'Chain Project' });
|
||||
expect(snapshot.parentChain).toEqual([
|
||||
{ kind: 'company', id: companyId, slug: 'chain-co' },
|
||||
{ kind: 'estate', id: estateId, slug: 'chain-estate' },
|
||||
]);
|
||||
await expect(repo.snapshot(handle.db, 'estate', randomUUID())).rejects.toThrow(
|
||||
HierarchyNodeNotFoundError,
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps events readable, in per-target seq order, after the target row is deleted', async () => {
|
||||
const companyId = randomUUID();
|
||||
await handle.db.transaction(async (tx) => {
|
||||
await tx.insert(companies).values({ id: companyId, name: 'Mortal Co', slug: 'mortal-co' });
|
||||
const snapshot = await repo.snapshot(tx, 'company', companyId);
|
||||
await repo.append(tx, input({ targetId: companyId, targetSnapshot: { ...snapshot } }));
|
||||
});
|
||||
await handle.db.transaction(async (tx) => {
|
||||
const snapshot = await repo.snapshot(tx, 'company', companyId);
|
||||
await repo.append(tx, {
|
||||
...input({ verb: 'delete', targetId: companyId }),
|
||||
targetSnapshot: { ...snapshot },
|
||||
});
|
||||
await tx.delete(companies).where(eq(companies.id, companyId));
|
||||
});
|
||||
const events = await repo.eventsForTarget(companyId);
|
||||
expect(events.map((e) => e.verb)).toEqual(['create', 'delete']);
|
||||
expect(events[1]!.seq).toBeGreaterThan(events[0]!.seq);
|
||||
expect((events[1]!.targetSnapshot as { id: string }).id).toBe(companyId);
|
||||
});
|
||||
|
||||
it('claims the oldest pending outbox record exactly once, completes and releases by CAS', async () => {
|
||||
// Drain records left pending by earlier cases so ordering is deterministic.
|
||||
for (;;) {
|
||||
const drained = await repo.claimPendingOutbox();
|
||||
if (!drained) break;
|
||||
await repo.completeOutbox(drained.id);
|
||||
}
|
||||
const older = await handle.db.transaction(async (tx) => repo.append(tx, input()));
|
||||
const newer = await handle.db.transaction(async (tx) => repo.append(tx, input()));
|
||||
|
||||
const claimed = await repo.claimPendingOutbox();
|
||||
expect(claimed).not.toBeNull();
|
||||
expect(claimed!.eventId).toBe(older.event.id);
|
||||
expect(claimed!.status).toBe('processing');
|
||||
|
||||
// Delivery fails: release returns it to pending and it is claimable again.
|
||||
await repo.releaseOutbox(claimed!.id);
|
||||
const reclaimed = await repo.claimPendingOutbox();
|
||||
expect(reclaimed!.id).toBe(claimed!.id);
|
||||
|
||||
await repo.completeOutbox(reclaimed!.id);
|
||||
const done = await handle.db
|
||||
.select()
|
||||
.from(hierarchyOutbox)
|
||||
.where(eq(hierarchyOutbox.id, reclaimed!.id));
|
||||
expect(done[0]!.status).toBe('delivered');
|
||||
expect(done[0]!.deliveredAt).not.toBeNull();
|
||||
// completeOutbox is CAS-guarded on 'processing': completing again is a no-op.
|
||||
await repo.completeOutbox(reclaimed!.id);
|
||||
|
||||
const second = await repo.claimPendingOutbox();
|
||||
expect(second!.eventId).toBe(newer.event.id);
|
||||
await repo.completeOutbox(second!.id);
|
||||
expect(await repo.claimPendingOutbox()).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,274 +0,0 @@
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import {
|
||||
and,
|
||||
asc,
|
||||
companies,
|
||||
eq,
|
||||
estates,
|
||||
hierarchyAuditEvents,
|
||||
hierarchyOutbox,
|
||||
platformProjects,
|
||||
type Db,
|
||||
type HIERARCHY_AUDIT_TARGET_KINDS,
|
||||
type HIERARCHY_AUDIT_VERBS,
|
||||
} from '@mosaicstack/db';
|
||||
import { DB } from '../database/database.module.js';
|
||||
|
||||
/**
|
||||
* Hierarchy audit event + outbox machinery (contract 1 §5.2).
|
||||
*
|
||||
* Every hierarchy mutation writes its semantic audit event AND the event's
|
||||
* outbox record on the caller's transaction, so state, event, and outbox
|
||||
* commit or roll back together. Events reference their target by an
|
||||
* immutable snapshot (id, slug, parent chain at event time), never by a
|
||||
* foreign key into the class tables — append-only events survive the
|
||||
* deletion of their target. This module exposes no update or delete path
|
||||
* for events: append-only is a property of the code surface, witnessed by
|
||||
* the integration tests.
|
||||
*
|
||||
* This is NOT a class-table writer: it touches only the audit/outbox
|
||||
* tables, so it does not appear on the writer-coverage allowlist. The
|
||||
* hierarchy command repositories (M4-1b-ii) are the allowlisted writers and
|
||||
* call into this on their own transactions.
|
||||
*/
|
||||
|
||||
export type HierarchyAuditVerb = (typeof HIERARCHY_AUDIT_VERBS)[number];
|
||||
export type HierarchyTargetKind = (typeof HIERARCHY_AUDIT_TARGET_KINDS)[number];
|
||||
export type HierarchyNodeKind = Exclude<HierarchyTargetKind, 'grant'>;
|
||||
|
||||
export interface ParentChainEntry {
|
||||
readonly kind: HierarchyNodeKind;
|
||||
readonly id: string;
|
||||
readonly slug: string;
|
||||
}
|
||||
|
||||
/** Immutable node snapshot at event time; parentChain is root-first. */
|
||||
export interface HierarchyNodeSnapshot {
|
||||
readonly id: string;
|
||||
readonly slug: string;
|
||||
readonly name: string;
|
||||
readonly parentChain: readonly ParentChainEntry[];
|
||||
}
|
||||
|
||||
export interface AppendHierarchyEventInput {
|
||||
readonly actorId: string;
|
||||
readonly verb: HierarchyAuditVerb;
|
||||
readonly targetKind: HierarchyTargetKind;
|
||||
readonly targetId: string;
|
||||
/** Node events: HierarchyNodeSnapshot. Grant events: subject/target/role snapshot (contract 2 §4.4). */
|
||||
readonly targetSnapshot: Record<string, unknown>;
|
||||
/** Present exactly on transfers (CHECK-enforced): source/destination parent { kind, id, slug }. */
|
||||
readonly transferFrom?: ParentChainEntry;
|
||||
readonly transferTo?: ParentChainEntry;
|
||||
readonly correlationId: string;
|
||||
/** Prior event in the causal chain (e.g. the delete event causing cascaded grant_revoke events). */
|
||||
readonly causationId?: string;
|
||||
readonly idempotencyKey: string;
|
||||
}
|
||||
|
||||
export type HierarchyAuditEventRow = typeof hierarchyAuditEvents.$inferSelect;
|
||||
export type HierarchyOutboxRow = typeof hierarchyOutbox.$inferSelect;
|
||||
|
||||
export interface AppendHierarchyEventResult {
|
||||
readonly event: HierarchyAuditEventRow;
|
||||
/** True when the idempotency key had already committed an identical event (REQ-AUD-001 duplicate suppression). */
|
||||
readonly replayed: boolean;
|
||||
}
|
||||
|
||||
type Tx = Pick<Db, 'insert' | 'select'>;
|
||||
|
||||
export class HierarchyAuditIdempotencyConflictError extends Error {
|
||||
constructor(idempotencyKey: string) {
|
||||
super(
|
||||
`hierarchy audit idempotency key ${idempotencyKey} already exists with different event content`,
|
||||
);
|
||||
this.name = 'HierarchyAuditIdempotencyConflictError';
|
||||
}
|
||||
}
|
||||
|
||||
export class HierarchyNodeNotFoundError extends Error {
|
||||
constructor(kind: HierarchyNodeKind, id: string) {
|
||||
super(`hierarchy node not found: ${kind} ${id}`);
|
||||
this.name = 'HierarchyNodeNotFoundError';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Append one audit event and its outbox record on the caller's transaction.
|
||||
* A duplicate idempotency key with identical semantic content returns the
|
||||
* prior event (replayed: true) without inserting anything; a duplicate key
|
||||
* with different content throws.
|
||||
*/
|
||||
export async function appendHierarchyEvent(
|
||||
tx: Tx,
|
||||
input: AppendHierarchyEventInput,
|
||||
): Promise<AppendHierarchyEventResult> {
|
||||
const inserted = await tx
|
||||
.insert(hierarchyAuditEvents)
|
||||
.values({
|
||||
actorId: input.actorId,
|
||||
verb: input.verb,
|
||||
targetKind: input.targetKind,
|
||||
targetId: input.targetId,
|
||||
targetSnapshot: input.targetSnapshot,
|
||||
transferFrom: input.transferFrom ?? null,
|
||||
transferTo: input.transferTo ?? null,
|
||||
correlationId: input.correlationId,
|
||||
causationId: input.causationId ?? null,
|
||||
idempotencyKey: input.idempotencyKey,
|
||||
})
|
||||
.onConflictDoNothing()
|
||||
.returning();
|
||||
const event = inserted[0];
|
||||
if (event) {
|
||||
await tx.insert(hierarchyOutbox).values({
|
||||
eventId: event.id,
|
||||
idempotencyKey: input.idempotencyKey,
|
||||
correlationId: input.correlationId,
|
||||
});
|
||||
return { event, replayed: false };
|
||||
}
|
||||
|
||||
const prior = await tx
|
||||
.select()
|
||||
.from(hierarchyAuditEvents)
|
||||
.where(eq(hierarchyAuditEvents.idempotencyKey, input.idempotencyKey))
|
||||
.limit(1);
|
||||
const existing = prior[0];
|
||||
if (!existing || !sameEvent(existing, input)) {
|
||||
throw new HierarchyAuditIdempotencyConflictError(input.idempotencyKey);
|
||||
}
|
||||
// Event and outbox committed atomically the first time, so the outbox
|
||||
// record already exists; a replay inserts nothing.
|
||||
return { event: existing, replayed: true };
|
||||
}
|
||||
|
||||
/** Key-order-independent serialization: jsonb does not preserve key order. */
|
||||
function canonicalJson(value: unknown): string {
|
||||
if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`;
|
||||
if (value !== null && typeof value === 'object') {
|
||||
const record = value as Record<string, unknown>;
|
||||
const body = Object.keys(record)
|
||||
.sort()
|
||||
.map((key) => `${JSON.stringify(key)}:${canonicalJson(record[key])}`)
|
||||
.join(',');
|
||||
return `{${body}}`;
|
||||
}
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
|
||||
function sameEvent(row: HierarchyAuditEventRow, input: AppendHierarchyEventInput): boolean {
|
||||
return (
|
||||
row.actorId === input.actorId &&
|
||||
row.verb === input.verb &&
|
||||
row.targetKind === input.targetKind &&
|
||||
row.targetId === input.targetId &&
|
||||
row.correlationId === input.correlationId &&
|
||||
(row.causationId ?? null) === (input.causationId ?? null) &&
|
||||
canonicalJson(row.targetSnapshot) === canonicalJson(input.targetSnapshot) &&
|
||||
// Transfer source/destination are semantic content (§5.2): a retry with a
|
||||
// different destination must conflict, never silently replay.
|
||||
canonicalJson(row.transferFrom ?? null) === canonicalJson(input.transferFrom ?? null) &&
|
||||
canonicalJson(row.transferTo ?? null) === canonicalJson(input.transferTo ?? null)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the immutable snapshot for a node: its row plus the parent chain up
|
||||
* to the company root, root-first, read on the caller's transaction so the
|
||||
* snapshot is consistent with the mutation it audits.
|
||||
*/
|
||||
export async function buildNodeSnapshot(
|
||||
tx: Tx,
|
||||
kind: HierarchyNodeKind,
|
||||
id: string,
|
||||
): Promise<HierarchyNodeSnapshot> {
|
||||
if (kind === 'company') {
|
||||
const rows = await tx.select().from(companies).where(eq(companies.id, id)).limit(1);
|
||||
const row = rows[0];
|
||||
if (!row) throw new HierarchyNodeNotFoundError(kind, id);
|
||||
return { id: row.id, slug: row.slug, name: row.name, parentChain: [] };
|
||||
}
|
||||
if (kind === 'estate') {
|
||||
const rows = await tx.select().from(estates).where(eq(estates.id, id)).limit(1);
|
||||
const row = rows[0];
|
||||
if (!row) throw new HierarchyNodeNotFoundError(kind, id);
|
||||
const parent = await buildNodeSnapshot(tx, 'company', row.companyId);
|
||||
return {
|
||||
id: row.id,
|
||||
slug: row.slug,
|
||||
name: row.name,
|
||||
parentChain: [...parent.parentChain, { kind: 'company', id: parent.id, slug: parent.slug }],
|
||||
};
|
||||
}
|
||||
const rows = await tx.select().from(platformProjects).where(eq(platformProjects.id, id)).limit(1);
|
||||
const row = rows[0];
|
||||
if (!row) throw new HierarchyNodeNotFoundError(kind, id);
|
||||
const parent = await buildNodeSnapshot(tx, 'estate', row.estateId);
|
||||
return {
|
||||
id: row.id,
|
||||
slug: row.slug,
|
||||
name: row.name,
|
||||
parentChain: [...parent.parentChain, { kind: 'estate', id: parent.id, slug: parent.slug }],
|
||||
};
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class HierarchyAuditRepository {
|
||||
constructor(@Inject(DB) private readonly db: Db) {}
|
||||
|
||||
/** Compose an event+outbox append into a caller-owned transaction. */
|
||||
append(tx: Tx, input: AppendHierarchyEventInput): Promise<AppendHierarchyEventResult> {
|
||||
return appendHierarchyEvent(tx, input);
|
||||
}
|
||||
|
||||
snapshot(tx: Tx, kind: HierarchyNodeKind, id: string): Promise<HierarchyNodeSnapshot> {
|
||||
return buildNodeSnapshot(tx, kind, id);
|
||||
}
|
||||
|
||||
/** Per-target ordered event history (REQ-AUD-001 per-target ordering; read-only). */
|
||||
async eventsForTarget(targetId: string): Promise<HierarchyAuditEventRow[]> {
|
||||
return this.db
|
||||
.select()
|
||||
.from(hierarchyAuditEvents)
|
||||
.where(eq(hierarchyAuditEvents.targetId, targetId))
|
||||
.orderBy(asc(hierarchyAuditEvents.seq));
|
||||
}
|
||||
|
||||
/**
|
||||
* Claim the oldest pending outbox record (claim-by-CAS: the UPDATE is
|
||||
* guarded on status so a lost race returns null and the caller retries).
|
||||
*/
|
||||
async claimPendingOutbox(): Promise<HierarchyOutboxRow | null> {
|
||||
const candidates = await this.db
|
||||
.select()
|
||||
.from(hierarchyOutbox)
|
||||
.where(eq(hierarchyOutbox.status, 'pending'))
|
||||
.orderBy(asc(hierarchyOutbox.createdAt))
|
||||
.limit(1);
|
||||
const candidate = candidates[0];
|
||||
if (!candidate) return null;
|
||||
const claimed = await this.db
|
||||
.update(hierarchyOutbox)
|
||||
.set({ status: 'processing', updatedAt: new Date() })
|
||||
.where(and(eq(hierarchyOutbox.id, candidate.id), eq(hierarchyOutbox.status, 'pending')))
|
||||
.returning();
|
||||
return claimed[0] ?? null;
|
||||
}
|
||||
|
||||
async completeOutbox(id: string): Promise<void> {
|
||||
const now = new Date();
|
||||
await this.db
|
||||
.update(hierarchyOutbox)
|
||||
.set({ status: 'delivered', deliveredAt: now, updatedAt: now })
|
||||
.where(and(eq(hierarchyOutbox.id, id), eq(hierarchyOutbox.status, 'processing')));
|
||||
}
|
||||
|
||||
/** Return a claimed record to pending (delivery failed; it stays replayable). */
|
||||
async releaseOutbox(id: string): Promise<void> {
|
||||
await this.db
|
||||
.update(hierarchyOutbox)
|
||||
.set({ status: 'pending', updatedAt: new Date() })
|
||||
.where(and(eq(hierarchyOutbox.id, id), eq(hierarchyOutbox.status, 'processing')));
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { HierarchyAuditRepository } from './hierarchy-audit.repository.js';
|
||||
|
||||
/**
|
||||
* Hierarchy (tenancy/authorization structure) feature module.
|
||||
*
|
||||
* M4-1b-i ships the audit event + outbox machinery only (contract 1 §5.2).
|
||||
* The hierarchy command family — controllers, DTOs, and the allowlisted
|
||||
* class-table repositories — lands in M4-1b-ii once contract 2 (RBAC grant
|
||||
* model) merges; until then this module exposes no routes, which the
|
||||
* route-inventory witness asserts.
|
||||
*/
|
||||
@Module({
|
||||
providers: [HierarchyAuditRepository],
|
||||
exports: [HierarchyAuditRepository],
|
||||
})
|
||||
export class HierarchyModule {}
|
||||
@@ -882,12 +882,3 @@ Objective: for alpha 0.0.50, the release cannot publish, report, or display work
|
||||
### Out of scope
|
||||
|
||||
The canonical dispatcher/control-plane vertical slice (work graph, execution attempts, fenced leases, typed check-in, independent verifier dispatch) is decided post-alpha (SDLC-D-033, option B). Multi-pipeline verification certificates (SDLC-D-034 option B) are post-alpha. Full AF-1..AF-4 objective matrices and Mission Control portfolio surfaces are post-alpha.
|
||||
|
||||
## Official CLI Capability and Tool Migration Workstream (T78)
|
||||
|
||||
Normative contract on integration trunk `next`:
|
||||
[docs/requirements/cli-capability-migration.md](./requirements/cli-capability-migration.md):
|
||||
migrates agent-facing operations from directly invoked scripts into documented, first-class
|
||||
`mosaic` CLI command groups, together with the central-registry resolver, capability catalog,
|
||||
adapter boundary, and phased legacy-tool-tree decommission the migration requires. The contract
|
||||
carries its own implementation hold and delivery stages.
|
||||
|
||||
+1
-3
@@ -12,9 +12,7 @@ design; scoping one requires its own PRD section or requirements doc plus
|
||||
review.
|
||||
|
||||
Phases are product phases. The in-flight platform workstreams (KBN-100/101
|
||||
kanban SOT implementation, FCM #758, FCOM #766, TESS, RI #1275, T78 CLI
|
||||
capability migration
|
||||
([requirements](./requirements/cli-capability-migration.md)), and the other
|
||||
kanban SOT implementation, FCM #758, FCOM #766, TESS, RI #1275, and the other
|
||||
Part II contracts in the PRD) run as parallel tracks under their own issues
|
||||
and are prerequisites where noted.
|
||||
|
||||
|
||||
@@ -18,7 +18,6 @@
|
||||
- [Active task rollup](TASKS.md) — orchestrator-owned work state; workers do not modify it.
|
||||
- [MVP mission manifest](MISSION-MANIFEST.md) — control-plane mission rollup; activity and status remain under its authorized owner.
|
||||
- [Documentation catalog and truth audit](reports/documentation/2026-08-10-docs-catalog-audit.md) — complete baseline inventory, evidence labels, broken-link clusters, and migration recommendations.
|
||||
- [CLI capability migration requirements](requirements/cli-capability-migration.md): T78 official CLI capability and tool migration contract, normative contract with implementation hold (M0).
|
||||
|
||||
## Protected current authority and executable books
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,748 +0,0 @@
|
||||
---
|
||||
kind: spec
|
||||
status: active
|
||||
source_of_truth: true
|
||||
---
|
||||
|
||||
# Official Mosaic CLI Capability and Tool Migration
|
||||
|
||||
- **Workstream:** T78
|
||||
- **Status:** active requirements contract, implementation held by the M0 gates
|
||||
- **Decision authority:** Jason Woltje
|
||||
- **Design owner:** Vision
|
||||
- **Integration trunk:** `next`
|
||||
|
||||
This contract is authoritative only on the integration trunk `next`. Branch copies are proposals.
|
||||
Publication does not authorize implementation until the M0 milestone, task-graph, interface, and
|
||||
partition gates pass.
|
||||
|
||||
## 1. Purpose
|
||||
|
||||
Migrate agent-facing operations from directly invoked scripts into documented, first-class command
|
||||
groups in the existing TypeScript and Node.js `mosaic` CLI. The CLI becomes the stable interface
|
||||
for operators, agents, the webUI, future seat containers, and future `mosaicd` execution.
|
||||
|
||||
The mission also phases out the installed `~/.config/mosaic/tools` script surface. Existing scripts
|
||||
may remain private compatibility adapters only while measured consumers still require them.
|
||||
|
||||
## 2. Product alignment
|
||||
|
||||
Items 1 through 3 implement PRD D8 and D12:
|
||||
|
||||
1. The CLI is the primary execution surface.
|
||||
2. The webUI uses Gateway APIs backed by the same official capability contracts.
|
||||
3. A missing official capability is built before a webUI bypass is accepted.
|
||||
|
||||
This contract adds one explicit extension beyond D8 and D12: no harness, skill, or agent receives a
|
||||
separate business-logic path around the CLI and Gateway capability contract.
|
||||
|
||||
This contract does not replace the fleet north star, issue `#1382`, the fleet configuration
|
||||
contract `#758`, the exact fleet communications contract `#766`, or future container and `mosaicd`
|
||||
specifications. It defines the interfaces those tracks consume.
|
||||
|
||||
## 3. Fixed decisions
|
||||
|
||||
| ID | Decision |
|
||||
| ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| T78-D1 | Extend the existing official TypeScript and Node.js `mosaic` CLI. A second Python or shell entrypoint is forbidden. |
|
||||
| T78-D2 | Expose documented groups such as `mosaic git`, `mosaic comms`, and `mosaic ci`. A generic public `mosaic tools` passthrough is forbidden. |
|
||||
| T78-D3 | Resolve homes, endpoints, sockets, tool locations, and runtime paths through the central registry and one typed resolver. Commands do not hard-code them. |
|
||||
| T78-D4 | One rootless container per seat is the target sandbox. It has a read-only root filesystem, no container-runtime socket, and lifecycle through future `mosaicd`. |
|
||||
| T78-D5 | Dispatch is per-site. Localhost `orch-01` alone dispatches USC-seat implementation. Homelab `orch-01` alone dispatches homelab-seat implementation and homelab-owned surfaces. |
|
||||
| T78-D6 | Tmux and fleet-comms remain temporary communications adapters behind a transport-neutral CLI contract. |
|
||||
| T78-D7 | Decommissioning is phased and mechanically enforced. Removal requires zero measured consumers and a discriminating planted-reference control. |
|
||||
|
||||
Derived security boundary:
|
||||
|
||||
- `~/.mosaic/tools` is canonical working source during migration. It is not automatically trusted
|
||||
runtime installation state.
|
||||
- Reviewed source is promoted into installed or packaged runtime artifacts.
|
||||
- A multi-writer brain-repository push must not silently replace credential-bearing executable code
|
||||
used by every seat.
|
||||
|
||||
## 4. Explicitly rejected alternatives
|
||||
|
||||
| Alternative | Rejection reason |
|
||||
| ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------ |
|
||||
| Separate Python CLI | Creates a second contract, release path, and policy surface. |
|
||||
| Public `mosaic tools <script>` passthrough | Preserves script names and paths as the API instead of defining capabilities. |
|
||||
| CLI allowlists as the sandbox | Parser allowlists do not isolate files, credentials, processes, networks, or container control. |
|
||||
| Execute the synced working tree as the final runtime | A brain push would become host-wide code execution authority. |
|
||||
| Big-bang script rewrite and deletion | Mature queue, identity, credential, and uncertainty behavior would be changed without parity evidence. |
|
||||
| Tmux-shaped communications API | It would force future Matrix or native transports to preserve tmux concepts. |
|
||||
|
||||
## 5. Terminology
|
||||
|
||||
- **Central registry:** the schema-v1 `config.json` authority filed in issue `#1382`.
|
||||
- **Registry resolver:** the typed reader that validates and resolves central-registry values.
|
||||
- **Capability catalog:** the typed inventory of public capability identifiers and behavior. It is
|
||||
not the central registry.
|
||||
- **Capability policy:** data that maps verified actor and lane identity to allowed capabilities and
|
||||
scopes.
|
||||
- **Local adapter:** a temporary in-process or private-script implementation used before `mosaicd`
|
||||
is available.
|
||||
- **Broker adapter:** the future client transport to `mosaicd` outside the seat container.
|
||||
- **Installed legacy tree:** `~/.config/mosaic/tools`.
|
||||
- **Canonical working source:** `~/.mosaic/tools` during the migration period.
|
||||
- **Runtime artifact:** reviewed package or installed bytes actually executed by a seat.
|
||||
|
||||
## 6. Public CLI grammar
|
||||
|
||||
### CLI-REQ-001: First-class command groups
|
||||
|
||||
The official help surface MUST register domain groups directly:
|
||||
|
||||
```text
|
||||
mosaic git ...
|
||||
mosaic comms ...
|
||||
mosaic ci ...
|
||||
```
|
||||
|
||||
Future domains MAY include `infra`, `identity`, and other reviewed capability families. They MUST
|
||||
NOT appear through a generic script dispatcher.
|
||||
|
||||
### CLI-REQ-002: Stable command shape
|
||||
|
||||
New capability commands use this grammar:
|
||||
|
||||
```text
|
||||
mosaic <domain> <resource> <verb> [target] [options]
|
||||
```
|
||||
|
||||
The first pilot freezes these paths:
|
||||
|
||||
```text
|
||||
mosaic git issue list
|
||||
mosaic git issue view <number>
|
||||
mosaic git issue comment <number> --input <path|->
|
||||
```
|
||||
|
||||
Capability identifiers are independent from display text:
|
||||
|
||||
| Command | Capability ID | Class |
|
||||
| -------------------------- | ------------------- | ---------------- |
|
||||
| `mosaic git issue list` | `git.issue.list` | read |
|
||||
| `mosaic git issue view` | `git.issue.view` | read |
|
||||
| `mosaic git issue comment` | `git.issue.comment` | bounded mutation |
|
||||
|
||||
Renaming a command path does not silently rename its capability identifier. Either change requires a
|
||||
versioned compatibility decision.
|
||||
|
||||
### CLI-REQ-003: Common targeting options
|
||||
|
||||
The pilot supports:
|
||||
|
||||
- `--instance <name>` for the configured provider instance.
|
||||
- `--repo <owner/name>` for the provider repository.
|
||||
- `--format <table|json>` for output selection.
|
||||
- `--correlation-id <id>` for a caller-supplied valid identifier. Omission generates one.
|
||||
- `--idempotency-key <key>` for mutations. Omission generates one and returns it.
|
||||
|
||||
An instance may be inferred only when the registry has exactly one valid instance for that domain.
|
||||
A repository may be inferred only from a validated current repository declaration and an
|
||||
unambiguous canonical remote. Ambiguity fails closed and names the missing field.
|
||||
|
||||
No public option forces local compatibility mode when policy selected broker mode. A caller cannot
|
||||
downgrade the execution boundary.
|
||||
|
||||
### CLI-REQ-004: Mutation input
|
||||
|
||||
`git.issue.comment` reads its body from `--input <path>` or stdin with `--input -`. The CLI MUST:
|
||||
|
||||
1. reject a missing or empty body.
|
||||
2. apply a documented byte limit before provider access.
|
||||
3. never place the body in process arguments, diagnostics, or audit metadata.
|
||||
4. compute a body digest for read-back verification without exposing the body.
|
||||
5. avoid automatic retry after an uncertain provider mutation.
|
||||
|
||||
### CLI-REQ-005: Structured result envelope
|
||||
|
||||
JSON output uses one versioned envelope:
|
||||
|
||||
```ts
|
||||
interface CapabilityResultV1<T> {
|
||||
schemaVersion: 1;
|
||||
capabilityId: string;
|
||||
status: 'succeeded' | 'invalid' | 'denied' | 'failed' | 'uncertain' | 'unavailable';
|
||||
executionMode: 'local-adapter' | 'mosaicd';
|
||||
identityTrust: 'local-asserted' | 'runtime-verified';
|
||||
correlationId: string;
|
||||
idempotencyKey?: string;
|
||||
target: Record<string, string | number | boolean | null>;
|
||||
data?: T;
|
||||
diagnostics: Array<{
|
||||
code: string;
|
||||
message: string;
|
||||
field?: string;
|
||||
retryable: boolean;
|
||||
}>;
|
||||
audit:
|
||||
| { authority: 'mosaicd'; recorded: true; eventId: string }
|
||||
| { authority: 'none'; recorded: false; localEventId?: string };
|
||||
}
|
||||
```
|
||||
|
||||
`target` and `diagnostics` contain no credentials or unbounded provider body. Table output is a
|
||||
human view of the same result and cannot carry a different verdict.
|
||||
|
||||
### CLI-REQ-006: Exit behavior
|
||||
|
||||
| Exit | Meaning |
|
||||
| ---: | --------------------------------------------------------------------------- |
|
||||
| 0 | `succeeded` |
|
||||
| 2 | `invalid`: invalid input, invalid configuration, or unsupported schema |
|
||||
| 3 | `denied` by capability or scope policy |
|
||||
| 4 | `failed` with a confirmed non-success outcome |
|
||||
| 5 | `uncertain`, including a mutation whose provider result cannot be confirmed |
|
||||
| 6 | `unavailable`, including missing broker, credentials, or required adapter |
|
||||
|
||||
A provider HTTP success alone is insufficient. The adapter validates the expected response shape.
|
||||
A mutation that may have landed but lacks confirmation returns exit 5 and is never described as
|
||||
failed or safe to retry. For a provider-native idempotent mutation, manual reconciliation MAY retry
|
||||
the same key. For `uncertain-no-retry`, help directs the caller to a read-back check and forbids
|
||||
mutation retry.
|
||||
|
||||
### CLI-REQ-007: Help and discovery
|
||||
|
||||
The capability catalog generates or validates:
|
||||
|
||||
- `mosaic --help` command-group listing.
|
||||
- group and command help.
|
||||
- stable capability identifiers.
|
||||
- machine-readable capability discovery.
|
||||
- documentation tables.
|
||||
- policy-generation inputs.
|
||||
- tests that reject undocumented public commands and orphaned capabilities.
|
||||
|
||||
## 7. Central registry resolver
|
||||
|
||||
### CFG-REQ-001: One distinct resolver
|
||||
|
||||
Implement one exported resolver named `MosaicRegistryResolver` or another name explicitly approved
|
||||
in the contract review. It MUST NOT be named `ConfigService`. The existing
|
||||
`packages/mosaic/src/config/config-service.ts` exports `ConfigService` for SOUL, USER, and TOOLS
|
||||
content and remains a separate concern.
|
||||
|
||||
### CFG-REQ-002: Frozen schema consumption
|
||||
|
||||
The resolver consumes schema v1 from issue `#1382` without creating parallel keys. Every key is
|
||||
optional. The exact v1 surface is:
|
||||
|
||||
- `$schema`, with the known marker `mosaic-config-v1`.
|
||||
- `mosaicHome`, reserved, null, and without a v1 consumer.
|
||||
- `brainHome`, default `~/.mosaic`.
|
||||
- `instances.gitea.<name>.url`.
|
||||
- `fleet.socket`.
|
||||
- `harnessConfig.pi.agentDir`.
|
||||
- `harnessConfig.claude.configDir`.
|
||||
- `harnessConfig.claude.secureStorageDir`.
|
||||
|
||||
Credential values, model and effort defaults, and `fleet.rosterPath` are forbidden. A non-null
|
||||
`mosaicHome` value fails validation because v1 reserves the field without implementing relocation.
|
||||
An absent or null `$schema` is interpreted as v1, the exact `mosaic-config-v1` marker is accepted,
|
||||
and every other non-null marker fails before value resolution.
|
||||
|
||||
Absent or null values select the framework default. A `~` path prefix expands at read time and is
|
||||
never rewritten into the user file. Unknown top-level and nested keys warn loudly and are ignored
|
||||
for rolling-version compatibility. Every warning and machine-readable diagnostic names the full
|
||||
ignored key path, so a typo is visible at every read.
|
||||
|
||||
Fail-closed read behavior applies to invalid JSON, a failed C1 version check, a known key with an
|
||||
invalid type or value, and a present but empty or invalid override. An optional
|
||||
`mosaic registry validate` lint mode MAY reject unknown keys for operator validation, but the normal
|
||||
resolver read path does not. This top-level group is separate from the existing `mosaic config`
|
||||
commands backed by `ConfigService`.
|
||||
|
||||
### CFG-REQ-003: Resolution precedence
|
||||
|
||||
For each supported value, resolution follows exactly:
|
||||
|
||||
1. the schema-defined `MOSAIC_<KEY>_OVERRIDE` environment override.
|
||||
2. validated `config.json` value.
|
||||
3. one centralized framework default, when the key defines a default.
|
||||
|
||||
A present override always wins. An empty or invalid override fails and does not fall through to the
|
||||
file or default. `$schema` and reserved `mosaicHome` have no environment override. Consumed values
|
||||
use this collision-free mapping:
|
||||
|
||||
| Registry key | Environment override |
|
||||
| --------------------------------------- | ---------------------------------------------------------- |
|
||||
| `brainHome` | `MOSAIC_BRAIN_HOME_OVERRIDE` |
|
||||
| `fleet.socket` | `MOSAIC_FLEET_SOCKET_OVERRIDE` |
|
||||
| `harnessConfig.pi.agentDir` | `MOSAIC_HARNESS_CONFIG_PI_AGENT_DIR_OVERRIDE` |
|
||||
| `harnessConfig.claude.configDir` | `MOSAIC_HARNESS_CONFIG_CLAUDE_CONFIG_DIR_OVERRIDE` |
|
||||
| `harnessConfig.claude.secureStorageDir` | `MOSAIC_HARNESS_CONFIG_CLAUDE_SECURE_STORAGE_DIR_OVERRIDE` |
|
||||
| `instances.gitea.<name>.url` | `MOSAIC_INSTANCES_GITEA_<NAME>_URL_OVERRIDE` |
|
||||
|
||||
Gitea instance names match `[a-z][a-z0-9-]*`. The override name uppercases the instance name and
|
||||
maps hyphen to underscore. Underscores are not valid in source instance names, so two valid names
|
||||
cannot flatten to the same override.
|
||||
|
||||
A value without a valid result fails before adapter or provider access. Invalid known URLs, socket
|
||||
names, paths, and value types fail closed. Unknown keys follow CFG-REQ-002.
|
||||
|
||||
### CFG-REQ-004: Typed provenance
|
||||
|
||||
Every resolved value carries non-secret provenance:
|
||||
|
||||
```ts
|
||||
type RegistryValueSource = 'override' | 'registry' | 'framework-default';
|
||||
|
||||
interface ResolvedRegistryValue<T> {
|
||||
key: string;
|
||||
value: T;
|
||||
source: RegistryValueSource;
|
||||
schemaVersion: 1;
|
||||
}
|
||||
```
|
||||
|
||||
Machine-readable diagnostics include the full path of every ignored unknown key. Diagnostics may
|
||||
name a known key and source class. They do not emit credential values or unrelated configuration.
|
||||
|
||||
### CFG-REQ-005: Bootstrap and path safety
|
||||
|
||||
Registry discovery is the fixed path `~/.config/mosaic/config.json`. It has no v1 search path and no
|
||||
alternate location. The file is the one user-updatable path inside `~/.config/mosaic` and is
|
||||
protected by a deny-wins upgrade carve-out. Upgrades never overwrite user edits.
|
||||
|
||||
This fixed bootstrap avoids circular dependence on reserved `mosaicHome`. A seat container reads its
|
||||
own internal `~/.config/mosaic/config.json`, supplied by the container topology, rather than a host
|
||||
path or a relocation flag. Path values are expanded, normalized, validated, and tested under at
|
||||
least two distinct home roots.
|
||||
|
||||
No command embeds home directories, script locations, provider endpoints, seat paths, or tmux socket
|
||||
names outside the resolver and its reviewed defaults.
|
||||
|
||||
### CFG-REQ-006: Schema evolution
|
||||
|
||||
A new key requires:
|
||||
|
||||
1. a named consumer.
|
||||
2. a `#1382` schema amendment.
|
||||
3. joint ACK from the frozen-schema and resolver-contract custodians until handoff, recorded by
|
||||
custodian-authored commits rather than relayed tokens alone.
|
||||
4. parser, invalid-input, default, and two-root tests.
|
||||
5. documentation in the same reviewed change.
|
||||
|
||||
Speculative keys are forbidden.
|
||||
|
||||
### CFG-REQ-007: Joint freeze evidence
|
||||
|
||||
The v1 resolver contract is jointly frozen:
|
||||
|
||||
- Fred, frozen-schema custodian, accepted C1 and C3 through token
|
||||
`CLI-T78-REGISTRY-FREEZE ACCEPT`, then accepted amended C2 through token
|
||||
`CLI-T78-REGISTRY-C2 ACCEPT`.
|
||||
- Homelab `orch-01`, issue and resolver-contract custodian, accepted C1 and C3 and supplied the
|
||||
adopted C2 rolling-version amendment in the fleet-comms repository, message
|
||||
`sites/usc/20260827T004509Z__to-vision__from-homelab.orch-01__683e4c.md`, blob
|
||||
`35a7c4c1e54eb9196abeef3135d211ee1dfc46db`.
|
||||
|
||||
Durable lane provenance is recorded in the Mosaic brain repository at
|
||||
`fleet/lanes/cli-migration/registry-freeze-evidence.md` and the independent custodian-authored
|
||||
`fleet/lanes/cli-migration/registry-freeze-fred-ack.md`. Schema evolution after this freeze still
|
||||
follows CFG-REQ-006.
|
||||
|
||||
## 8. Capability catalog and policy
|
||||
|
||||
### CAP-REQ-001: One typed catalog
|
||||
|
||||
Each capability definition records:
|
||||
|
||||
```ts
|
||||
type CapabilityEffect = 'read' | 'bounded-mutation' | 'privileged-mutation';
|
||||
|
||||
interface CapabilityDefinitionV1 {
|
||||
id: string;
|
||||
commandPath: readonly string[];
|
||||
effect: CapabilityEffect;
|
||||
targetSchema: string;
|
||||
inputSchema: string;
|
||||
outputSchema: string;
|
||||
credentialClass: string | null;
|
||||
requiredScopes: readonly string[];
|
||||
auditRequired: boolean;
|
||||
timeoutMs: number;
|
||||
idempotency: 'read' | 'required-key' | 'provider-native' | 'uncertain-no-retry';
|
||||
adapterId: string;
|
||||
deprecation: 'active' | 'deprecated' | 'removed';
|
||||
}
|
||||
```
|
||||
|
||||
The catalog is data consumed by the parser, help, policy, documentation, and tests. Command handlers
|
||||
must not maintain independent copies of these facts.
|
||||
|
||||
### CAP-REQ-002: Policy is not parser logic
|
||||
|
||||
Capability grants map verified actor identity and lane to capability IDs and resource scopes. They
|
||||
are data. A named seat receives no authority from its name alone.
|
||||
|
||||
The user-editable central registry is placement and endpoint configuration, not authorization
|
||||
policy. It MUST NOT contain lane grants or let a seat self-grant capability scope. Target authority
|
||||
lives in the `mosaicd` control-plane store outside seat containers and returns a policy revision and
|
||||
digest with every decision.
|
||||
|
||||
Before `mosaicd`, local compatibility mode may evaluate a package-owned policy for behavior and test
|
||||
parity, but it reports locally asserted identity and makes no broker-grade authorization claim. Mode
|
||||
selection is declared by topology and policy, never inferred from broker availability. A missing or
|
||||
unhealthy required broker returns `unavailable`. It never falls back to local mode.
|
||||
|
||||
A capability using a shared, service, operator, or admin credential is broker-only. Local mode may
|
||||
use only the acting seat's own credential against a registry endpoint. Privileged infrastructure,
|
||||
merge, deployment, identity, authorization, and secret-management cutover requires `mosaicd`. A
|
||||
future policy-store key or broker endpoint still requires CFG-REQ-006 and the `mosaicd` topology
|
||||
contract.
|
||||
|
||||
### CAP-REQ-003: Identity trust
|
||||
|
||||
CLI arguments and ordinary environment variables are actor hints, not authorization identity. The
|
||||
local adapter reports that identity is locally asserted and MUST NOT claim broker-grade
|
||||
authorization. `mosaicd` derives or verifies actor identity from the authenticated seat runtime.
|
||||
|
||||
### CAP-REQ-004: Positive and denied controls
|
||||
|
||||
Every capability test includes:
|
||||
|
||||
1. an allowed request with expected result.
|
||||
2. a denied request differing only in the relevant lane or scope.
|
||||
3. a malformed target or configuration denial.
|
||||
4. a credential-redaction assertion.
|
||||
5. a verdict-discrimination control that proves the test can fail.
|
||||
|
||||
## 9. Adapter and broker contract
|
||||
|
||||
### EXE-REQ-001: One capability request
|
||||
|
||||
```ts
|
||||
interface CapabilityRequestV1 {
|
||||
schemaVersion: 1;
|
||||
capabilityId: string;
|
||||
actorHint?: { seat?: string; lane?: string };
|
||||
target: Record<string, string | number | boolean | null>;
|
||||
arguments: Record<string, string | number | boolean | null>;
|
||||
correlationId: string;
|
||||
idempotencyKey?: string;
|
||||
}
|
||||
```
|
||||
|
||||
Credential values and unbounded comment bodies are not serialized into audit-safe request metadata.
|
||||
Body content travels through a bounded private input channel appropriate to the adapter.
|
||||
|
||||
### EXE-REQ-002: Local compatibility adapter
|
||||
|
||||
The local adapter MAY call a reviewed in-process implementation or a private script adapter. It
|
||||
MUST preserve existing queue guards, wrapper-first behavior, credential resolution, response
|
||||
validation, and mutation uncertainty. It reports `executionMode: local-adapter` and
|
||||
`identityTrust: local-asserted`.
|
||||
|
||||
Private child adapters receive bodies and credentials only through stdin, owner-only temporary
|
||||
files, or inherited file descriptors, never child-process arguments. Captured child stderr, shell
|
||||
trace, and diagnostics are inside the redaction boundary. Local results always use
|
||||
`audit: { authority: 'none', recorded: false }`. A local event identifier is not authoritative
|
||||
audit evidence.
|
||||
|
||||
The local adapter is compatibility, not a sandbox or authorization claim.
|
||||
|
||||
### EXE-REQ-003: `mosaicd` broker adapter
|
||||
|
||||
The broker adapter sends the same logical request to `mosaicd` outside the seat container.
|
||||
`mosaicd` owns:
|
||||
|
||||
- authoritative seat identity, recorded in audit from the derived runtime identity rather than
|
||||
`actorHint`.
|
||||
- capability and scope authorization.
|
||||
- credential resolution.
|
||||
- operation execution.
|
||||
- output sanitization.
|
||||
- audit persistence.
|
||||
- bounded timeout and cancellation behavior.
|
||||
|
||||
A contradictory `actorHint` produces a diagnostic and never replaces the derived actor. Broker
|
||||
results report `identityTrust: runtime-verified`. `audit.recorded: true` is valid only after
|
||||
`mosaicd` confirms persistence and returns its event ID. Consumers verify authoritative evidence
|
||||
against the broker trail, not the seat-produced envelope alone.
|
||||
|
||||
The transport and endpoint are supplied by immutable container topology and the reviewed central
|
||||
registry contract. No command hard-codes a daemon socket.
|
||||
|
||||
### EXE-REQ-004: Packaged implementation boundary
|
||||
|
||||
The initial TypeScript layout is:
|
||||
|
||||
- `packages/mosaic/src/central-registry/` for `MosaicRegistryResolver`, schema, and provenance.
|
||||
- `packages/mosaic/src/capabilities/` for catalog, request, result, policy interfaces, and tests.
|
||||
- `packages/mosaic/src/capabilities/adapters/local/` for temporary local adapter modules.
|
||||
- `packages/mosaic/src/capabilities/adapters/mosaicd/` for the broker client seam.
|
||||
- `packages/mosaic/src/commands/git.ts`, with later first-class domain files following the same
|
||||
command pattern.
|
||||
|
||||
Remaining script implementations may be promoted under `packages/mosaic/framework/tools/` as
|
||||
private packaged adapters during transition. Their installed paths are resolver-owned and are not
|
||||
public command contracts. No production adapter imports or executes source from the brain working
|
||||
tree as the final path.
|
||||
|
||||
### EXE-REQ-005: Container boundary
|
||||
|
||||
The representative seat container has:
|
||||
|
||||
- one seat identity.
|
||||
- rootless execution.
|
||||
- read-only root filesystem, with explicit bounded writable mounts.
|
||||
- a read-only internal `~/.config/mosaic/config.json` supplied by topology.
|
||||
- no host credential tree.
|
||||
- no shared host or fleet tmux socket.
|
||||
- a dedicated per-seat tmux socket only for one named, reviewed temporary adapter with a stated
|
||||
removal stage.
|
||||
- no Docker, Podman, or other container-runtime socket.
|
||||
- no installed legacy tool tree mount.
|
||||
- network access limited to declared capability paths.
|
||||
|
||||
Container implementation is outside this mission. Contract and compatibility tests are inside it.
|
||||
|
||||
## 10. Communications portability
|
||||
|
||||
### COM-REQ-001: Transport-neutral public contract
|
||||
|
||||
Public communications capabilities use logical addresses, messages, correlation IDs, delivery
|
||||
status, and adapter diagnostics. Tmux pane, socket, retry, and draft details stay below the public
|
||||
contract.
|
||||
|
||||
### COM-REQ-002: Transitional semantics
|
||||
|
||||
The tmux adapter preserves the measured `rc=2` behavior: content reached a pane as a draft, so the
|
||||
operation is not retried automatically. Fleet-comms preserves durable cross-site message identity
|
||||
and acknowledgment behavior.
|
||||
|
||||
### COM-REQ-003: Future transport replacement
|
||||
|
||||
A Matrix or native transport implementation passes the same contract tests. Callers do not change
|
||||
command paths, capability IDs, or result interpretation when the adapter changes.
|
||||
|
||||
## 11. Canonical source and runtime integrity
|
||||
|
||||
### SRC-REQ-001: Reviewed baseline
|
||||
|
||||
The F11 baseline is commit `5be5825`. Inventory report `585f214`, code review `3fe8de7`, and
|
||||
security review `e270098` are the M0 evidence. Both reviews found no blocker.
|
||||
|
||||
### SRC-REQ-002: Required M1 corrections
|
||||
|
||||
Before expanding direct execution from the working tree:
|
||||
|
||||
1. fix the `check-helper-drift.sh` environment assignment that suppresses version diagnostics.
|
||||
2. strip 20 dangling Excalidraw `node_modules` symlinks.
|
||||
3. add `tools/**/node_modules/` to the brain `.gitignore`.
|
||||
4. keep the reviewed `package-lock.json` as the reproducible dependency contract.
|
||||
5. correct the baseline report's misleading path-count headline.
|
||||
6. move `ci-publish-watch.sh` credential headers from process arguments to curl stdin
|
||||
configuration when that suite is changed.
|
||||
|
||||
### SRC-REQ-003: Source is not installation
|
||||
|
||||
Runtime code is loaded from reviewed package or installed artifacts, not directly from a mutable
|
||||
multi-writer checkout as the final design. Any transitional direct execution requires:
|
||||
|
||||
- a protected-path review rule.
|
||||
- an accepted digest anchored outside the synced tree in reviewed package metadata or Stack source.
|
||||
- verification before execution, including every credential-helper invocation.
|
||||
- a periodic verifier whose mismatch alert reaches a human.
|
||||
- a stated removal point.
|
||||
|
||||
### SRC-REQ-004: Credential helper integrity
|
||||
|
||||
The host-wide git credential helper and its accepted pin cannot be replaceable by the same synced
|
||||
commit. Transition requires an independently anchored verifier and alert. Final state moves the
|
||||
helper into the reviewed runtime installation or another explicitly protected location.
|
||||
|
||||
## 12. Migration and decommission
|
||||
|
||||
### MIG-REQ-001: Consumer census
|
||||
|
||||
Inventory every direct caller of `~/.config/mosaic/tools`, grouped as:
|
||||
|
||||
- skills and guides.
|
||||
- hooks and generated harness configuration.
|
||||
- systemd units and timers.
|
||||
- launchers and provisioning.
|
||||
- tests and CI.
|
||||
- direct agent commands.
|
||||
- private tool-to-tool calls.
|
||||
- production consumers.
|
||||
|
||||
Each census run creates a fresh randomized planted legacy reference at a unique path and is valid
|
||||
only when the detector reports that run's exact plant. Every host at every site still running the
|
||||
installed legacy tree is censused independently. An empty result without the fresh control, or a
|
||||
zero from only one host, is not evidence.
|
||||
|
||||
### MIG-REQ-002: Risk-ordered waves
|
||||
|
||||
Migrate in this order:
|
||||
|
||||
1. read-only status, health, list, and view.
|
||||
2. bounded CI and communications.
|
||||
3. issue, pull-request, and milestone mutation.
|
||||
4. credentialed infrastructure.
|
||||
5. merge, deployment, identity, authorization, and secret management.
|
||||
|
||||
Each wave proves contract parity before consumer cutover. Waves 1 through 3 may use local mode with
|
||||
acting-seat credentials. Wave 4 cutover is broker-only when it uses a shared or service credential.
|
||||
Wave 5 cutover is always broker-only and begins only after the M6 `mosaicd` boundary gate passes.
|
||||
|
||||
### MIG-REQ-003: Protected consumers
|
||||
|
||||
- M365 credentials, AD status, and six production consumers remain Peggy-owned until exact signoff
|
||||
and timer-aware tests.
|
||||
- Fleet-doctor, seat-service, Woodpecker extras, and their units remain Veronica-owned until exact
|
||||
replacement proof and named handoff.
|
||||
- Brain guards are excluded from wholesale removal.
|
||||
- The active A2 hold applies to `tools/seat-service/` and
|
||||
`fleet/bin/launch-seat-claude.sh` only.
|
||||
- Fleet configuration issue `#758` retains its own normative contract and delivery DAG. T78 does
|
||||
not re-scope or absorb its missing `inspect` and `validate` verbs. T78 measures and consumes the
|
||||
stable fleet surface only after `#758` completion or an explicit owner handoff.
|
||||
|
||||
### MIG-REQ-004: Compatibility and deprecation
|
||||
|
||||
Compatibility shims are private and time-bounded. Each shim:
|
||||
|
||||
- names its public replacement.
|
||||
- preserves existing safety behavior.
|
||||
- emits a machine-detectable deprecation diagnostic without corrupting JSON output.
|
||||
- has a measured consumer and removal issue.
|
||||
- cannot be used to add new direct callers.
|
||||
|
||||
### MIG-REQ-005: Final removal
|
||||
|
||||
The installed `~/.config/mosaic/tools` script surface is removed only after:
|
||||
|
||||
1. all active consumers use official capabilities.
|
||||
2. the census reports zero with a firing planted control.
|
||||
3. Constitution and wrapper-first gates are mechanically enforced by the CLI path.
|
||||
4. systemd units are regenerated, daemon-reloaded, re-enabled, and behavior-tested.
|
||||
5. fleet-doctor state is preserved.
|
||||
6. clean install, upgrade, rollback, and stale-install tests pass.
|
||||
7. user, admin, developer, API, and migration documentation is current.
|
||||
|
||||
## 13. Testing requirements
|
||||
|
||||
### TST-REQ-001: Resolver
|
||||
|
||||
- exact schema-v1 valid fixture.
|
||||
- absent, null, exact-v1, and unknown-non-null `$schema` cases.
|
||||
- unknown top-level and nested key warnings with full-path diagnostics.
|
||||
- `mosaic registry validate` lint rejection of the same unknown-key fixture.
|
||||
- invalid URL, path, socket, and type failures.
|
||||
- every precedence branch, including present-empty and present-invalid override denial without
|
||||
fallback.
|
||||
- two valid roots.
|
||||
- container topology with a read-only internal registry and no host registry path.
|
||||
- no credential value accepted or emitted.
|
||||
- control proving the invalid fixture fails.
|
||||
|
||||
### TST-REQ-002: Capability catalog
|
||||
|
||||
- command and capability ID uniqueness.
|
||||
- every public command documented.
|
||||
- no orphan catalog record.
|
||||
- parser, policy, help, and docs consume the same definition.
|
||||
- unauthorized lane and scope denial.
|
||||
- unknown capability denial.
|
||||
- topology-selected mode never falls back when the required broker is unavailable.
|
||||
- shared, service, operator, and admin credential classes reject local mode.
|
||||
|
||||
### TST-REQ-003: Pilot
|
||||
|
||||
- issue list and view against a valid configured instance.
|
||||
- invalid instance and repository denial.
|
||||
- comment success with provider response-shape and body-digest confirmation.
|
||||
- comment denial before provider access.
|
||||
- post-request uncertainty without retry, plus provider-native same-key and
|
||||
`uncertain-no-retry` read-back reconciliation cases.
|
||||
- credential, cookie, token, comment-body, child-argv, captured-stderr, and shell-trace redaction.
|
||||
- local results prove `identityTrust: local-asserted` and `audit.recorded: false`.
|
||||
- broker-stub results prove derived-identity precedence and reject unconfirmed
|
||||
`audit.recorded: true`.
|
||||
- user-editable endpoint changes cannot redirect a shared or service credential.
|
||||
- local-adapter and broker-stub request/result seam parity at M3.
|
||||
- live local-adapter and `mosaicd` contract parity at M6.
|
||||
|
||||
### TST-REQ-004: Migration
|
||||
|
||||
- fresh randomized consumer-census plant detected independently on every affected host and site.
|
||||
- compatibility diagnostics in table and JSON modes.
|
||||
- systemd timer and restart behavior.
|
||||
- production M365/AD consumer probes.
|
||||
- fleet-doctor digest-state preservation.
|
||||
- clean install, upgrade, rollback, stale install, and greenfield operation.
|
||||
- representative container without legacy tools mounted.
|
||||
- representative container mounts no shared or fleet tmux socket, and any temporary tmux exception
|
||||
uses only the named adapter's dedicated per-seat socket.
|
||||
|
||||
### TST-REQ-005: Delivery gates
|
||||
|
||||
Every source card requires focused tests, repository quality gates, independent code review,
|
||||
security review for authorization, credentials, transport, or integrity surfaces, reviewed squash
|
||||
PR to `next`, terminal-green CI, and linked-issue closure.
|
||||
|
||||
## 14. Documentation requirements
|
||||
|
||||
The workstream updates in the same delivery sequence:
|
||||
|
||||
- official CLI help.
|
||||
- `docs/PRD.md` workstream pointer.
|
||||
- `docs/ROADMAP.md` parallel-track entry.
|
||||
- `docs/SITEMAP.md` requirements link.
|
||||
- user guide commands and deprecation behavior.
|
||||
- administrator configuration, migration, and recovery.
|
||||
- developer architecture, capability authoring, schemas, and adapter contracts.
|
||||
- API and machine-readable result schemas.
|
||||
- release notes.
|
||||
- T78 program-map and unified-roadmap records.
|
||||
|
||||
No command is public until its help, structured output, authorization behavior, and documentation
|
||||
are present.
|
||||
|
||||
## 15. Delivery stages
|
||||
|
||||
| Stage | Scope | Exit gate |
|
||||
| ----- | ------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ |
|
||||
| M0 | Register mission, reconcile ownership, establish and review source baseline, publish requirements and tracking | Reviewed contract merged, dedicated milestone and task graph present |
|
||||
| M1 | Inventory consumers, normalize baseline, freeze registry resolver, capability catalog, policy, and runtime-integrity contracts | Typed interfaces and migration census reviewed |
|
||||
| M2 | Implement resolver, catalog, common result envelope, and adapter interface | Contract and two-root tests green |
|
||||
| M3 | Deliver pilot issue list, view, and comment | Allowed and denied controls, uncertainty behavior, docs, review, CI |
|
||||
| M4 | Migrate waves 1 through 3, prepare wave 4 private adapters without shared-credential cutover | Per-suite owner handoff and parity evidence |
|
||||
| M5 | Cut eligible consumers and generate harness policy | No new direct references, compatibility callers measured |
|
||||
| M6 | Prove representative container and `mosaicd` seam, then cut over shared-credential wave 4 and all wave 5 capabilities | Boundary, authorization, audit, and parity tests green |
|
||||
| M7 | Remove installed legacy script tree | Zero callers, migration and rollback evidence, docs and release gates complete |
|
||||
|
||||
## 16. Workstream acceptance
|
||||
|
||||
T78 completes only when:
|
||||
|
||||
1. the official TypeScript CLI exposes documented first-class capability groups.
|
||||
2. the central registry resolver and capability catalog are single typed authorities.
|
||||
3. two-root and container-topology tests prove no command-path hard-coding.
|
||||
4. authorization has allowed and denied situational evidence.
|
||||
5. agent-visible output, logs, and process arguments contain no credential values.
|
||||
6. local and `mosaicd` modes share one request and result contract and report their mode honestly.
|
||||
7. a representative rootless seat container performs granted operations without legacy tools,
|
||||
host credentials, or a container-runtime socket.
|
||||
8. tmux and fleet-comms can be replaced without changing public communications callers.
|
||||
9. the legacy consumer census reaches zero with a discriminating control.
|
||||
10. the installed `~/.config/mosaic/tools` script surface is removed.
|
||||
11. independent review passes for every source partition.
|
||||
12. all PRs are squash-merged to `next`, terminal CI is green, and linked issues are closed.
|
||||
|
||||
## 17. Contract-freeze status
|
||||
|
||||
The architecture inputs are frozen for independent review:
|
||||
|
||||
1. The central-registry resolver has joint C1, amended C2, and C3 approval.
|
||||
2. User-editable `config.json` is not authorization policy. Target grant authority belongs to
|
||||
`mosaicd`. Local mode is explicitly non-authoritative.
|
||||
3. Registry, capability, and adapter source boundaries are packaged TypeScript modules. Brain tools
|
||||
remain working source and temporary private adapters, not the final runtime contract.
|
||||
4. Issue `#758` remains an independent dependency and is not re-scoped into T78.
|
||||
|
||||
Provider tracking remains operationally blocked until the `orch-01` Mosaic Stack credential slot is
|
||||
minted. This does not weaken the contract or authorize implementation before reviewed publication.
|
||||
@@ -1,380 +0,0 @@
|
||||
# Hierarchy Schema Contract (D2)
|
||||
|
||||
Status: DRAFT — awaiting ratification (webui-audit S2, contract 1 of 9).
|
||||
Authority: PRD D2/D9/D13 (Part I §4) and the native-kanban SOT Amendment A1
|
||||
(`docs/requirements/native-kanban-sot.md` §8, ratified 2026-08-25). This
|
||||
document turns the ratified hierarchy into a concrete schema contract:
|
||||
tables, cardinalities, constraints, and ownership/transfer semantics. It is
|
||||
the prerequisite for the hierarchy command family and for the RBAC grant
|
||||
model (contract 2, `docs/requirements/rbac-grant-model.md`).
|
||||
|
||||
Revision 2 (independent review, GPT-5.6 terra): tenancy-FK exemption made
|
||||
explicit (§1.1); record class extended to include `hierarchy_grants`
|
||||
(§1.1); provenance corrections on legacy tables and the planning `projects`
|
||||
table (§1.3, §2 naming note); NOT NULL and `NULLS NOT DISTINCT` grant
|
||||
uniqueness (§2.6, §3.2); grant FK delete actions split cascade/restrict
|
||||
(§3.3); transfer transaction includes its audit write (§4.3); ownership
|
||||
invariant completed via contract 2 with the both-sides rule marked as new
|
||||
policy (§4.2, §4.4); hierarchy audit brought under REQ-AUD-001-equivalent
|
||||
guarantees with deletion-safe linkage (§5.2); roll-up never-a-write restored
|
||||
to full A1 strength (§5.4); §6 rebuilt with bounded observables for every
|
||||
MUST (allowlist, command surface, audit, corrected cardinality witness).
|
||||
|
||||
Revision 3 (terra re-review residuals): §4.3 transfer write inventory
|
||||
reconciled with §5.2 — the transaction's writes are the single class-row
|
||||
mutation plus that mutation's §5.2 audit writes (event + outbox record),
|
||||
not "exactly two writes"; §6.3 extended with a closed writer-coverage
|
||||
witness so an unregistered internal writer cannot pass a registered-route
|
||||
inventory. (Terra's finding-8 residual — a stale contract 2 §7.8 backlink
|
||||
to contract 1 §6.2 — was already fixed in contract 2 revision 2, which
|
||||
cites §6.5; measured against `origin/contract/rbac-grants` head
|
||||
`501112d2`.)
|
||||
|
||||
Revision 4 (terra r3 residual F7): the §6.3(b) writer-coverage assertion
|
||||
extended to raw SQL — it now also fails on class-table name literals
|
||||
inside SQL strings or tagged SQL templates outside the allowlist, so a
|
||||
raw-SQL writer that touches no schema symbol is still caught.
|
||||
|
||||
Revision 5 (terra r4 residual F7): §6.3(b) gains a third prong — any
|
||||
raw-SQL execution primitive outside the allowlist fails the assertion
|
||||
regardless of its SQL content, closing the evasion where a
|
||||
dynamically constructed table name carries neither a schema symbol nor
|
||||
a class-table literal. The detection claim is now coextensive with
|
||||
what the three prongs statically see.
|
||||
|
||||
Revision 6 (terra r5 residual F7 + new F8): the "two prongs" wording
|
||||
corrected to three (F8); §6.3(b) gains the allowlist composition rules
|
||||
(no generic raw-SQL helper is allowlisted; an allowlisted module may
|
||||
not export caller-supplied-SQL execution) and fails outright on
|
||||
runtime code-construction primitives; the detection claim is scoped
|
||||
honestly to the stated syntactic forms, with evasions beyond static
|
||||
reach assigned to §5.1 review/audit rather than claimed for CI.
|
||||
|
||||
Revision 7 (terra r6 new F9): the false-positive remedy no longer
|
||||
contradicts the composition rules — legitimate non-hierarchy raw
|
||||
execution (e.g. the db package's migration runner) is dispositioned
|
||||
onto a second closed enumerated list, the infrastructure register,
|
||||
exempt from prong (iii) only, still bound by prongs (i)/(ii), barred
|
||||
from the writer allowlist, and importable only by registered modules
|
||||
or the operational entry points.
|
||||
|
||||
Revision 8 (terra r7 residual F9): the register's import rule made
|
||||
satisfiable by the live tree — imports are checked re-export-aware
|
||||
(package barrels followed), and each registered module carries its own
|
||||
closed importer enumeration, which may name operational entry points
|
||||
such as the Gateway's startup migration hook; named importers stay
|
||||
subject to prongs (i)/(ii) and gain no writer standing.
|
||||
|
||||
Revision 9 (terra r8 F10): revision 8 called the Gateway database
|
||||
module the runner's "one live importer today". That was false — the
|
||||
measured production importer set has four members. The enumeration
|
||||
example now lists the complete measured set, and the import analysis
|
||||
is extended to resolve literal dynamic `import()` routes, which two of
|
||||
the four members use.
|
||||
|
||||
Scope: the tenancy/authorization structure record class — companies,
|
||||
estates, platform-projects, workspaces, hierarchy grants, their parentage,
|
||||
and constraints. Out of scope: the RBAC grant vocabulary and evaluation
|
||||
semantics (contract 2), roll-up projection semantics (contract 8), kanban
|
||||
planning entities inside workspaces (SOT §5), migration or retirement of
|
||||
legacy flat data (future work; see §1.3).
|
||||
|
||||
## 1. Record class and placement
|
||||
|
||||
1. The **tenancy/authorization structure record class** defined by
|
||||
Amendment A1 §8.1.2 comprises five tables: the four node tables of §2
|
||||
AND `hierarchy_grants` (§3) — A1 includes hierarchy-level access grants
|
||||
in the class. Every rule addressed to "the class" in this contract
|
||||
(payload prohibition, mutation path, audit) binds all five tables. Class
|
||||
rows carry parentage, naming, grant, and audit-linkage data only — never
|
||||
task, plan, or any business/orchestration payload.
|
||||
References from business/orchestration rows into the class are limited
|
||||
to exactly one form: the canonical `workspace_id` tenancy column that
|
||||
REQ-TEN-001 requires on every canonical row, referencing
|
||||
`workspaces.id`. No business/orchestration row may reference a company,
|
||||
estate, platform-project, or grant id in any position, and no
|
||||
business/orchestration row may reference a workspace id in any
|
||||
non-tenancy position (dependency, claim target, work subject).
|
||||
2. Hierarchy records are NOT workspace-scoped rows: REQ-TEN-001's
|
||||
`workspace_id` obligation binds business/orchestration rows and does not
|
||||
apply to this class (A1 §8.1.2). The `workspaces` table itself is the
|
||||
anchor the obligation points at.
|
||||
3. The legacy flat tables (`teams`, and the Brain planning `projects` table
|
||||
in `packages/db/src/schema.ts`) are not part of this class. What A1
|
||||
§8.1.4 pins is narrower: the planning `projects` table and
|
||||
`platform_projects` stay distinct tables. This contract adds, as new
|
||||
policy ratified here: neither `teams` nor `projects` is repurposed as a
|
||||
hierarchy table. Their eventual migration or retirement is future work
|
||||
that no existing REQ assigns; it is out of scope here.
|
||||
|
||||
## 2. Tables and cardinalities
|
||||
|
||||
Naming: the level above workspaces is `platform_projects`, per A1 §8.1.4.
|
||||
The existing `projects` table is Brain planning data (so labeled in
|
||||
`packages/db/src/schema.ts`; it carries no `workspace_id`), and the schema
|
||||
MUST NOT merge the two. (A rename of either remains an implementation-PR
|
||||
decision under A1; this contract pins only that they stay distinct tables.)
|
||||
|
||||
1. `companies` — id (uuid pk), name, slug (unique per deployment),
|
||||
created_at, updated_at. N per deployment (D2).
|
||||
2. `estates` — id, name, slug, `company_id` NOT NULL →
|
||||
`companies.id` ON DELETE RESTRICT. Exactly one company per estate; a
|
||||
company holds any number of estates.
|
||||
3. `platform_projects` — id, name, slug, `estate_id` NOT NULL →
|
||||
`estates.id` ON DELETE RESTRICT. Exactly one estate per
|
||||
platform-project; an estate holds any number of platform-projects.
|
||||
4. `workspaces` — id, name, slug, `platform_project_id` NOT NULL →
|
||||
`platform_projects.id` ON DELETE RESTRICT. Exactly one platform-project
|
||||
per workspace. This table is the referent of every `workspace_id` column
|
||||
the SOT requires on canonical rows.
|
||||
5. **Chain resolution is by construction.** Because every parent FK is NOT
|
||||
NULL and single-valued (one FK column, no parentage edge tables, no
|
||||
multi-parent forms, no nullable "detached" states), each workspace
|
||||
resolves to exactly one platform-project → estate → company chain (A1
|
||||
§8.3 acceptance 1). One-parent-per-child is the constrained direction;
|
||||
many children per parent is valid data.
|
||||
6. **Slug scoping.** All `name` and `slug` columns are NOT NULL.
|
||||
`estates.slug` is unique within its company, `platform_projects.slug`
|
||||
within its estate, `workspaces.slug` within its platform-project
|
||||
(composite unique constraints). Display names are unconstrained beyond
|
||||
NOT NULL.
|
||||
7. No hierarchy table carries a `metadata` jsonb column or any
|
||||
free-form payload field. The columns declared in this section and §3
|
||||
are exhaustive: a class table's column set is exactly its declared set
|
||||
(verified per §6.2) — nothing else (A1 §8.1.2).
|
||||
|
||||
## 3. Grant attachment points
|
||||
|
||||
The grant vocabulary (which roles exist, what each permits, how evaluation
|
||||
and revocation work) is contract 2. This contract pins only the schema
|
||||
shape contract 2 attaches to:
|
||||
|
||||
1. `hierarchy_grants` — id, subject (exactly one of `user_id` → `users.id`,
|
||||
`team_id` → `teams.id`; CHECK-enforced exactly-one-of), target (exactly
|
||||
one of `company_id`, `estate_id`, `platform_project_id`;
|
||||
CHECK-enforced exactly-one-of), `role` (text NOT NULL; vocabulary and
|
||||
its CHECK constraint owned by contract 2 §2), `granted_by` NOT NULL →
|
||||
`users.id`, created_at.
|
||||
2. Uniqueness: at most one grant row per (subject, target, role). Because
|
||||
the subject and target columns are nullable by design, ordinary
|
||||
PostgreSQL composite uniqueness treats NULLs as distinct and would not
|
||||
enforce this. The implementation MUST use a single
|
||||
`UNIQUE NULLS NOT DISTINCT` constraint across (`user_id`, `team_id`,
|
||||
`company_id`, `estate_id`, `platform_project_id`, `role`) or six
|
||||
equivalent partial unique indexes (one per subject×target form). The
|
||||
pinned Drizzle ORM supports `nullsNotDistinct()`.
|
||||
3. Delete actions are split by column class:
|
||||
- Target FKs (`company_id`, `estate_id`, `platform_project_id`):
|
||||
ON DELETE CASCADE — the one permitted cascade in this class. A grant
|
||||
on a deleted node is meaningless and fail-open if retained. Cascaded
|
||||
grant deletions are audited per §5.2.
|
||||
- Principal FKs (`user_id`, `team_id`, `granted_by`): ON DELETE
|
||||
RESTRICT. The identity contract (§7.3) gates user deletion today and
|
||||
defines no team-deletion rule; this contract does not invent one.
|
||||
These FKs stay RESTRICT until an explicit deletion-and-retention
|
||||
contract ratifies otherwise.
|
||||
4. Workspace-level access is evaluated, not stored here: a grant at any of
|
||||
the three levels evaluates down the chain to workspace-scoped
|
||||
authorization (A1 §8.1.3). No `workspace_id` column exists on
|
||||
`hierarchy_grants` — workspace membership (REQ-ID-001) remains its own
|
||||
mechanism inside the SOT schema, and the chain adds where grants can be
|
||||
declared, never a bypass.
|
||||
|
||||
## 4. Ownership and transfer
|
||||
|
||||
"Assets are transferable subject to the structure" (PRD Part I §4):
|
||||
|
||||
1. A transfer changes exactly one parent FK on exactly one hierarchy row:
|
||||
workspace → new platform-project, platform-project → new estate, estate
|
||||
→ new company. Nothing else in the class or the SOT changes: business
|
||||
and orchestration rows inside affected workspaces are untouched, keep
|
||||
their `workspace_id`, and never cross a workspace boundary (A1 §8.1.3
|
||||
"chain maintenance").
|
||||
2. Transfer authorization requires authority over BOTH the source and the
|
||||
destination parent. This both-sides predicate is **new policy
|
||||
introduced by this contract pair** (D2/A1 do not state it); its
|
||||
evaluation semantics are contract 2 §5. The structural half — that the
|
||||
transfer command evaluates it before mutating — binds here.
|
||||
3. A transfer transaction mutates exactly one class-table row — the
|
||||
single-row parent-FK update — and contains, beyond that, only the
|
||||
§5.2 audit writes for that mutation (the audit event and its
|
||||
hierarchy-outbox record, committing in the same transaction). No other
|
||||
class, business, or orchestration row changes. There are no multi-row
|
||||
transfer batches at the schema level; bulk moves are N audited
|
||||
transfers.
|
||||
4. Hierarchy records have no `owner_id`. Ownership in the hierarchy IS the
|
||||
grant structure: a "company owner" is a subject with an `owner` grant
|
||||
on that company or an ancestor (contract 2 §2), not a column. The
|
||||
ownership invariant across the contract pair: a node may hold zero
|
||||
direct owner grants (authority can derive from an ancestor grant); node
|
||||
creation names the initial `owner` grant in the same audited operation
|
||||
and the wizard seeds the first company's owner the same way (contract 2
|
||||
§4.3); transfer and revocation semantics are contract 2 §§5–6. This
|
||||
avoids column-encoded authority of the kind the legacy schema carries
|
||||
(`teams.owner_id` and `teams.manager_id` are required user FKs, and
|
||||
`team_members.role` is a further authority field — none of them
|
||||
evaluable under a grant model).
|
||||
|
||||
## 5. Mutation path, audit, and deletion
|
||||
|
||||
1. All hierarchy mutations flow through the same sole-writable-SOT,
|
||||
fail-closed, audited Gateway command path as everything else (A1 §8.2.3,
|
||||
REQ-API-001). No direct-DB writers, no raw CRUD endpoints.
|
||||
2. **Audit parity.** A1 §8.2 leaves every pre-existing REQ binding, so
|
||||
hierarchy mutations get REQ-AUD-001's guarantees, not a weakened
|
||||
substitute. Concretely:
|
||||
- Every create, rename, transfer, grant create/change/revoke, and
|
||||
delete — including every grant deletion cascaded by a node delete —
|
||||
emits a semantic audit event carrying actor, verb, target, and (for
|
||||
transfers) source and destination parents, with the correlation,
|
||||
causation, idempotency, and per-target ordering guarantees REQ-AUD-001
|
||||
defines.
|
||||
- The state change and its audit event(s) commit in the same
|
||||
transaction, delivered through a transactional outbox. Hierarchy
|
||||
events are not workspace-scoped rows and do not ride the workspace
|
||||
outbox; they get an equivalent hierarchy outbox under the same
|
||||
append-only, same-transaction rules.
|
||||
- **Deletion-safe linkage:** audit events reference their target by an
|
||||
immutable snapshot (id, slug, and parent chain at event time), never
|
||||
by a foreign key into the class tables, so append-only events survive
|
||||
the deletion of their target.
|
||||
3. Deletion is fail-closed bottom-up: a hierarchy record with children
|
||||
cannot be deleted (RESTRICT FKs, §2). Deleting a workspace is a SOT-side
|
||||
operation subject to the kanban SOT's own rules and is not granted any
|
||||
new semantics by this contract.
|
||||
4. **Roll-up is never a write** (A1 §8.2.2, preserved at full strength). A
|
||||
roll-up read mutates nothing — not hierarchy state, and not business or
|
||||
orchestration state: it must not mutate, claim, order, or gate
|
||||
workspace work. Contract 8 owns projection details but cannot narrow
|
||||
this rule. This contract additionally guarantees the chain roll-ups
|
||||
aggregate over is unique and non-null (§2.5).
|
||||
|
||||
## 6. Verification requirements
|
||||
|
||||
Binding on the implementing PRs (extends A1 §8.3):
|
||||
|
||||
1. Schema witnesses (real PostgreSQL, §6.8): chain construction — insert
|
||||
with a null parent FK refused; insert with one valid parent accepted;
|
||||
two siblings under one parent accepted (the control proving the
|
||||
constraint rejects only what §2.5 forbids); catalog assertion that each
|
||||
child table has exactly one parent-FK column and no parentage edge
|
||||
table exists. Composite slug uniqueness per parent (duplicate slug
|
||||
under same parent refused; same slug under different parents accepted).
|
||||
Grant CHECKs: exactly-one-of subject and exactly-one-of target each
|
||||
witnessed (zero and two set → refused). Grant uniqueness: a duplicate
|
||||
(subject, target, role) row refused for each of the six subject×target
|
||||
forms, proving NULLS-NOT-DISTINCT semantics; NOT NULL on `role`,
|
||||
`granted_by`, and all `name`/`slug` columns witnessed.
|
||||
2. Column allowlist: an information_schema assertion that each class
|
||||
table's column set is exactly the set declared in §2/§3 — the bounded
|
||||
observable for no-payload (§2.7) and no-`owner_id` (§4.4).
|
||||
3. Command surface: two witnesses, both required (§5.1). (a) Route
|
||||
inventory: an assertion over the Gateway's registered hierarchy
|
||||
routes/commands proving the registered mutation surface is exactly the
|
||||
declared hierarchy command family — no generic CRUD endpoint. (b)
|
||||
Writer coverage — the closed allowlist a route inventory cannot
|
||||
provide: a static CI assertion over the Gateway and package sources
|
||||
with three prongs, each bound to one explicitly enumerated allowlist
|
||||
of hierarchy command/repository modules. (i) Symbol prong: write
|
||||
references to the class-table schema symbols (insert, update, delete)
|
||||
occur only in allowlisted modules. (ii) Literal prong: a class-table
|
||||
name appearing inside a SQL string or tagged SQL template outside the
|
||||
allowlist fails the assertion — this is what catches a raw-SQL writer
|
||||
that references no schema symbol. (iii) Raw-execution prong: any call
|
||||
to a raw-SQL execution primitive (the ORM's raw/unsafe constructors,
|
||||
driver-level query/execute) outside the allowlist fails the
|
||||
assertion, regardless of what the SQL string contains or how it is
|
||||
constructed — the call site is statically detectable even when a
|
||||
dynamically assembled table name is not, so a raw writer with a
|
||||
runtime-built identifier is caught by its primitive, not its
|
||||
payload. Two composition rules keep prong (iii) meaningful: the
|
||||
allowlist names hierarchy command/repository modules only — a
|
||||
generic raw-SQL helper or database-utility module is never
|
||||
allowlisted; and an allowlisted module MUST NOT export a function
|
||||
that executes caller-supplied SQL (such an export is itself a
|
||||
raw-execution primitive, and the exporting module is treated as
|
||||
unallowlisted for prong (iii) if it does). Legitimate raw execution
|
||||
that is not a hierarchy writer — e.g. the migration runner in the
|
||||
db package — lives on a second, separately enumerated
|
||||
**infrastructure register**, distinct from the writer allowlist and
|
||||
equally closed. A registered module is exempt from prong (iii) only:
|
||||
prongs (i) and (ii) apply to it with no exemption, so it can hold no
|
||||
class-table schema symbol or class-table SQL literal, and it can
|
||||
never appear on the writer allowlist. To close the laundering path,
|
||||
the same assertion checks imports, and the import analysis is
|
||||
**re-export-aware**: it follows package barrels and re-exports, so a
|
||||
route hidden behind an index module is still a route — and it
|
||||
resolves literal dynamic imports the same way: an
|
||||
`await import('<literal specifier>')` is an import edge like any
|
||||
static import, not an evasion of the analysis (a dynamic import of
|
||||
the db package whose specifier is not a literal fails the assertion
|
||||
outright, because it makes the import graph unanalyzable). A
|
||||
registered module may be imported only by other registered modules
|
||||
or by importers named on that module's own closed importer
|
||||
enumeration in the register — operational entry points such as the
|
||||
migration/bootstrap CLI or the Gateway's startup migration hook.
|
||||
The enumeration names the complete permitted production consumer
|
||||
set, and completeness is measured, not asserted: the migration
|
||||
runner's measured production importer set today has four members —
|
||||
the Gateway database module (reached through the db package
|
||||
barrel), the storage package's Postgres adapter, and two mosaic CLI
|
||||
commands, the fleet-backlog command and the gateway verify command,
|
||||
both routed through literal dynamic imports of the db package — so
|
||||
its enumeration names those four. A module that only receives the
|
||||
runner's functions by parameter injection (the gateway schema-check
|
||||
module takes them as arguments from the verify command) has no
|
||||
import edge of its own and is not enumerated. Any import route
|
||||
outside the enumeration fails the assertion. Being a
|
||||
named importer confers nothing else: the importer stays fully
|
||||
subject to prongs (i) and (ii), gains no writer-allowlist standing,
|
||||
and whether it uses the registered module beyond its operational
|
||||
purpose is a §5.1 review question, not a static claim. Runtime code-construction
|
||||
primitives (`eval`, `new Function`) anywhere in the scanned sources
|
||||
fail the assertion outright, allowlist or not. Schema definitions
|
||||
and generated migrations are excluded from the literal prong; a
|
||||
false positive is resolved in the same PR by adding the module to
|
||||
the one enumerated list its role permits — the writer allowlist for
|
||||
a hierarchy command/repository module, the infrastructure register
|
||||
for non-hierarchy raw execution — never by weakening the assertion,
|
||||
and neither list may take a module the composition rules bar from
|
||||
it. Both lists are closed, and the assertion's detection
|
||||
claim is exactly its prongs: it statically surfaces every writer
|
||||
expressed as a schema-symbol reference, a class-table SQL literal, a
|
||||
raw-execution call site, or runtime code construction. An evasion
|
||||
engineered outside those syntactic forms is a §5.1 violation that
|
||||
review and audit own — the witness does not claim to catch what
|
||||
static analysis cannot see, and any such evasion found later is
|
||||
corrected as a conformance defect, not grandfathered.
|
||||
4. Audit witnesses: for each mutation class (create, rename, transfer,
|
||||
grant create/change/revoke, delete) — the event exists after commit
|
||||
with actor/verb/target and same-transaction atomicity; a rolled-back
|
||||
mutation leaves no event (rollback witness); a node delete's cascaded
|
||||
grant deletions are each covered by events; events survive deletion of
|
||||
their target (query the events of a deleted node).
|
||||
5. Transfer tests: parent-FK update moves the subtree resolution and
|
||||
modifies zero business/orchestration rows (row-count and content
|
||||
assertions on workspace contents before/after); transfer without
|
||||
authority on the source or on the destination side is refused (with
|
||||
contract 2 §7.8).
|
||||
6. Deletion tests: delete with children refused at the database level;
|
||||
delete of a leaf cascades its grants and nothing else; deleting a user
|
||||
or team that is a grant subject (or `granted_by` referent) is refused
|
||||
(RESTRICT witnesses for §3.3).
|
||||
7. Negative tests: no business/orchestration table accepts a company,
|
||||
estate, platform-project, or grant id in any reference position, and
|
||||
none accepts a workspace id in any non-tenancy position; the canonical
|
||||
tenancy FK control — a business row inserted with a valid
|
||||
`workspace_id` succeeds, with an invalid one is refused; roll-up
|
||||
endpoints mutate no canonical state anywhere (assert zero writes across
|
||||
hierarchy AND workspace tables, not hierarchy only); readers see
|
||||
aggregates only over workspaces they are authorized on, with no
|
||||
cross-tenant existence oracles (A1 §8.3 acceptance 3).
|
||||
8. Real-PostgreSQL coverage for every constraint witness (unique/CHECK/
|
||||
RESTRICT/NULLS NOT DISTINCT behavior), using the `ci-postgres` service
|
||||
in the `test` CI step; mocked specs cannot witness database constraints.
|
||||
|
||||
## Ruling request
|
||||
|
||||
Ratify sections 1–6 as written, with one decision embedded: hierarchy
|
||||
records carry no owner column — ownership is expressed solely through
|
||||
grants (§4.4) — say "agreed" or name the ownership model you want.
|
||||
@@ -1,63 +0,0 @@
|
||||
CREATE TABLE "companies" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"name" text NOT NULL,
|
||||
"slug" text NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
CONSTRAINT "companies_slug_unique" UNIQUE("slug")
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "estates" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"name" text NOT NULL,
|
||||
"slug" text NOT NULL,
|
||||
"company_id" uuid NOT NULL,
|
||||
CONSTRAINT "estates_company_slug_uniq" UNIQUE("company_id","slug")
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "hierarchy_grants" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"user_id" text,
|
||||
"team_id" uuid,
|
||||
"company_id" uuid,
|
||||
"estate_id" uuid,
|
||||
"platform_project_id" uuid,
|
||||
"role" text NOT NULL,
|
||||
"granted_by" text NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
CONSTRAINT "hierarchy_grants_subject_target_role_uniq" UNIQUE NULLS NOT DISTINCT("user_id","team_id","company_id","estate_id","platform_project_id","role"),
|
||||
CONSTRAINT "hierarchy_grants_subject_check" CHECK (num_nonnulls(user_id, team_id) = 1),
|
||||
CONSTRAINT "hierarchy_grants_target_check" CHECK (num_nonnulls(company_id, estate_id, platform_project_id) = 1)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "platform_projects" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"name" text NOT NULL,
|
||||
"slug" text NOT NULL,
|
||||
"estate_id" uuid NOT NULL,
|
||||
CONSTRAINT "platform_projects_estate_slug_uniq" UNIQUE("estate_id","slug")
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "workspaces" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"name" text NOT NULL,
|
||||
"slug" text NOT NULL,
|
||||
"platform_project_id" uuid NOT NULL,
|
||||
CONSTRAINT "workspaces_platform_project_slug_uniq" UNIQUE("platform_project_id","slug")
|
||||
);
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "estates" ADD CONSTRAINT "estates_company_id_companies_id_fk" FOREIGN KEY ("company_id") REFERENCES "public"."companies"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "hierarchy_grants" ADD CONSTRAINT "hierarchy_grants_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "hierarchy_grants" ADD CONSTRAINT "hierarchy_grants_team_id_teams_id_fk" FOREIGN KEY ("team_id") REFERENCES "public"."teams"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "hierarchy_grants" ADD CONSTRAINT "hierarchy_grants_company_id_companies_id_fk" FOREIGN KEY ("company_id") REFERENCES "public"."companies"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "hierarchy_grants" ADD CONSTRAINT "hierarchy_grants_estate_id_estates_id_fk" FOREIGN KEY ("estate_id") REFERENCES "public"."estates"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "hierarchy_grants" ADD CONSTRAINT "hierarchy_grants_platform_project_id_platform_projects_id_fk" FOREIGN KEY ("platform_project_id") REFERENCES "public"."platform_projects"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "hierarchy_grants" ADD CONSTRAINT "hierarchy_grants_granted_by_users_id_fk" FOREIGN KEY ("granted_by") REFERENCES "public"."users"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "platform_projects" ADD CONSTRAINT "platform_projects_estate_id_estates_id_fk" FOREIGN KEY ("estate_id") REFERENCES "public"."estates"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "workspaces" ADD CONSTRAINT "workspaces_platform_project_id_platform_projects_id_fk" FOREIGN KEY ("platform_project_id") REFERENCES "public"."platform_projects"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
CREATE INDEX "hierarchy_grants_company_id_idx" ON "hierarchy_grants" USING btree ("company_id");--> statement-breakpoint
|
||||
CREATE INDEX "hierarchy_grants_estate_id_idx" ON "hierarchy_grants" USING btree ("estate_id");--> statement-breakpoint
|
||||
CREATE INDEX "hierarchy_grants_platform_project_id_idx" ON "hierarchy_grants" USING btree ("platform_project_id");--> statement-breakpoint
|
||||
CREATE INDEX "hierarchy_grants_user_id_idx" ON "hierarchy_grants" USING btree ("user_id");--> statement-breakpoint
|
||||
CREATE INDEX "hierarchy_grants_team_id_idx" ON "hierarchy_grants" USING btree ("team_id");--> statement-breakpoint
|
||||
CREATE INDEX "hierarchy_grants_granted_by_idx" ON "hierarchy_grants" USING btree ("granted_by");
|
||||
@@ -1,40 +0,0 @@
|
||||
CREATE TYPE "public"."hierarchy_outbox_status" AS ENUM('pending', 'processing', 'delivered');--> statement-breakpoint
|
||||
CREATE TABLE "hierarchy_audit_events" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"seq" bigint GENERATED ALWAYS AS IDENTITY (sequence name "hierarchy_audit_events_seq_seq" INCREMENT BY 1 MINVALUE 1 MAXVALUE 9223372036854775807 START WITH 1 CACHE 1),
|
||||
"actor_id" text NOT NULL,
|
||||
"verb" text NOT NULL,
|
||||
"target_kind" text NOT NULL,
|
||||
"target_id" uuid NOT NULL,
|
||||
"target_snapshot" jsonb NOT NULL,
|
||||
"transfer_from" jsonb,
|
||||
"transfer_to" jsonb,
|
||||
"correlation_id" text NOT NULL,
|
||||
"causation_id" uuid,
|
||||
"idempotency_key" text NOT NULL,
|
||||
"occurred_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
CONSTRAINT "hierarchy_audit_events_verb_check" CHECK (verb IN ('create', 'rename', 'transfer', 'delete', 'grant_create', 'grant_change', 'grant_revoke')),
|
||||
CONSTRAINT "hierarchy_audit_events_target_kind_check" CHECK (target_kind IN ('company', 'estate', 'platform_project', 'grant')),
|
||||
CONSTRAINT "hierarchy_audit_events_transfer_check" CHECK ((verb = 'transfer') = (transfer_from IS NOT NULL AND transfer_to IS NOT NULL))
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "hierarchy_outbox" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"event_id" uuid NOT NULL,
|
||||
"idempotency_key" text NOT NULL,
|
||||
"correlation_id" text NOT NULL,
|
||||
"status" "hierarchy_outbox_status" DEFAULT 'pending' NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"delivered_at" timestamp with time zone
|
||||
);
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "hierarchy_audit_events" ADD CONSTRAINT "hierarchy_audit_events_causation_id_hierarchy_audit_events_id_fk" FOREIGN KEY ("causation_id") REFERENCES "public"."hierarchy_audit_events"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "hierarchy_outbox" ADD CONSTRAINT "hierarchy_outbox_event_id_hierarchy_audit_events_id_fk" FOREIGN KEY ("event_id") REFERENCES "public"."hierarchy_audit_events"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX "hierarchy_audit_events_idempotency_idx" ON "hierarchy_audit_events" USING btree ("idempotency_key");--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX "hierarchy_audit_events_seq_idx" ON "hierarchy_audit_events" USING btree ("seq");--> statement-breakpoint
|
||||
CREATE INDEX "hierarchy_audit_events_target_seq_idx" ON "hierarchy_audit_events" USING btree ("target_id","seq");--> statement-breakpoint
|
||||
CREATE INDEX "hierarchy_audit_events_correlation_idx" ON "hierarchy_audit_events" USING btree ("correlation_id");--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX "hierarchy_outbox_event_idx" ON "hierarchy_outbox" USING btree ("event_id");--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX "hierarchy_outbox_idempotency_idx" ON "hierarchy_outbox" USING btree ("idempotency_key");--> statement-breakpoint
|
||||
CREATE INDEX "hierarchy_outbox_status_created_idx" ON "hierarchy_outbox" USING btree ("status","created_at");
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -127,20 +127,6 @@
|
||||
"when": 1787609223282,
|
||||
"tag": "0017_accounts_issuer",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 18,
|
||||
"version": "7",
|
||||
"when": 1787862158838,
|
||||
"tag": "0018_clean_cobalt_man",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 19,
|
||||
"version": "7",
|
||||
"when": 1787880918208,
|
||||
"tag": "0019_volatile_killraven",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,363 +0,0 @@
|
||||
/**
|
||||
* Hierarchy audit event + outbox schema witnesses — contract 1 §5.2 and the
|
||||
* schema-level half of §6.4.
|
||||
*
|
||||
* Witnesses the guarantees the tables themselves carry: verb/target-kind/
|
||||
* transfer CHECK constraints, idempotency uniqueness (REQ-AUD-001 duplicate
|
||||
* suppression at the database level), monotonic append order (`seq`),
|
||||
* deletion-safe linkage (no foreign key from the events table into any class
|
||||
* table — events survive the deletion of their target), the causation
|
||||
* self-FK, and the outbox's FK/uniqueness/status shape. The repository-level
|
||||
* half of §6.4 (same-transaction atomicity, rollback, replay) is witnessed in
|
||||
* apps/gateway/src/hierarchy/hierarchy-audit.integration.test.ts.
|
||||
*
|
||||
* Two legs run the same witness body:
|
||||
* - PGlite (WASM Postgres): always runs.
|
||||
* - Real PostgreSQL (§6.8): runs when DATABASE_URL is set — the binding
|
||||
* witness; CI migrates ci-postgres before `pnpm test`.
|
||||
*/
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { mkdtempSync, rmSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { sql } from 'drizzle-orm';
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||
import { createDb } from './client.js';
|
||||
import { createPgliteDb } from './client-pglite.js';
|
||||
import { runPgliteMigrations } from './migrate.js';
|
||||
import { companies, hierarchyAuditEvents, hierarchyOutbox } from './schema.js';
|
||||
|
||||
type AnyDb = {
|
||||
db: {
|
||||
insert: (t: unknown) => { values: (v: unknown) => Promise<unknown> };
|
||||
execute: (q: unknown) => Promise<{ rows?: unknown[] } | unknown[]>;
|
||||
};
|
||||
close: () => Promise<void>;
|
||||
};
|
||||
|
||||
/** Match a constraint failure anywhere along drizzle's cause chain. */
|
||||
async function expectViolation(p: Promise<unknown>, re: RegExp, label = ''): Promise<void> {
|
||||
let err: unknown;
|
||||
try {
|
||||
await p;
|
||||
} catch (e) {
|
||||
err = e;
|
||||
}
|
||||
expect(err, label || 'expected the statement to be refused').toBeDefined();
|
||||
const messages: string[] = [];
|
||||
let cur: unknown = err;
|
||||
while (cur instanceof Error) {
|
||||
messages.push(cur.message);
|
||||
cur = (cur as { cause?: unknown }).cause;
|
||||
}
|
||||
expect(messages.join(' | '), label).toMatch(re);
|
||||
}
|
||||
|
||||
function rows(res: { rows?: unknown[] } | unknown[]): Record<string, unknown>[] {
|
||||
return (Array.isArray(res) ? res : (res.rows ?? [])) as Record<string, unknown>[];
|
||||
}
|
||||
|
||||
/** Unique per-run prefix so real-PG runs never collide and clean up safely. */
|
||||
const T = `hier-a-${randomUUID().slice(0, 8)}`;
|
||||
|
||||
/** Minimal valid event row; overrides compose the negative cases. */
|
||||
type EventInsert = typeof hierarchyAuditEvents.$inferInsert;
|
||||
|
||||
function eventRow(overrides: Partial<EventInsert> = {}): EventInsert {
|
||||
return {
|
||||
actorId: `${T}-actor`,
|
||||
verb: 'create',
|
||||
targetKind: 'company',
|
||||
targetId: randomUUID(),
|
||||
targetSnapshot: { id: 'x', slug: 'x', name: 'x', parentChain: [] },
|
||||
correlationId: `${T}-corr`,
|
||||
idempotencyKey: `${T}-${randomUUID()}`,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function witnessSuite(getHandle: () => AnyDb): void {
|
||||
const db = () => getHandle().db as unknown as ReturnType<typeof createDb>['db'];
|
||||
|
||||
afterAll(async () => {
|
||||
const d = db();
|
||||
await d.execute(sql`DELETE FROM hierarchy_outbox WHERE idempotency_key LIKE ${T + '%'}`);
|
||||
// Caused events first: the causation self-FK is RESTRICT.
|
||||
await d.execute(
|
||||
sql`DELETE FROM hierarchy_audit_events WHERE idempotency_key LIKE ${T + '%'} AND causation_id IS NOT NULL`,
|
||||
);
|
||||
await d.execute(sql`DELETE FROM hierarchy_audit_events WHERE idempotency_key LIKE ${T + '%'}`);
|
||||
await d.execute(sql`DELETE FROM companies WHERE slug LIKE ${T + '%'}`);
|
||||
});
|
||||
|
||||
// ── CHECK constraints ──────────────────────────────────────────────────────
|
||||
|
||||
it('accepts every declared verb and refuses an undeclared one', async () => {
|
||||
for (const verb of [
|
||||
'create',
|
||||
'rename',
|
||||
'delete',
|
||||
'grant_create',
|
||||
'grant_change',
|
||||
'grant_revoke',
|
||||
]) {
|
||||
await db().insert(hierarchyAuditEvents).values(eventRow({ verb }));
|
||||
}
|
||||
await expectViolation(
|
||||
db()
|
||||
.insert(hierarchyAuditEvents)
|
||||
.values(eventRow({ verb: 'update' })),
|
||||
/verb_check|violates check/i,
|
||||
'undeclared verb must be refused',
|
||||
);
|
||||
});
|
||||
|
||||
it('refuses an undeclared target kind', async () => {
|
||||
await expectViolation(
|
||||
db()
|
||||
.insert(hierarchyAuditEvents)
|
||||
.values(eventRow({ targetKind: 'workspace' })),
|
||||
/target_kind_check|violates check/i,
|
||||
'workspace is not an audited target kind (workspace mutation is SOT-side)',
|
||||
);
|
||||
});
|
||||
|
||||
it('requires transfer snapshots exactly on transfers', async () => {
|
||||
const parent = { kind: 'company', id: randomUUID(), slug: 'p' };
|
||||
await db()
|
||||
.insert(hierarchyAuditEvents)
|
||||
.values(
|
||||
eventRow({
|
||||
verb: 'transfer',
|
||||
targetKind: 'estate',
|
||||
transferFrom: parent,
|
||||
transferTo: { ...parent, id: randomUUID() },
|
||||
}),
|
||||
);
|
||||
await expectViolation(
|
||||
db()
|
||||
.insert(hierarchyAuditEvents)
|
||||
.values(eventRow({ verb: 'transfer' })),
|
||||
/transfer_check|violates check/i,
|
||||
'transfer without source/destination snapshots must be refused',
|
||||
);
|
||||
await expectViolation(
|
||||
db()
|
||||
.insert(hierarchyAuditEvents)
|
||||
.values(eventRow({ verb: 'transfer', transferFrom: parent })),
|
||||
/transfer_check|violates check/i,
|
||||
'transfer with only the source snapshot must be refused',
|
||||
);
|
||||
await expectViolation(
|
||||
db()
|
||||
.insert(hierarchyAuditEvents)
|
||||
.values(eventRow({ verb: 'create', transferFrom: parent, transferTo: parent })),
|
||||
/transfer_check|violates check/i,
|
||||
'non-transfer with transfer snapshots must be refused',
|
||||
);
|
||||
});
|
||||
|
||||
// ── Idempotency and ordering ───────────────────────────────────────────────
|
||||
|
||||
it('refuses a duplicate idempotency key', async () => {
|
||||
const key = `${T}-dup-${randomUUID()}`;
|
||||
await db()
|
||||
.insert(hierarchyAuditEvents)
|
||||
.values(eventRow({ idempotencyKey: key }));
|
||||
await expectViolation(
|
||||
db()
|
||||
.insert(hierarchyAuditEvents)
|
||||
.values(eventRow({ idempotencyKey: key })),
|
||||
/duplicate key|unique/i,
|
||||
);
|
||||
});
|
||||
|
||||
it('assigns strictly increasing seq in insert order for one target', async () => {
|
||||
const targetId = randomUUID();
|
||||
const k1 = `${T}-seq-1-${randomUUID()}`;
|
||||
const k2 = `${T}-seq-2-${randomUUID()}`;
|
||||
await db()
|
||||
.insert(hierarchyAuditEvents)
|
||||
.values(eventRow({ targetId, idempotencyKey: k1 }));
|
||||
await db()
|
||||
.insert(hierarchyAuditEvents)
|
||||
.values(eventRow({ targetId, verb: 'rename', idempotencyKey: k2 }));
|
||||
const res = rows(
|
||||
await db().execute(
|
||||
sql`SELECT idempotency_key, seq FROM hierarchy_audit_events WHERE target_id = ${targetId} ORDER BY seq ASC`,
|
||||
),
|
||||
);
|
||||
expect(res.map((r) => r['idempotency_key'])).toEqual([k1, k2]);
|
||||
expect(Number(res[1]!['seq'])).toBeGreaterThan(Number(res[0]!['seq']));
|
||||
});
|
||||
|
||||
// ── Deletion-safe linkage (§5.2) ───────────────────────────────────────────
|
||||
|
||||
it('has no foreign key into any class table, and events survive target deletion', async () => {
|
||||
const fks = rows(
|
||||
await db().execute(sql`
|
||||
SELECT ccu.table_name AS referenced_table
|
||||
FROM information_schema.table_constraints tc
|
||||
JOIN information_schema.constraint_column_usage ccu
|
||||
ON ccu.constraint_name = tc.constraint_name AND ccu.constraint_schema = tc.constraint_schema
|
||||
WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_name = 'hierarchy_audit_events'
|
||||
`),
|
||||
);
|
||||
// The causation self-FK is the ONLY foreign key on the events table.
|
||||
expect([...new Set(fks.map((r) => r['referenced_table']))]).toEqual(['hierarchy_audit_events']);
|
||||
|
||||
const companyId = randomUUID();
|
||||
await db()
|
||||
.insert(companies)
|
||||
.values({ id: companyId, name: 'Doomed', slug: `${T}-doomed` });
|
||||
const key = `${T}-survive-${randomUUID()}`;
|
||||
await db()
|
||||
.insert(hierarchyAuditEvents)
|
||||
.values(
|
||||
eventRow({
|
||||
verb: 'delete',
|
||||
targetId: companyId,
|
||||
targetSnapshot: { id: companyId, slug: `${T}-doomed`, name: 'Doomed', parentChain: [] },
|
||||
idempotencyKey: key,
|
||||
}),
|
||||
);
|
||||
await db().execute(sql`DELETE FROM companies WHERE id = ${companyId}`);
|
||||
const after = rows(
|
||||
await db().execute(
|
||||
sql`SELECT target_snapshot FROM hierarchy_audit_events WHERE idempotency_key = ${key}`,
|
||||
),
|
||||
);
|
||||
expect(after).toHaveLength(1);
|
||||
expect((after[0]!['target_snapshot'] as { id: string }).id).toBe(companyId);
|
||||
});
|
||||
|
||||
it('enforces the causation self-FK and RESTRICTs deleting a cause', async () => {
|
||||
await expectViolation(
|
||||
db()
|
||||
.insert(hierarchyAuditEvents)
|
||||
.values(eventRow({ causationId: randomUUID() })),
|
||||
/foreign key/i,
|
||||
'causation must reference an existing event',
|
||||
);
|
||||
const causeKey = `${T}-cause-${randomUUID()}`;
|
||||
await db()
|
||||
.insert(hierarchyAuditEvents)
|
||||
.values(eventRow({ verb: 'delete', idempotencyKey: causeKey }));
|
||||
const cause = rows(
|
||||
await db().execute(
|
||||
sql`SELECT id FROM hierarchy_audit_events WHERE idempotency_key = ${causeKey}`,
|
||||
),
|
||||
)[0]!;
|
||||
await db()
|
||||
.insert(hierarchyAuditEvents)
|
||||
.values(
|
||||
eventRow({ verb: 'grant_revoke', targetKind: 'grant', causationId: cause['id'] as string }),
|
||||
);
|
||||
await expectViolation(
|
||||
db().execute(sql`DELETE FROM hierarchy_audit_events WHERE id = ${cause['id'] as string}`),
|
||||
/foreign key/i,
|
||||
'a cause with dependent events must not be deletable',
|
||||
);
|
||||
});
|
||||
|
||||
// ── Outbox shape ───────────────────────────────────────────────────────────
|
||||
|
||||
it('outbox rows require an existing event, one outbox row per event, unique idempotency', async () => {
|
||||
await expectViolation(
|
||||
db()
|
||||
.insert(hierarchyOutbox)
|
||||
.values({
|
||||
eventId: randomUUID(),
|
||||
idempotencyKey: `${T}-ob-${randomUUID()}`,
|
||||
correlationId: `${T}-corr`,
|
||||
}),
|
||||
/foreign key/i,
|
||||
'outbox must reference an existing event',
|
||||
);
|
||||
const key = `${T}-ob-${randomUUID()}`;
|
||||
await db()
|
||||
.insert(hierarchyAuditEvents)
|
||||
.values(eventRow({ idempotencyKey: key }));
|
||||
const event = rows(
|
||||
await db().execute(sql`SELECT id FROM hierarchy_audit_events WHERE idempotency_key = ${key}`),
|
||||
)[0]!;
|
||||
const eventId = event['id'] as string;
|
||||
await db()
|
||||
.insert(hierarchyOutbox)
|
||||
.values({ eventId, idempotencyKey: key, correlationId: `${T}-corr` });
|
||||
await expectViolation(
|
||||
db()
|
||||
.insert(hierarchyOutbox)
|
||||
.values({ eventId, idempotencyKey: `${T}-ob2-${randomUUID()}`, correlationId: `${T}-c` }),
|
||||
/duplicate key|unique/i,
|
||||
'one outbox record per event',
|
||||
);
|
||||
await expectViolation(
|
||||
db().execute(
|
||||
sql`INSERT INTO hierarchy_outbox (event_id, idempotency_key, correlation_id, status)
|
||||
VALUES (${eventId}, ${`${T}-ob3-${randomUUID()}`}, 'c', 'failed')`,
|
||||
),
|
||||
/invalid input value for enum|22P02/i,
|
||||
'status outside pending/processing/delivered must be refused',
|
||||
);
|
||||
});
|
||||
|
||||
it('outbox FK RESTRICTs event deletion while the outbox row exists', async () => {
|
||||
const key = `${T}-obr-${randomUUID()}`;
|
||||
await db()
|
||||
.insert(hierarchyAuditEvents)
|
||||
.values(eventRow({ idempotencyKey: key }));
|
||||
const event = rows(
|
||||
await db().execute(sql`SELECT id FROM hierarchy_audit_events WHERE idempotency_key = ${key}`),
|
||||
)[0]!;
|
||||
await db()
|
||||
.insert(hierarchyOutbox)
|
||||
.values({
|
||||
eventId: event['id'] as string,
|
||||
idempotencyKey: key,
|
||||
correlationId: `${T}-corr`,
|
||||
});
|
||||
await expectViolation(
|
||||
db().execute(sql`DELETE FROM hierarchy_audit_events WHERE id = ${event['id'] as string}`),
|
||||
/foreign key/i,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
// ── Leg 1: PGlite (always runs — local witness signal) ───────────────────────
|
||||
|
||||
describe('hierarchy audit witnesses — PGlite', () => {
|
||||
let dir: string;
|
||||
let handle: ReturnType<typeof createPgliteDb>;
|
||||
|
||||
beforeAll(async () => {
|
||||
dir = mkdtempSync(join(tmpdir(), 'hier-audit-witness-'));
|
||||
handle = createPgliteDb(dir);
|
||||
await runPgliteMigrations(handle);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await handle.close();
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
witnessSuite(() => handle as unknown as AnyDb);
|
||||
});
|
||||
|
||||
// ── Leg 2: real PostgreSQL (§6.8 — binding witness, ci-postgres in CI) ───────
|
||||
|
||||
const hasPostgres = Boolean(process.env['DATABASE_URL']);
|
||||
|
||||
describe.skipIf(!hasPostgres)('hierarchy audit witnesses — real PostgreSQL', () => {
|
||||
let handle: ReturnType<typeof createDb>;
|
||||
|
||||
beforeAll(() => {
|
||||
handle = createDb(process.env['DATABASE_URL']!);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await handle.close();
|
||||
});
|
||||
|
||||
witnessSuite(() => handle as unknown as AnyDb);
|
||||
});
|
||||
@@ -1,501 +0,0 @@
|
||||
/**
|
||||
* Hierarchy schema witnesses — contract 1 (docs/requirements/hierarchy-schema.md) §6.
|
||||
*
|
||||
* Witnesses §6.1 (chain construction, slug scoping, grant CHECKs, grant
|
||||
* uniqueness, NOT NULLs), §6.2 (column allowlist), the database-level parts of
|
||||
* §6.6 (RESTRICT/cascade deletion behavior), and §6.7's catalog half (no
|
||||
* foreign keys from outside the class into class tables).
|
||||
*
|
||||
* Two legs run the same witness body:
|
||||
* - PGlite (WASM Postgres): always runs, so the witnesses execute locally
|
||||
* with no database configured.
|
||||
* - Real PostgreSQL (§6.8): runs when DATABASE_URL is set — in CI that is
|
||||
* the ci-postgres service, migrated by the pipeline before `pnpm test`.
|
||||
* This leg is the contract's binding witness; the PGlite leg is the local
|
||||
* development signal.
|
||||
*/
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { mkdtempSync, rmSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { sql } from 'drizzle-orm';
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||
import { createDb } from './client.js';
|
||||
import { createPgliteDb } from './client-pglite.js';
|
||||
import { runPgliteMigrations } from './migrate.js';
|
||||
import {
|
||||
companies,
|
||||
estates,
|
||||
hierarchyGrants,
|
||||
platformProjects,
|
||||
workspaces,
|
||||
teams,
|
||||
users,
|
||||
} from './schema.js';
|
||||
|
||||
type AnyDb = {
|
||||
db: {
|
||||
insert: (t: unknown) => { values: (v: unknown) => Promise<unknown> };
|
||||
delete: (t: unknown) => { where?: unknown } & PromiseLike<unknown>;
|
||||
execute: (q: unknown) => Promise<{ rows?: unknown[] } | unknown[]>;
|
||||
};
|
||||
close: () => Promise<void>;
|
||||
};
|
||||
|
||||
/** Column allowlist — the exact declared sets of §2/§3. Nothing else. */
|
||||
const COLUMN_ALLOWLIST: Record<string, string[]> = {
|
||||
companies: ['id', 'name', 'slug', 'created_at', 'updated_at'],
|
||||
estates: ['id', 'name', 'slug', 'company_id'],
|
||||
platform_projects: ['id', 'name', 'slug', 'estate_id'],
|
||||
workspaces: ['id', 'name', 'slug', 'platform_project_id'],
|
||||
hierarchy_grants: [
|
||||
'id',
|
||||
'user_id',
|
||||
'team_id',
|
||||
'company_id',
|
||||
'estate_id',
|
||||
'platform_project_id',
|
||||
'role',
|
||||
'granted_by',
|
||||
'created_at',
|
||||
],
|
||||
};
|
||||
|
||||
const NODE_TABLES = ['companies', 'estates', 'platform_projects', 'workspaces'];
|
||||
const CLASS_TABLES = [...NODE_TABLES, 'hierarchy_grants'];
|
||||
|
||||
/**
|
||||
* Drizzle wraps constraint failures ("Failed query: ...") with the driver
|
||||
* error attached as `cause`. Match the pattern anywhere along the cause chain.
|
||||
*/
|
||||
async function expectViolation(p: Promise<unknown>, re: RegExp, label = ''): Promise<void> {
|
||||
let err: unknown;
|
||||
try {
|
||||
await p;
|
||||
} catch (e) {
|
||||
err = e;
|
||||
}
|
||||
expect(err, label || 'expected the statement to be refused').toBeDefined();
|
||||
const messages: string[] = [];
|
||||
let cur: unknown = err;
|
||||
while (cur instanceof Error) {
|
||||
messages.push(cur.message);
|
||||
cur = (cur as { cause?: unknown }).cause;
|
||||
}
|
||||
expect(messages.join(' | '), label).toMatch(re);
|
||||
}
|
||||
|
||||
function rows(res: { rows?: unknown[] } | unknown[]): Record<string, unknown>[] {
|
||||
return (Array.isArray(res) ? res : (res.rows ?? [])) as Record<string, unknown>[];
|
||||
}
|
||||
|
||||
/** Unique per-run prefix so real-PG runs never collide and clean up safely. */
|
||||
const T = `hier-w-${randomUUID().slice(0, 8)}`;
|
||||
|
||||
function witnessSuite(getHandle: () => AnyDb): void {
|
||||
const db = () => getHandle().db as unknown as ReturnType<typeof createDb>['db'];
|
||||
|
||||
const userA = `${T}-user-a`;
|
||||
const userB = `${T}-user-b`;
|
||||
let teamId: string;
|
||||
let companyId: string;
|
||||
let company2Id: string;
|
||||
let estateId: string;
|
||||
let estate2Id: string;
|
||||
let ppId: string;
|
||||
let workspaceId: string;
|
||||
|
||||
beforeAll(async () => {
|
||||
await db()
|
||||
.insert(users)
|
||||
.values([
|
||||
{ id: userA, name: 'Witness A', email: `${userA}@example.com` },
|
||||
{ id: userB, name: 'Witness B', email: `${userB}@example.com` },
|
||||
]);
|
||||
teamId = randomUUID();
|
||||
await db()
|
||||
.insert(teams)
|
||||
.values({
|
||||
id: teamId,
|
||||
name: `${T}-team`,
|
||||
slug: `${T}-team`,
|
||||
ownerId: userA,
|
||||
managerId: userA,
|
||||
});
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
// Bottom-up, fail-closed order; grants cascade with their targets.
|
||||
const d = db();
|
||||
await d.execute(sql`DELETE FROM hierarchy_grants WHERE granted_by LIKE ${T + '%'}`);
|
||||
await d.execute(sql`DELETE FROM workspaces WHERE slug LIKE ${T + '%'}`);
|
||||
await d.execute(sql`DELETE FROM platform_projects WHERE slug LIKE ${T + '%'}`);
|
||||
await d.execute(sql`DELETE FROM estates WHERE slug LIKE ${T + '%'}`);
|
||||
await d.execute(sql`DELETE FROM companies WHERE slug LIKE ${T + '%'}`);
|
||||
await d.execute(sql`DELETE FROM teams WHERE slug LIKE ${T + '%'}`);
|
||||
await d.execute(sql`DELETE FROM users WHERE id LIKE ${T + '%'}`);
|
||||
});
|
||||
|
||||
// ── §6.1 chain construction ────────────────────────────────────────────────
|
||||
|
||||
it('accepts a full valid chain: company → estate → platform-project → workspace', async () => {
|
||||
companyId = randomUUID();
|
||||
estateId = randomUUID();
|
||||
ppId = randomUUID();
|
||||
workspaceId = randomUUID();
|
||||
await db()
|
||||
.insert(companies)
|
||||
.values({ id: companyId, name: 'Acme', slug: `${T}-acme` });
|
||||
await db()
|
||||
.insert(estates)
|
||||
.values({ id: estateId, name: 'Estate 1', slug: `${T}-e1`, companyId });
|
||||
await db()
|
||||
.insert(platformProjects)
|
||||
.values({ id: ppId, name: 'PP 1', slug: `${T}-pp1`, estateId });
|
||||
await db()
|
||||
.insert(workspaces)
|
||||
.values({ id: workspaceId, name: 'WS 1', slug: `${T}-ws1`, platformProjectId: ppId });
|
||||
});
|
||||
|
||||
it('accepts two siblings under one parent (the §2.5 control)', async () => {
|
||||
estate2Id = randomUUID();
|
||||
await db()
|
||||
.insert(estates)
|
||||
.values({ id: estate2Id, name: 'Estate 2', slug: `${T}-e2`, companyId });
|
||||
});
|
||||
|
||||
it('refuses inserts with a null parent FK', async () => {
|
||||
await expectViolation(
|
||||
db().execute(
|
||||
sql`INSERT INTO estates (id, name, slug, company_id) VALUES (${randomUUID()}, 'x', ${T + '-null-e'}, NULL)`,
|
||||
),
|
||||
/null value|not-null/i,
|
||||
);
|
||||
await expectViolation(
|
||||
db().execute(
|
||||
sql`INSERT INTO platform_projects (id, name, slug, estate_id) VALUES (${randomUUID()}, 'x', ${T + '-null-p'}, NULL)`,
|
||||
),
|
||||
/null value|not-null/i,
|
||||
);
|
||||
await expectViolation(
|
||||
db().execute(
|
||||
sql`INSERT INTO workspaces (id, name, slug, platform_project_id) VALUES (${randomUUID()}, 'x', ${T + '-null-w'}, NULL)`,
|
||||
),
|
||||
/null value|not-null/i,
|
||||
);
|
||||
});
|
||||
|
||||
it('refuses inserts with a dangling parent FK', async () => {
|
||||
await expectViolation(
|
||||
db()
|
||||
.insert(estates)
|
||||
.values({ id: randomUUID(), name: 'x', slug: `${T}-dangle`, companyId: randomUUID() }),
|
||||
/foreign key/i,
|
||||
);
|
||||
});
|
||||
|
||||
it('catalog: each child table has exactly one parent-FK column and no parentage edge table exists', async () => {
|
||||
const res = rows(
|
||||
await db().execute(sql`
|
||||
SELECT tc.table_name, kcu.column_name, ccu.table_name AS ref_table
|
||||
FROM information_schema.table_constraints tc
|
||||
JOIN information_schema.key_column_usage kcu
|
||||
ON tc.constraint_name = kcu.constraint_name AND tc.table_schema = kcu.table_schema
|
||||
JOIN information_schema.constraint_column_usage ccu
|
||||
ON tc.constraint_name = ccu.constraint_name AND tc.table_schema = ccu.table_schema
|
||||
WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_schema = 'public'
|
||||
`),
|
||||
);
|
||||
const nodeSet = new Set(NODE_TABLES);
|
||||
// Exactly one parent FK per child node table.
|
||||
for (const [child, parent] of [
|
||||
['estates', 'companies'],
|
||||
['platform_projects', 'estates'],
|
||||
['workspaces', 'platform_projects'],
|
||||
] as const) {
|
||||
const parentFks = res.filter(
|
||||
(r) => r['table_name'] === child && nodeSet.has(String(r['ref_table'])),
|
||||
);
|
||||
expect(parentFks.map((r) => `${r['column_name']}->${r['ref_table']}`)).toEqual([
|
||||
`${{ estates: 'company_id', platform_projects: 'estate_id', workspaces: 'platform_project_id' }[child]}->${parent}`,
|
||||
]);
|
||||
}
|
||||
// No table outside the class references a node table (also §6.7's catalog
|
||||
// half for companies/estates/platform_projects/workspaces), and the only
|
||||
// multi-FK referencer is hierarchy_grants (grant attachment, not
|
||||
// parentage).
|
||||
const referencers = new Map<string, number>();
|
||||
for (const r of res) {
|
||||
if (nodeSet.has(String(r['ref_table']))) {
|
||||
const t = String(r['table_name']);
|
||||
referencers.set(t, (referencers.get(t) ?? 0) + 1);
|
||||
}
|
||||
}
|
||||
for (const [table, count] of referencers) {
|
||||
expect(CLASS_TABLES, `unexpected referencer of a node table: ${table}`).toContain(table);
|
||||
if (count > 1) expect(table).toBe('hierarchy_grants');
|
||||
}
|
||||
// No FK anywhere references hierarchy_grants.
|
||||
expect(res.filter((r) => r['ref_table'] === 'hierarchy_grants')).toEqual([]);
|
||||
});
|
||||
|
||||
// ── §6.1 slug scoping ──────────────────────────────────────────────────────
|
||||
|
||||
it('refuses a duplicate slug under the same parent, accepts it under another parent', async () => {
|
||||
company2Id = randomUUID();
|
||||
await db()
|
||||
.insert(companies)
|
||||
.values({ id: company2Id, name: 'Beta', slug: `${T}-beta` });
|
||||
await expectViolation(
|
||||
db()
|
||||
.insert(estates)
|
||||
.values({ id: randomUUID(), name: 'dup', slug: `${T}-e1`, companyId }),
|
||||
/duplicate key|unique/i,
|
||||
);
|
||||
// Same slug, different company — accepted.
|
||||
await db()
|
||||
.insert(estates)
|
||||
.values({ id: randomUUID(), name: 'ok', slug: `${T}-e1`, companyId: company2Id });
|
||||
// companies.slug is unique per deployment.
|
||||
await expectViolation(
|
||||
db()
|
||||
.insert(companies)
|
||||
.values({ id: randomUUID(), name: 'dup', slug: `${T}-acme` }),
|
||||
/duplicate key|unique/i,
|
||||
);
|
||||
});
|
||||
|
||||
it('scopes platform_projects and workspaces slugs per parent (refuse same-parent duplicate, accept cross-parent)', async () => {
|
||||
// Dedicated parent estate so this test leaves estate2 a leaf (the §3.4
|
||||
// cascade witness depends on that).
|
||||
const estate3Id = randomUUID();
|
||||
await db()
|
||||
.insert(estates)
|
||||
.values({ id: estate3Id, name: 'Estate 3', slug: `${T}-e3`, companyId });
|
||||
// platform_projects: (estate_id, slug) unique.
|
||||
await expectViolation(
|
||||
db()
|
||||
.insert(platformProjects)
|
||||
.values({ id: randomUUID(), name: 'dup', slug: `${T}-pp1`, estateId }),
|
||||
/duplicate key|unique/i,
|
||||
);
|
||||
const pp2Id = randomUUID();
|
||||
await db()
|
||||
.insert(platformProjects)
|
||||
.values({ id: pp2Id, name: 'ok', slug: `${T}-pp1`, estateId: estate3Id });
|
||||
// workspaces: (platform_project_id, slug) unique.
|
||||
await expectViolation(
|
||||
db()
|
||||
.insert(workspaces)
|
||||
.values({ id: randomUUID(), name: 'dup', slug: `${T}-ws1`, platformProjectId: ppId }),
|
||||
/duplicate key|unique/i,
|
||||
);
|
||||
await db()
|
||||
.insert(workspaces)
|
||||
.values({ id: randomUUID(), name: 'ok', slug: `${T}-ws1`, platformProjectId: pp2Id });
|
||||
});
|
||||
|
||||
// ── §6.2 column allowlist ──────────────────────────────────────────────────
|
||||
|
||||
it('column allowlist: each class table has exactly its declared columns (no payload, no owner_id)', async () => {
|
||||
for (const [table, allow] of Object.entries(COLUMN_ALLOWLIST)) {
|
||||
const res = rows(
|
||||
await db().execute(
|
||||
sql`SELECT column_name FROM information_schema.columns WHERE table_schema = 'public' AND table_name = ${table}`,
|
||||
),
|
||||
);
|
||||
const actual = res.map((r) => String(r['column_name'])).sort();
|
||||
expect(actual, `column set of ${table}`).toEqual([...allow].sort());
|
||||
}
|
||||
});
|
||||
|
||||
// ── §6.1 grant CHECKs ──────────────────────────────────────────────────────
|
||||
|
||||
it('accepts one valid grant per subject×target form', async () => {
|
||||
// All six forms; also the base rows for the §6.1 uniqueness witness below.
|
||||
const forms = [
|
||||
{ userId: userA, companyId },
|
||||
{ userId: userA, estateId },
|
||||
{ userId: userA, platformProjectId: ppId },
|
||||
{ teamId, companyId },
|
||||
{ teamId, estateId },
|
||||
{ teamId, platformProjectId: ppId },
|
||||
];
|
||||
for (const form of forms) {
|
||||
await db()
|
||||
.insert(hierarchyGrants)
|
||||
.values({ ...form, role: 'owner', grantedBy: userA });
|
||||
}
|
||||
});
|
||||
|
||||
it('refuses a grant with zero or two subjects (exactly-one-of CHECK)', async () => {
|
||||
await expectViolation(
|
||||
db().insert(hierarchyGrants).values({ companyId, role: 'viewer', grantedBy: userA }),
|
||||
/check constraint/i,
|
||||
);
|
||||
await expectViolation(
|
||||
db()
|
||||
.insert(hierarchyGrants)
|
||||
.values({ userId: userA, teamId, companyId, role: 'viewer', grantedBy: userA }),
|
||||
/check constraint/i,
|
||||
);
|
||||
});
|
||||
|
||||
it('refuses a grant with zero or two targets (exactly-one-of CHECK)', async () => {
|
||||
await expectViolation(
|
||||
db().insert(hierarchyGrants).values({ userId: userA, role: 'viewer', grantedBy: userA }),
|
||||
/check constraint/i,
|
||||
);
|
||||
await expectViolation(
|
||||
db()
|
||||
.insert(hierarchyGrants)
|
||||
.values({ userId: userA, companyId, estateId, role: 'viewer', grantedBy: userA }),
|
||||
/check constraint/i,
|
||||
);
|
||||
});
|
||||
|
||||
// ── §6.1 grant uniqueness (NULLS NOT DISTINCT) ─────────────────────────────
|
||||
|
||||
it('refuses a duplicate (subject, target, role) for each of the six forms', async () => {
|
||||
const forms = [
|
||||
{ userId: userA, companyId },
|
||||
{ userId: userA, estateId },
|
||||
{ userId: userA, platformProjectId: ppId },
|
||||
{ teamId, companyId },
|
||||
{ teamId, estateId },
|
||||
{ teamId, platformProjectId: ppId },
|
||||
];
|
||||
for (const form of forms) {
|
||||
await expectViolation(
|
||||
db()
|
||||
.insert(hierarchyGrants)
|
||||
.values({ ...form, role: 'owner', grantedBy: userB }),
|
||||
/duplicate key|unique/i,
|
||||
`duplicate form ${JSON.stringify(form)} must be refused`,
|
||||
);
|
||||
}
|
||||
// Control: same subject and target with a different role is a new grant.
|
||||
await db()
|
||||
.insert(hierarchyGrants)
|
||||
.values({ userId: userA, companyId, role: `${T}-other-role`, grantedBy: userA });
|
||||
});
|
||||
|
||||
// ── §6.1 NOT NULLs ─────────────────────────────────────────────────────────
|
||||
|
||||
it('refuses null role, granted_by, and null name/slug columns', async () => {
|
||||
await expectViolation(
|
||||
db().execute(
|
||||
sql`INSERT INTO hierarchy_grants (user_id, company_id, role, granted_by) VALUES (${userA}, ${companyId}, NULL, ${userA})`,
|
||||
),
|
||||
/null value|not-null/i,
|
||||
);
|
||||
await expectViolation(
|
||||
db().execute(
|
||||
sql`INSERT INTO hierarchy_grants (user_id, company_id, role, granted_by) VALUES (${userA}, ${companyId}, 'x', NULL)`,
|
||||
),
|
||||
/null value|not-null/i,
|
||||
);
|
||||
await expectViolation(
|
||||
db().execute(sql`INSERT INTO companies (name, slug) VALUES (NULL, ${T + '-nn'})`),
|
||||
/null value|not-null/i,
|
||||
);
|
||||
await expectViolation(
|
||||
db().execute(sql`INSERT INTO companies (name, slug) VALUES ('x', NULL)`),
|
||||
/null value|not-null/i,
|
||||
);
|
||||
await expectViolation(
|
||||
db().execute(
|
||||
sql`INSERT INTO estates (name, slug, company_id) VALUES ('x', NULL, ${companyId})`,
|
||||
),
|
||||
/null value|not-null/i,
|
||||
);
|
||||
});
|
||||
|
||||
// ── §6.6 deletion (database-level witnesses) ───────────────────────────────
|
||||
|
||||
it('refuses deleting a node with children (fail-closed bottom-up)', async () => {
|
||||
await expectViolation(
|
||||
db().execute(sql`DELETE FROM companies WHERE id = ${companyId}`),
|
||||
/foreign key/i,
|
||||
);
|
||||
await expectViolation(
|
||||
db().execute(sql`DELETE FROM estates WHERE id = ${estateId}`),
|
||||
/foreign key/i,
|
||||
);
|
||||
await expectViolation(
|
||||
db().execute(sql`DELETE FROM platform_projects WHERE id = ${ppId}`),
|
||||
/foreign key/i,
|
||||
);
|
||||
});
|
||||
|
||||
it('cascades a deleted leaf node’s grants and nothing else', async () => {
|
||||
// estate2 is a leaf (no platform-projects). Attach one grant to it.
|
||||
await db()
|
||||
.insert(hierarchyGrants)
|
||||
.values({ userId: userB, estateId: estate2Id, role: 'viewer', grantedBy: userA });
|
||||
const grantCount = async () =>
|
||||
Number(
|
||||
rows(
|
||||
await db().execute(
|
||||
sql`SELECT count(*)::int AS n FROM hierarchy_grants WHERE granted_by LIKE ${T + '%'}`,
|
||||
),
|
||||
)[0]!['n'],
|
||||
);
|
||||
const before = await grantCount();
|
||||
await db().execute(sql`DELETE FROM estates WHERE id = ${estate2Id}`);
|
||||
// Exactly the one grant on the deleted estate is gone.
|
||||
expect(await grantCount()).toBe(before - 1);
|
||||
});
|
||||
|
||||
it('refuses deleting a user or team that is a grant subject or granted_by referent (RESTRICT)', async () => {
|
||||
await expectViolation(db().execute(sql`DELETE FROM users WHERE id = ${userA}`), /foreign key/i);
|
||||
// userB is only a subject (its estate2 grant cascaded away above, but it
|
||||
// still holds no grants — re-create one to witness subject RESTRICT).
|
||||
await db()
|
||||
.insert(hierarchyGrants)
|
||||
.values({ userId: userB, companyId: company2Id, role: 'viewer', grantedBy: userA });
|
||||
await expectViolation(db().execute(sql`DELETE FROM users WHERE id = ${userB}`), /foreign key/i);
|
||||
await expectViolation(
|
||||
db().execute(sql`DELETE FROM teams WHERE id = ${teamId}`),
|
||||
/foreign key/i,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
// ── Leg 1: PGlite (always runs — local witness signal) ───────────────────────
|
||||
|
||||
describe('hierarchy schema witnesses — PGlite', () => {
|
||||
let dir: string;
|
||||
let handle: ReturnType<typeof createPgliteDb>;
|
||||
|
||||
beforeAll(async () => {
|
||||
dir = mkdtempSync(join(tmpdir(), 'hier-witness-'));
|
||||
handle = createPgliteDb(dir);
|
||||
await runPgliteMigrations(handle);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await handle.close();
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
witnessSuite(() => handle as unknown as AnyDb);
|
||||
});
|
||||
|
||||
// ── Leg 2: real PostgreSQL (§6.8 — binding witness, ci-postgres in CI) ───────
|
||||
|
||||
const hasPostgres = Boolean(process.env['DATABASE_URL']);
|
||||
|
||||
describe.skipIf(!hasPostgres)('hierarchy schema witnesses — real PostgreSQL', () => {
|
||||
let handle: ReturnType<typeof createDb>;
|
||||
|
||||
beforeAll(() => {
|
||||
handle = createDb(process.env['DATABASE_URL']!);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await handle.close();
|
||||
});
|
||||
|
||||
witnessSuite(() => handle as unknown as AnyDb);
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
@@ -3,8 +3,6 @@
|
||||
* drizzle-kit reads this file directly (avoids CJS/ESM extension issues).
|
||||
*/
|
||||
|
||||
import { sql } from 'drizzle-orm';
|
||||
import type { AnyPgColumn } from 'drizzle-orm/pg-core';
|
||||
import {
|
||||
pgTable,
|
||||
pgEnum,
|
||||
@@ -15,8 +13,6 @@ import {
|
||||
jsonb,
|
||||
index,
|
||||
uniqueIndex,
|
||||
unique,
|
||||
check,
|
||||
real,
|
||||
integer,
|
||||
bigint,
|
||||
@@ -1052,212 +1048,3 @@ export const federationEnrollmentTokens = pgTable('federation_enrollment_tokens'
|
||||
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
|
||||
});
|
||||
|
||||
// ─── Hierarchy (tenancy/authorization structure record class) ────────────────
|
||||
// Contract: docs/requirements/hierarchy-schema.md (D2, ratified 2026-08-27).
|
||||
// Five tables: companies → estates → platform_projects → workspaces, plus
|
||||
// hierarchy_grants. Class rows carry parentage, naming, grant, and
|
||||
// audit-linkage data only — the column sets below are exhaustive (§2.7) and
|
||||
// witnessed against information_schema (§6.2). No owner_id: ownership is the
|
||||
// grant structure (§4.4). All writes flow through the Gateway hierarchy
|
||||
// command family only (§5.1), enforced by the writer-coverage assertion
|
||||
// (§6.3b) — do not add writers outside that allowlist.
|
||||
|
||||
export const companies = pgTable('companies', {
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
name: text('name').notNull(),
|
||||
slug: text('slug').notNull().unique(),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
|
||||
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
|
||||
});
|
||||
|
||||
export const estates = pgTable(
|
||||
'estates',
|
||||
{
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
name: text('name').notNull(),
|
||||
slug: text('slug').notNull(),
|
||||
companyId: uuid('company_id')
|
||||
.notNull()
|
||||
.references(() => companies.id, { onDelete: 'restrict' }),
|
||||
},
|
||||
(t) => [unique('estates_company_slug_uniq').on(t.companyId, t.slug)],
|
||||
);
|
||||
|
||||
export const platformProjects = pgTable(
|
||||
'platform_projects',
|
||||
{
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
name: text('name').notNull(),
|
||||
slug: text('slug').notNull(),
|
||||
estateId: uuid('estate_id')
|
||||
.notNull()
|
||||
.references(() => estates.id, { onDelete: 'restrict' }),
|
||||
},
|
||||
(t) => [unique('platform_projects_estate_slug_uniq').on(t.estateId, t.slug)],
|
||||
);
|
||||
|
||||
export const workspaces = pgTable(
|
||||
'workspaces',
|
||||
{
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
name: text('name').notNull(),
|
||||
slug: text('slug').notNull(),
|
||||
platformProjectId: uuid('platform_project_id')
|
||||
.notNull()
|
||||
.references(() => platformProjects.id, { onDelete: 'restrict' }),
|
||||
},
|
||||
(t) => [unique('workspaces_platform_project_slug_uniq').on(t.platformProjectId, t.slug)],
|
||||
);
|
||||
|
||||
export const hierarchyGrants = pgTable(
|
||||
'hierarchy_grants',
|
||||
{
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
// Subject: exactly one of user/team (CHECK below). Principal FKs are
|
||||
// RESTRICT until a deletion-and-retention contract rules otherwise (§3.3).
|
||||
userId: text('user_id').references(() => users.id, { onDelete: 'restrict' }),
|
||||
teamId: uuid('team_id').references(() => teams.id, { onDelete: 'restrict' }),
|
||||
// Target: exactly one of the three grantable levels (CHECK below).
|
||||
// Target FKs CASCADE — the one permitted cascade in the class (§3.3);
|
||||
// cascaded grant deletions are audited by the command family (§5.2).
|
||||
companyId: uuid('company_id').references(() => companies.id, { onDelete: 'cascade' }),
|
||||
estateId: uuid('estate_id').references(() => estates.id, { onDelete: 'cascade' }),
|
||||
platformProjectId: uuid('platform_project_id').references(() => platformProjects.id, {
|
||||
onDelete: 'cascade',
|
||||
}),
|
||||
// Role vocabulary and its CHECK constraint are contract 2 §2 (M4-2).
|
||||
role: text('role').notNull(),
|
||||
grantedBy: text('granted_by')
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: 'restrict' }),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
|
||||
},
|
||||
(t) => [
|
||||
check('hierarchy_grants_subject_check', sql`num_nonnulls(user_id, team_id) = 1`),
|
||||
check(
|
||||
'hierarchy_grants_target_check',
|
||||
sql`num_nonnulls(company_id, estate_id, platform_project_id) = 1`,
|
||||
),
|
||||
// At most one grant per (subject, target, role) across all six
|
||||
// subject×target forms — NULLS NOT DISTINCT so nullable columns
|
||||
// participate (§3.2).
|
||||
unique('hierarchy_grants_subject_target_role_uniq')
|
||||
.on(t.userId, t.teamId, t.companyId, t.estateId, t.platformProjectId, t.role)
|
||||
.nullsNotDistinct(),
|
||||
index('hierarchy_grants_company_id_idx').on(t.companyId),
|
||||
index('hierarchy_grants_estate_id_idx').on(t.estateId),
|
||||
index('hierarchy_grants_platform_project_id_idx').on(t.platformProjectId),
|
||||
index('hierarchy_grants_user_id_idx').on(t.userId),
|
||||
index('hierarchy_grants_team_id_idx').on(t.teamId),
|
||||
index('hierarchy_grants_granted_by_idx').on(t.grantedBy),
|
||||
],
|
||||
);
|
||||
|
||||
// ─── Hierarchy audit events + outbox (contract 1 §5.2) ──────────────────────
|
||||
// NOT part of the record class (the class is exactly the five tables above).
|
||||
// Append-only semantic audit log for hierarchy mutations, with a dedicated
|
||||
// transactional outbox — hierarchy events are not workspace-scoped rows and
|
||||
// do not ride the workspace outbox. Deletion-safe linkage: events reference
|
||||
// their target by an immutable snapshot (id, slug, parent chain at event
|
||||
// time), never by a foreign key into the class tables, so append-only events
|
||||
// survive the deletion of their target. Append-only is enforced at the
|
||||
// application layer (the hierarchy audit repository exposes no update/delete
|
||||
// path for events); REQ-AUD-001's INSERT/SELECT-only database role is a
|
||||
// deployment concern outside this schema.
|
||||
|
||||
export const HIERARCHY_AUDIT_VERBS = [
|
||||
'create',
|
||||
'rename',
|
||||
'transfer',
|
||||
'delete',
|
||||
'grant_create',
|
||||
'grant_change',
|
||||
'grant_revoke',
|
||||
] as const;
|
||||
|
||||
export const HIERARCHY_AUDIT_TARGET_KINDS = [
|
||||
'company',
|
||||
'estate',
|
||||
'platform_project',
|
||||
'grant',
|
||||
] as const;
|
||||
|
||||
export const hierarchyAuditEvents = pgTable(
|
||||
'hierarchy_audit_events',
|
||||
{
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
// Global append order; per-target ordering (REQ-AUD-001) is a filter on
|
||||
// target_id ordered by seq.
|
||||
seq: bigint('seq', { mode: 'number' }).notNull().generatedAlwaysAsIdentity(),
|
||||
// No FK: audit events outlive every principal and every target (§5.2).
|
||||
actorId: text('actor_id').notNull(),
|
||||
verb: text('verb').notNull(),
|
||||
targetKind: text('target_kind').notNull(),
|
||||
targetId: uuid('target_id').notNull(),
|
||||
// Immutable snapshot at event time. Node events: { id, slug, name,
|
||||
// parentChain: [{ kind, id, slug }, …] root-first }. Grant events:
|
||||
// { id, subject: { userId | teamId }, target: { kind, id }, role }
|
||||
// (subject and role per contract 2 §4.4).
|
||||
targetSnapshot: jsonb('target_snapshot').notNull(),
|
||||
// Present exactly on transfers: snapshot of the source/destination
|
||||
// parent ({ kind, id, slug }), CHECK-enforced below.
|
||||
transferFrom: jsonb('transfer_from'),
|
||||
transferTo: jsonb('transfer_to'),
|
||||
correlationId: text('correlation_id').notNull(),
|
||||
// Prior event in the causal chain (e.g. cascaded grant_revoke events
|
||||
// caused by a node delete). Self-FK RESTRICT keeps the chain intact.
|
||||
causationId: uuid('causation_id').references((): AnyPgColumn => hierarchyAuditEvents.id, {
|
||||
onDelete: 'restrict',
|
||||
}),
|
||||
idempotencyKey: text('idempotency_key').notNull(),
|
||||
occurredAt: timestamp('occurred_at', { withTimezone: true }).notNull().defaultNow(),
|
||||
},
|
||||
(t) => [
|
||||
uniqueIndex('hierarchy_audit_events_idempotency_idx').on(t.idempotencyKey),
|
||||
uniqueIndex('hierarchy_audit_events_seq_idx').on(t.seq),
|
||||
index('hierarchy_audit_events_target_seq_idx').on(t.targetId, t.seq),
|
||||
index('hierarchy_audit_events_correlation_idx').on(t.correlationId),
|
||||
check(
|
||||
'hierarchy_audit_events_verb_check',
|
||||
sql`verb IN ('create', 'rename', 'transfer', 'delete', 'grant_create', 'grant_change', 'grant_revoke')`,
|
||||
),
|
||||
check(
|
||||
'hierarchy_audit_events_target_kind_check',
|
||||
sql`target_kind IN ('company', 'estate', 'platform_project', 'grant')`,
|
||||
),
|
||||
check(
|
||||
'hierarchy_audit_events_transfer_check',
|
||||
sql`(verb = 'transfer') = (transfer_from IS NOT NULL AND transfer_to IS NOT NULL)`,
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
export const hierarchyOutboxStatusEnum = pgEnum('hierarchy_outbox_status', [
|
||||
'pending',
|
||||
'processing',
|
||||
'delivered',
|
||||
]);
|
||||
|
||||
export const hierarchyOutbox = pgTable(
|
||||
'hierarchy_outbox',
|
||||
{
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
// FK into the append-only events table (not a class table): never
|
||||
// dangles, so RESTRICT is safe and keeps event/outbox integrity.
|
||||
eventId: uuid('event_id')
|
||||
.notNull()
|
||||
.references(() => hierarchyAuditEvents.id, { onDelete: 'restrict' }),
|
||||
idempotencyKey: text('idempotency_key').notNull(),
|
||||
correlationId: text('correlation_id').notNull(),
|
||||
status: hierarchyOutboxStatusEnum('status').notNull().default('pending'),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
|
||||
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
|
||||
deliveredAt: timestamp('delivered_at', { withTimezone: true }),
|
||||
},
|
||||
(t) => [
|
||||
uniqueIndex('hierarchy_outbox_event_idx').on(t.eventId),
|
||||
uniqueIndex('hierarchy_outbox_idempotency_idx').on(t.idempotencyKey),
|
||||
index('hierarchy_outbox_status_created_idx').on(t.status, t.createdAt),
|
||||
],
|
||||
);
|
||||
|
||||
@@ -75,7 +75,7 @@ def run_pi_registry_command(
|
||||
runner=subprocess.run,
|
||||
sleeper=time.sleep,
|
||||
) -> subprocess.CompletedProcess[str]:
|
||||
"""Run a Pi probe command with bounded retries for concurrent-Pi stalls."""
|
||||
"""Run the registry probe with bounded retries for concurrent-Pi stalls."""
|
||||
|
||||
for attempt in range(1, PI_PROBE_ATTEMPTS + 1):
|
||||
try:
|
||||
@@ -106,7 +106,13 @@ def probe_pi_registry() -> list[dict[str, object]]:
|
||||
if pi is None:
|
||||
raise AssertionError("installed Pi runtime is required for Invariant R")
|
||||
|
||||
version = run_pi_registry_command([pi, "--version"], dict(os.environ))
|
||||
version = subprocess.run(
|
||||
[pi, "--version"],
|
||||
check=False,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=10,
|
||||
)
|
||||
if version.returncode != 0:
|
||||
raise AssertionError(f"Pi version probe failed: {version.stderr.strip()}")
|
||||
if version.stdout.strip() != PI_VERSION:
|
||||
|
||||
Reference in New Issue
Block a user