feat(fleet): add shared role semantics (#768)
This commit was merged in pull request #768.
This commit is contained in:
@@ -25,10 +25,10 @@
|
||||
* can reference a customized or user-added persona.
|
||||
*/
|
||||
|
||||
import { readFileSync, readdirSync } from 'node:fs';
|
||||
import { readFile, readdir } from 'node:fs/promises';
|
||||
import { lstatSync, readFileSync, readdirSync, statSync } from 'node:fs';
|
||||
import { lstat, readFile, readdir, stat } from 'node:fs/promises';
|
||||
import { homedir } from 'node:os';
|
||||
import { basename, join } from 'node:path';
|
||||
import { basename, isAbsolute, join, sep } from 'node:path';
|
||||
import type { Command } from 'commander';
|
||||
|
||||
function defaultMosaicHome(): string {
|
||||
@@ -53,52 +53,136 @@ export function defaultOverrideDir(mosaicHome = defaultMosaicHome()): string {
|
||||
const CLASS_MARKER = /`?class:\s*\n?\s*([a-z][a-z0-9-]*)`?/g;
|
||||
/** Optional `domain: Y` marker that travels alongside the class in the prose. */
|
||||
const DOMAIN_MARKER = /`?domain:\s*\n?\s*([a-z][a-z0-9-]*)`?/;
|
||||
/** LIBRARY.md persona rows: the first table cell is the persona name. */
|
||||
const LIBRARY_ROW = /^\|\s*([a-z][a-z0-9-]*)\s*\|/gm;
|
||||
|
||||
/** Where a resolved persona's definition came from. */
|
||||
export type PersonaLayer = 'baseline' | 'override';
|
||||
|
||||
export const ROLE_CLASS_ALIASES = Object.freeze({
|
||||
implementer: 'code',
|
||||
reviewer: 'review',
|
||||
'operator-interaction': 'interaction',
|
||||
} as const);
|
||||
|
||||
export interface CanonicalRoleClass {
|
||||
readonly requestedClass: string;
|
||||
readonly canonicalClass: string;
|
||||
}
|
||||
|
||||
/** Canonicalize only the three explicitly approved compatibility aliases. */
|
||||
export function canonicalizeRoleClass(requestedClass: string): CanonicalRoleClass {
|
||||
const requested = requestedClass.trim();
|
||||
const canonical = Object.hasOwn(ROLE_CLASS_ALIASES, requested)
|
||||
? ROLE_CLASS_ALIASES[requested as keyof typeof ROLE_CLASS_ALIASES]
|
||||
: requested;
|
||||
return Object.freeze({ requestedClass: requested, canonicalClass: canonical });
|
||||
}
|
||||
|
||||
export interface RoleAuthority {
|
||||
readonly mayMerge: boolean;
|
||||
readonly mayIssueValidationCertificate: boolean;
|
||||
readonly mayOrchestrate: boolean;
|
||||
readonly mayManageTopology: boolean;
|
||||
readonly mayIssueLeases: boolean;
|
||||
readonly leasedCapacityOnly: boolean;
|
||||
readonly requestStatusOnly: boolean;
|
||||
readonly mayMutateRoster: boolean;
|
||||
readonly mayMutateConfiguration: boolean;
|
||||
readonly mayAccessCredentials: boolean;
|
||||
}
|
||||
|
||||
const NO_PROTECTED_AUTHORITY: RoleAuthority = Object.freeze({
|
||||
mayMerge: false,
|
||||
mayIssueValidationCertificate: false,
|
||||
mayOrchestrate: false,
|
||||
mayManageTopology: false,
|
||||
mayIssueLeases: false,
|
||||
leasedCapacityOnly: false,
|
||||
requestStatusOnly: false,
|
||||
mayMutateRoster: false,
|
||||
mayMutateConfiguration: false,
|
||||
mayAccessCredentials: false,
|
||||
});
|
||||
|
||||
/** Immutable authority contracts keyed only by canonical class identity. */
|
||||
export const ROLE_AUTHORITY_BY_CANONICAL_CLASS: Readonly<Record<string, RoleAuthority>> =
|
||||
Object.freeze({
|
||||
'merge-gate': Object.freeze({ ...NO_PROTECTED_AUTHORITY, mayMerge: true }),
|
||||
validator: Object.freeze({
|
||||
...NO_PROTECTED_AUTHORITY,
|
||||
mayIssueValidationCertificate: true,
|
||||
}),
|
||||
orchestrator: Object.freeze({
|
||||
...NO_PROTECTED_AUTHORITY,
|
||||
mayOrchestrate: true,
|
||||
mayManageTopology: true,
|
||||
mayIssueLeases: true,
|
||||
}),
|
||||
'team-leader': Object.freeze({ ...NO_PROTECTED_AUTHORITY, leasedCapacityOnly: true }),
|
||||
interaction: Object.freeze({ ...NO_PROTECTED_AUTHORITY, requestStatusOnly: true }),
|
||||
});
|
||||
|
||||
/** Return protected authority for an already-canonical class; custom classes get none. */
|
||||
export function authorityForCanonicalClass(canonicalClass: string): RoleAuthority {
|
||||
return Object.hasOwn(ROLE_AUTHORITY_BY_CANONICAL_CLASS, canonicalClass)
|
||||
? ROLE_AUTHORITY_BY_CANONICAL_CLASS[canonicalClass]!
|
||||
: NO_PROTECTED_AUTHORITY;
|
||||
}
|
||||
|
||||
/** One discovered persona file (a single role contract on disk). */
|
||||
export interface PersonaFile {
|
||||
klass: string;
|
||||
/** The markdown file the class was found in. */
|
||||
file: string;
|
||||
/** True when the first class marker, rather than filename, defined this mapping. */
|
||||
markerDefined?: boolean;
|
||||
domain?: string;
|
||||
}
|
||||
|
||||
export type DirScanState = 'scanned' | 'missing' | 'error';
|
||||
|
||||
/** The set of persona classes a directory of role contracts defines. */
|
||||
export interface DirClasses {
|
||||
/** Every class name the dir contributes (markers + filenames + LIBRARY rows). */
|
||||
/** Whether the directory was scanned, absent, or present-but-unscannable. */
|
||||
scanState: DirScanState;
|
||||
/** Every readable class name the directory contributes by filename or first marker. */
|
||||
classes: Set<string>;
|
||||
/** Filename stems present on disk, retained even when a markdown entry is unreadable. */
|
||||
fileStems: Set<string>;
|
||||
/** For classes whose file carries a marker, the file + domain that defined it. */
|
||||
byClass: Map<string, PersonaFile>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Scan one directory of role contracts and extract the persona classes it
|
||||
* defines. THIS is the shared extraction both fleet-personas and fleet-profiles
|
||||
* rely on. Sources, unioned (each needed — see module doc):
|
||||
* 1. inline `class: X` markers in roles/*.md (primary; may wrap a newline),
|
||||
* 2. persona-name cells from LIBRARY.md index tables,
|
||||
* 3. the role filename stem (covers marker-less alias docs like planner).
|
||||
* Scan one directory of role contracts and extract readable persona identities.
|
||||
* Valid identities come only from a successfully read non-LIBRARY filename and
|
||||
* that file's first `class:` marker. LIBRARY rows and later prose mentions are
|
||||
* index/reference data, not independently readable role contracts.
|
||||
*
|
||||
* Missing dir / unreadable files degrade gracefully to whatever was found.
|
||||
* `byClass` records the defining file+domain for marker-bearing classes so the
|
||||
* resolver can map a class back to its file; filename-only and LIBRARY-only
|
||||
* classes still appear in `classes` for membership checks.
|
||||
* Missing directories are distinguished from present-but-unscannable paths.
|
||||
* `byClass` records the first marker-defined file+domain so the resolver can map
|
||||
* a class back to its contract; marker-less readable files map by filename.
|
||||
*/
|
||||
export async function extractClassesFromDir(dir: string): Promise<DirClasses> {
|
||||
const acc: DirClasses = { classes: new Set<string>(), byClass: new Map<string, PersonaFile>() };
|
||||
const acc: DirClasses = {
|
||||
scanState: 'scanned',
|
||||
classes: new Set<string>(),
|
||||
fileStems: new Set<string>(),
|
||||
byClass: new Map<string, PersonaFile>(),
|
||||
};
|
||||
let entries: string[];
|
||||
try {
|
||||
entries = await readdir(dir);
|
||||
} catch {
|
||||
} catch (error) {
|
||||
acc.scanState = await classifyScanFailure(dir, error);
|
||||
return acc;
|
||||
}
|
||||
|
||||
for (const entry of entries) {
|
||||
if (!entry.endsWith('.md')) continue;
|
||||
// Preserve entry presence separately from valid readable classes. Resolvers
|
||||
// use it to fail closed on an explicit unreadable canonical override without
|
||||
// advertising that override through class listing/status APIs.
|
||||
if (entry !== 'LIBRARY.md') acc.fileStems.add(basename(entry, '.md'));
|
||||
let text: string;
|
||||
try {
|
||||
text = await readFile(join(dir, entry), 'utf8');
|
||||
@@ -117,16 +201,25 @@ export async function extractClassesFromDir(dir: string): Promise<DirClasses> {
|
||||
* cannot await. Missing dir / unreadable files degrade gracefully.
|
||||
*/
|
||||
export function extractClassesFromDirSync(dir: string): DirClasses {
|
||||
const acc: DirClasses = { classes: new Set<string>(), byClass: new Map<string, PersonaFile>() };
|
||||
const acc: DirClasses = {
|
||||
scanState: 'scanned',
|
||||
classes: new Set<string>(),
|
||||
fileStems: new Set<string>(),
|
||||
byClass: new Map<string, PersonaFile>(),
|
||||
};
|
||||
let entries: string[];
|
||||
try {
|
||||
entries = readdirSync(dir);
|
||||
} catch {
|
||||
} catch (error) {
|
||||
acc.scanState = classifyScanFailureSync(dir, error);
|
||||
return acc;
|
||||
}
|
||||
|
||||
for (const entry of entries) {
|
||||
if (!entry.endsWith('.md')) continue;
|
||||
// Keep sync extraction equivalent to the async scanner, including unreadable
|
||||
// filename presence kept separate from valid readable classes.
|
||||
if (entry !== 'LIBRARY.md') acc.fileStems.add(basename(entry, '.md'));
|
||||
let text: string;
|
||||
try {
|
||||
text = readFileSync(join(dir, entry), 'utf8');
|
||||
@@ -138,6 +231,74 @@ export function extractClassesFromDirSync(dir: string): DirClasses {
|
||||
return acc;
|
||||
}
|
||||
|
||||
async function classifyScanFailure(dir: string, error: unknown): Promise<DirScanState> {
|
||||
if (!isMissingPathError(error)) return 'error';
|
||||
return (await hasBrokenSymlinkInPath(dir)) ? 'error' : 'missing';
|
||||
}
|
||||
|
||||
function classifyScanFailureSync(dir: string, error: unknown): DirScanState {
|
||||
if (!isMissingPathError(error)) return 'error';
|
||||
return hasBrokenSymlinkInPathSync(dir) ? 'error' : 'missing';
|
||||
}
|
||||
|
||||
function traversalPrefixes(path: string): string[] {
|
||||
const absolute = isAbsolute(path) ? path : `${process.cwd()}${sep}${path}`;
|
||||
const parts = absolute.split(sep);
|
||||
const prefixes: string[] = [];
|
||||
let current: string = sep;
|
||||
for (const part of parts) {
|
||||
if (!part) continue;
|
||||
current = current === sep ? `${sep}${part}` : `${current}${sep}${part}`;
|
||||
prefixes.push(current);
|
||||
}
|
||||
return prefixes;
|
||||
}
|
||||
|
||||
async function hasBrokenSymlinkInPath(path: string): Promise<boolean> {
|
||||
for (const current of traversalPrefixes(path)) {
|
||||
try {
|
||||
const entry = await lstat(current);
|
||||
if (entry.isSymbolicLink()) {
|
||||
try {
|
||||
await stat(current);
|
||||
} catch {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
if (!isMissingPathError(error)) return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function hasBrokenSymlinkInPathSync(path: string): boolean {
|
||||
for (const current of traversalPrefixes(path)) {
|
||||
try {
|
||||
const entry = lstatSync(current);
|
||||
if (entry.isSymbolicLink()) {
|
||||
try {
|
||||
statSync(current);
|
||||
} catch {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
if (!isMissingPathError(error)) return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function isMissingPathError(error: unknown): boolean {
|
||||
return (
|
||||
typeof error === 'object' &&
|
||||
error !== null &&
|
||||
'code' in error &&
|
||||
(error as { code?: unknown }).code === 'ENOENT'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply the class-extraction rules for ONE role file's text into `acc`. Pure
|
||||
* over already-read content, so the async and sync directory scanners share a
|
||||
@@ -146,33 +307,26 @@ export function extractClassesFromDirSync(dir: string): DirClasses {
|
||||
*/
|
||||
function accumulateEntry(acc: DirClasses, dir: string, entry: string, text: string): void {
|
||||
const { classes, byClass } = acc;
|
||||
if (entry === 'LIBRARY.md') {
|
||||
for (const m of text.matchAll(LIBRARY_ROW)) {
|
||||
const name = m[1];
|
||||
if (name && name !== 'persona') classes.add(name);
|
||||
}
|
||||
return;
|
||||
}
|
||||
// The filename stem is itself a valid class (covers marker-less alias docs).
|
||||
if (entry === 'LIBRARY.md') return;
|
||||
|
||||
// An explicit first marker owns identity. Filename identity is a fallback only
|
||||
// for markerless compatibility contracts such as planner.md.
|
||||
const stem = basename(entry, '.md');
|
||||
classes.add(stem);
|
||||
const domainMatch = DOMAIN_MARKER.exec(text);
|
||||
const domain = domainMatch?.[1];
|
||||
let markedClassForFile: string | undefined;
|
||||
for (const m of text.matchAll(CLASS_MARKER)) {
|
||||
const klass = m[1];
|
||||
if (!klass) continue;
|
||||
classes.add(klass);
|
||||
// Record the FIRST marker as the file's defining class (the prose names
|
||||
// the persona's own class up top; later mentions reference siblings).
|
||||
if (!markedClassForFile) {
|
||||
markedClassForFile = klass;
|
||||
byClass.set(klass, { klass, file: join(dir, entry), ...(domain ? { domain } : {}) });
|
||||
}
|
||||
}
|
||||
// A marker-less file still maps its stem to itself (no domain known).
|
||||
if (!markedClassForFile && !byClass.has(stem)) {
|
||||
byClass.set(stem, { klass: stem, file: join(dir, entry) });
|
||||
const firstMarker = text.matchAll(CLASS_MARKER).next().value as RegExpExecArray | undefined;
|
||||
const markedClassForFile = firstMarker?.[1];
|
||||
if (markedClassForFile) {
|
||||
classes.add(markedClassForFile);
|
||||
byClass.set(markedClassForFile, {
|
||||
klass: markedClassForFile,
|
||||
file: join(dir, entry),
|
||||
markerDefined: true,
|
||||
...(domain ? { domain } : {}),
|
||||
});
|
||||
} else {
|
||||
classes.add(stem);
|
||||
if (!byClass.has(stem)) byClass.set(stem, { klass: stem, file: join(dir, entry) });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -193,24 +347,19 @@ function resolveDirs(opts: PersonaDirs): { rolesDir: string; overrideDir: string
|
||||
}
|
||||
|
||||
/**
|
||||
* UNION of baseline classes and override classes. Overrides may ADD entirely new
|
||||
* classes not present in the baseline, so callers (e.g. profile roster
|
||||
* validation) treat a user-added persona as a real class.
|
||||
* Every class with an actually readable winning contract. Discovery applies the
|
||||
* same override shadow/fail-closed semantics as resolution, so callers never
|
||||
* advertise a class that cannot be used.
|
||||
*/
|
||||
export async function listPersonaClasses(opts: PersonaDirs = {}): Promise<Set<string>> {
|
||||
const { rolesDir, overrideDir } = resolveDirs(opts);
|
||||
const [base, over] = await Promise.all([
|
||||
extractClassesFromDir(rolesDir),
|
||||
extractClassesFromDir(overrideDir),
|
||||
]);
|
||||
const union = new Set<string>(base.classes);
|
||||
for (const c of over.classes) union.add(c);
|
||||
return union;
|
||||
const { personas } = await collectUsablePersonas(opts);
|
||||
return new Set(personas.keys());
|
||||
}
|
||||
|
||||
export type PersonaStatus = 'baseline' | 'overridden' | 'custom';
|
||||
|
||||
export interface PersonaResolution {
|
||||
export interface PersonaResolution extends CanonicalRoleClass {
|
||||
/** Compatibility name for the canonical class. */
|
||||
klass: string;
|
||||
layer: PersonaLayer;
|
||||
/** The file the resolved persona was read from (override wins). */
|
||||
@@ -219,6 +368,118 @@ export interface PersonaResolution {
|
||||
domain?: string;
|
||||
}
|
||||
|
||||
async function readPersonaFromLayer(
|
||||
requestedClass: string,
|
||||
canonicalClass: string,
|
||||
dir: string,
|
||||
extracted: DirClasses,
|
||||
layer: PersonaLayer,
|
||||
): Promise<PersonaResolution | null> {
|
||||
const pf = extracted.byClass.get(canonicalClass);
|
||||
if (!pf) {
|
||||
if (!extracted.classes.has(canonicalClass)) return null;
|
||||
const byName = join(dir, `${canonicalClass}.md`);
|
||||
try {
|
||||
const content = await readFile(byName, 'utf8');
|
||||
const currentMarker = content.matchAll(CLASS_MARKER).next().value as
|
||||
| RegExpExecArray
|
||||
| undefined;
|
||||
if (currentMarker && currentMarker[1] !== canonicalClass) return null;
|
||||
const dm = DOMAIN_MARKER.exec(content);
|
||||
return {
|
||||
requestedClass,
|
||||
canonicalClass,
|
||||
klass: canonicalClass,
|
||||
layer,
|
||||
file: byName,
|
||||
content,
|
||||
...(dm?.[1] ? { domain: dm[1] } : {}),
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
try {
|
||||
const content = await readFile(pf.file, 'utf8');
|
||||
const currentMarker = content.matchAll(CLASS_MARKER).next().value as
|
||||
| RegExpExecArray
|
||||
| undefined;
|
||||
if (currentMarker && currentMarker[1] !== canonicalClass) return null;
|
||||
const dm = DOMAIN_MARKER.exec(content);
|
||||
return {
|
||||
requestedClass,
|
||||
canonicalClass,
|
||||
klass: canonicalClass,
|
||||
layer,
|
||||
file: pf.file,
|
||||
content,
|
||||
...(dm?.[1] ? { domain: dm[1] } : {}),
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function overrideShadowsBaseline(over: DirClasses, canonicalClass: string): boolean {
|
||||
return (
|
||||
over.scanState === 'error' ||
|
||||
over.fileStems.has(canonicalClass) ||
|
||||
over.byClass.has(canonicalClass)
|
||||
);
|
||||
}
|
||||
|
||||
function readPersonaFromLayerSync(
|
||||
requestedClass: string,
|
||||
canonicalClass: string,
|
||||
dir: string,
|
||||
extracted: DirClasses,
|
||||
layer: PersonaLayer,
|
||||
): PersonaResolution | null {
|
||||
const pf = extracted.byClass.get(canonicalClass);
|
||||
if (!pf) {
|
||||
if (!extracted.classes.has(canonicalClass)) return null;
|
||||
const byName = join(dir, `${canonicalClass}.md`);
|
||||
try {
|
||||
const content = readFileSync(byName, 'utf8');
|
||||
const currentMarker = content.matchAll(CLASS_MARKER).next().value as
|
||||
| RegExpExecArray
|
||||
| undefined;
|
||||
if (currentMarker && currentMarker[1] !== canonicalClass) return null;
|
||||
const dm = DOMAIN_MARKER.exec(content);
|
||||
return {
|
||||
requestedClass,
|
||||
canonicalClass,
|
||||
klass: canonicalClass,
|
||||
layer,
|
||||
file: byName,
|
||||
content,
|
||||
...(dm?.[1] ? { domain: dm[1] } : {}),
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
try {
|
||||
const content = readFileSync(pf.file, 'utf8');
|
||||
const currentMarker = content.matchAll(CLASS_MARKER).next().value as
|
||||
| RegExpExecArray
|
||||
| undefined;
|
||||
if (currentMarker && currentMarker[1] !== canonicalClass) return null;
|
||||
const dm = DOMAIN_MARKER.exec(content);
|
||||
return {
|
||||
requestedClass,
|
||||
canonicalClass,
|
||||
klass: canonicalClass,
|
||||
layer,
|
||||
file: pf.file,
|
||||
content,
|
||||
...(dm?.[1] ? { domain: dm[1] } : {}),
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a persona class to its winning definition: the override file if
|
||||
* roles.local/ defines that class, else the baseline. Match by inline `class:`
|
||||
@@ -245,42 +506,32 @@ export async function resolvePersona(
|
||||
* is identical to {@link resolvePersona}: override layer wins, then baseline.
|
||||
*/
|
||||
export async function resolvePersonaFrom(
|
||||
klass: string,
|
||||
requestedClass: string,
|
||||
layers: { rolesDir: string; overrideDir: string; base: DirClasses; over: DirClasses },
|
||||
): Promise<PersonaResolution | null> {
|
||||
const { requestedClass: requested, canonicalClass: klass } =
|
||||
canonicalizeRoleClass(requestedClass);
|
||||
const { rolesDir, overrideDir, base, over } = layers;
|
||||
|
||||
const fromLayer = async (
|
||||
dir: string,
|
||||
extracted: DirClasses,
|
||||
layer: PersonaLayer,
|
||||
): Promise<PersonaResolution | null> => {
|
||||
// Prefer the marker-defined file; fall back to the filename stem.
|
||||
let pf = extracted.byClass.get(klass);
|
||||
if (!pf) {
|
||||
const byName = join(dir, `${klass}.md`);
|
||||
if (!extracted.classes.has(klass)) return null;
|
||||
// Class known only via filename/LIBRARY: read the stem file if present.
|
||||
try {
|
||||
const content = await readFile(byName, 'utf8');
|
||||
const dm = DOMAIN_MARKER.exec(content);
|
||||
return { klass, layer, file: byName, content, ...(dm?.[1] ? { domain: dm[1] } : {}) };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
try {
|
||||
const content = await readFile(pf.file, 'utf8');
|
||||
return { klass, layer, file: pf.file, content, ...(pf.domain ? { domain: pf.domain } : {}) };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
const override = await readPersonaFromLayer(requested, klass, overrideDir, over, 'override');
|
||||
if (override) return override;
|
||||
// An observed explicit override that cannot resolve/read shadows the baseline.
|
||||
if (overrideShadowsBaseline(over, klass)) return null;
|
||||
|
||||
return (
|
||||
(await fromLayer(overrideDir, over, 'override')) ??
|
||||
(await fromLayer(rolesDir, base, 'baseline'))
|
||||
// Cached scans are only snapshots. Re-scan immediately before baseline fallback
|
||||
// so a newly created canonical or marker-defined override cannot be skipped.
|
||||
const currentOver = await extractClassesFromDir(overrideDir);
|
||||
const currentOverride = await readPersonaFromLayer(
|
||||
requested,
|
||||
klass,
|
||||
overrideDir,
|
||||
currentOver,
|
||||
'override',
|
||||
);
|
||||
if (currentOverride) return currentOverride;
|
||||
if (overrideShadowsBaseline(currentOver, klass)) return null;
|
||||
if (currentOver.scanState === 'error') return null;
|
||||
return readPersonaFromLayer(requested, klass, rolesDir, base, 'baseline');
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -292,40 +543,55 @@ export async function resolvePersonaFrom(
|
||||
* one module so the launch-time and command-time resolutions never diverge.
|
||||
*/
|
||||
export function resolvePersonaSync(
|
||||
klass: string,
|
||||
requestedClass: string,
|
||||
opts: PersonaDirs = {},
|
||||
): PersonaResolution | null {
|
||||
const { requestedClass: requested, canonicalClass: klass } =
|
||||
canonicalizeRoleClass(requestedClass);
|
||||
const { rolesDir, overrideDir } = resolveDirs(opts);
|
||||
const base = extractClassesFromDirSync(rolesDir);
|
||||
const over = extractClassesFromDirSync(overrideDir);
|
||||
|
||||
const fromLayer = (
|
||||
dir: string,
|
||||
extracted: DirClasses,
|
||||
layer: PersonaLayer,
|
||||
): PersonaResolution | null => {
|
||||
// Prefer the marker-defined file; fall back to the filename stem.
|
||||
const pf = extracted.byClass.get(klass);
|
||||
if (!pf) {
|
||||
if (!extracted.classes.has(klass)) return null;
|
||||
const byName = join(dir, `${klass}.md`);
|
||||
try {
|
||||
const content = readFileSync(byName, 'utf8');
|
||||
const dm = DOMAIN_MARKER.exec(content);
|
||||
return { klass, layer, file: byName, content, ...(dm?.[1] ? { domain: dm[1] } : {}) };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
try {
|
||||
const content = readFileSync(pf.file, 'utf8');
|
||||
return { klass, layer, file: pf.file, content, ...(pf.domain ? { domain: pf.domain } : {}) };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
const override = readPersonaFromLayerSync(requested, klass, overrideDir, over, 'override');
|
||||
if (override) return override;
|
||||
if (overrideShadowsBaseline(over, klass)) return null;
|
||||
return readPersonaFromLayerSync(requested, klass, rolesDir, base, 'baseline');
|
||||
}
|
||||
|
||||
return fromLayer(overrideDir, over, 'override') ?? fromLayer(rolesDir, base, 'baseline');
|
||||
interface UsablePersonaIndex {
|
||||
personas: Map<string, PersonaResolution>;
|
||||
readableBaseline: Set<string>;
|
||||
}
|
||||
|
||||
async function collectUsablePersonas(opts: PersonaDirs): Promise<UsablePersonaIndex> {
|
||||
const { rolesDir, overrideDir } = resolveDirs(opts);
|
||||
const [base, over] = await Promise.all([
|
||||
extractClassesFromDir(rolesDir),
|
||||
extractClassesFromDir(overrideDir),
|
||||
]);
|
||||
if (over.scanState === 'error') {
|
||||
return { personas: new Map(), readableBaseline: new Set() };
|
||||
}
|
||||
|
||||
const candidates = new Set<string>([...base.classes, ...over.classes]);
|
||||
const checked = await Promise.all(
|
||||
[...candidates].map(async (requestedClass) => {
|
||||
const { canonicalClass } = canonicalizeRoleClass(requestedClass);
|
||||
const [persona, baseline] = await Promise.all([
|
||||
resolvePersonaFrom(requestedClass, { rolesDir, overrideDir, base, over }),
|
||||
readPersonaFromLayer(requestedClass, canonicalClass, rolesDir, base, 'baseline'),
|
||||
]);
|
||||
return { requestedClass, persona, baseline };
|
||||
}),
|
||||
);
|
||||
|
||||
const personas = new Map<string, PersonaResolution>();
|
||||
const readableBaseline = new Set<string>();
|
||||
for (const { requestedClass, persona, baseline } of checked) {
|
||||
if (persona) personas.set(requestedClass, persona);
|
||||
if (baseline) readableBaseline.add(requestedClass);
|
||||
}
|
||||
return { personas, readableBaseline };
|
||||
}
|
||||
|
||||
export interface PersonaStatusEntry {
|
||||
@@ -342,24 +608,20 @@ export interface PersonaStatusEntry {
|
||||
* Domain is taken from the WINNING layer (override domain wins if present).
|
||||
*/
|
||||
export async function personaStatus(opts: PersonaDirs = {}): Promise<PersonaStatusEntry[]> {
|
||||
const { rolesDir, overrideDir } = resolveDirs(opts);
|
||||
const [base, over] = await Promise.all([
|
||||
extractClassesFromDir(rolesDir),
|
||||
extractClassesFromDir(overrideDir),
|
||||
]);
|
||||
|
||||
const all = new Set<string>([...base.classes, ...over.classes]);
|
||||
const domainOf = (extracted: DirClasses, klass: string): string | undefined =>
|
||||
extracted.byClass.get(klass)?.domain;
|
||||
|
||||
const entries: PersonaStatusEntry[] = [];
|
||||
for (const klass of all) {
|
||||
const inBase = base.classes.has(klass);
|
||||
const inOver = over.classes.has(klass);
|
||||
const status: PersonaStatus = inOver ? (inBase ? 'overridden' : 'custom') : 'baseline';
|
||||
const domain = (inOver ? domainOf(over, klass) : undefined) ?? domainOf(base, klass);
|
||||
entries.push({ klass, status, ...(domain ? { domain } : {}) });
|
||||
}
|
||||
const { personas, readableBaseline } = await collectUsablePersonas(opts);
|
||||
const entries = [...personas.entries()].map(([klass, persona]): PersonaStatusEntry => {
|
||||
const status: PersonaStatus =
|
||||
persona.layer === 'baseline'
|
||||
? 'baseline'
|
||||
: readableBaseline.has(klass)
|
||||
? 'overridden'
|
||||
: 'custom';
|
||||
return {
|
||||
klass,
|
||||
status,
|
||||
...(persona.domain ? { domain: persona.domain } : {}),
|
||||
};
|
||||
});
|
||||
entries.sort((a, b) => a.klass.localeCompare(b.klass));
|
||||
return entries;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user