/** Standard goal specs. Projects supply accountability and hydrate specs with goal(). */
import { fileURLToPath } from "node:url";
import { goal, GoalError, refSafe, type DefaultedSpec, type DemonstratedSpec, type GoalSpec, type Judge } from "./goal.ts";
type DemonstratedGoal = GoalSpec<DemonstratedSpec>;
type DemonstratedDraft = DefaultedSpec<DemonstratedSpec, Pick<DemonstratedGoal, "owner">>;
// Preserve the engine’s paired judge and criteria types when replacing fields.
type DemonstratedInput<T = DemonstratedDraft> = T extends DemonstratedDraft ? Omit<T, "statement" | "hold" | "measure" | "acceptance"> & {
statement?: string;
acceptance: Record<string, string>;
} : never;
/** For a single acceptance entry its text is also the default goal statement. */
export function demonstratedGoal(spec: DemonstratedInput & Pick<DemonstratedGoal, "owner">): DemonstratedGoal;
export function demonstratedGoal(spec: DemonstratedInput): DemonstratedDraft;
export function demonstratedGoal({ id, statement, owner, nextReview, acceptance, ...fields }: DemonstratedInput): DemonstratedDraft {
const entries = Object.values(acceptance);
if (!entries.length) throw new GoalError(`goal "${id}" needs at least one acceptance entry`);
if (statement === undefined && entries.length !== 1) {
throw new GoalError(`goal "${id}" needs a statement for multiple acceptance entries`);
}
return {
id, statement: statement ?? entries[0]!, ...(owner !== undefined && { owner }), ...(nextReview && { nextReview }), ...fields,
hold: { max: 0 }, measure: { demonstrated: true }, acceptance,
};
}
type BehaviorGoal = {
id: string;
statement?: string;
acceptance: Record<string, string>;
};
type CompatibilitySlice = Required<Pick<GoalSpec, "owner" | "nextReview">> & {
project: string;
scope: string;
focus: string;
} & (
| { behaviors: Record<string, string>; goals?: never }
| { goals: readonly BehaviorGoal[]; behaviors?: never }
);
type CompatibilityBundle = {
goals: GoalSpec<DemonstratedSpec>[];
submission: { version: 1; contextParent: string; guidanceGoals: string[] };
};
/** Expand a scoped reconstruction into portable goal specs and a submission manifest. */
export function compatibilitySlice({ project, scope, focus, owner, nextReview, behaviors, goals }: CompatibilitySlice): CompatibilityBundle {
if ((behaviors === undefined) === (goals === undefined)) {
throw new GoalError(`slice "${project}" needs exactly one of behaviors or goals`);
}
if (goals !== undefined && !Array.isArray(goals)) throw new GoalError(`slice "${project}" needs an ordered goals array`);
if (behaviors !== undefined && (!behaviors || typeof behaviors !== "object" || Array.isArray(behaviors))) {
throw new GoalError(`slice "${project}" needs a behaviors map`);
}
const definitions = goals ?? Object.entries(behaviors!).map(([entry, text]) => ({
id: `${project}-${entry}`, acceptance: { [entry]: text },
}));
if (!definitions.length) throw new GoalError(`slice "${project}" needs a behavior`);
if (!scope.trim() || !focus.trim()) throw new GoalError(`slice "${project}" needs a scope and focus`);
const charter = refSafe("charter id", `${project}.context.charter`);
const compatibility = `${project}.context.compatibility`;
const clarity = `${project}.context.clarity`;
const focusId = `${project}.context.focus`;
const implementation = `${project}.context.implementation`;
const group = { goal: charter, id: "delivery" };
const mandate = { goal: charter, id: "implementation-mandate" };
const ids = new Set([charter, compatibility, clarity, focusId, implementation]);
const behaviorGoals = Array.from(definitions, (definition: BehaviorGoal) => {
if (!definition || !definition.acceptance || typeof definition.acceptance !== "object" || Array.isArray(definition.acceptance)) {
throw new GoalError(`slice "${project}" needs an acceptance map for each goal`);
}
if (Object.keys(definition).some(key => !["id", "statement", "acceptance"].includes(key))) {
throw new GoalError(`slice "${project}" behavior goals accept only id, statement and acceptance`);
}
if (typeof definition.id !== "string") throw new GoalError(`slice "${project}" needs a string goal id`);
if (definition.statement !== undefined && typeof definition.statement !== "string") {
throw new GoalError(`goal "${definition.id}" needs a string statement`);
}
if (ids.has(definition.id)) throw new GoalError(`slice "${project}" has duplicate goal id "${definition.id}"`);
ids.add(definition.id);
const spec = demonstratedGoal({ ...definition, acceptance: { ...definition.acceptance }, owner, nextReview });
goal(spec); // Check the engine's ID, statement and acceptance rules before emitting portable JSON.
return { ...spec, context: { parent: implementation }, serves: [compatibility] };
});
const scopeName = scope === "README.md" ? "README" : scope;
const guidance: GoalSpec[] = [
{
id: charter,
statement: `Deliver the documented ${project} compatibility slice with all stated contracts intact. The ${scopeName} scope and exclusions remain authoritative; this is not a claim of full upstream equivalence.`,
owner, nextReview,
context: {
obligations: behaviorGoals.map(g => g.id),
groups: [{ id: group.id, priorities: [{ goal: compatibility, scope: charter }, { goal: clarity, scope: charter }] }],
grants: [{
id: mandate.id, group, to: { goal: implementation, owner }, redelegate: false,
because: "Allow project-specific implementation focus while retaining every compatibility obligation.",
}],
},
},
{
id: compatibility,
statement: `Preserve every stated ${project} public behavior, failure semantic and scope boundary. Completion requires all registered acceptance entries, not just the current implementation focus.`,
owner, nextReview,
},
{
id: clarity,
statement: "Prefer a coherent implementation whose behavior and meaningful tests are understandable. This is qualitative guidance within the required compatibility scope, not an extra mechanical acceptance claim.",
owner, nextReview,
},
{ id: focusId, statement: focus, owner, nextReview, serves: [compatibility] },
{
id: implementation,
statement: `Implement and validate the complete ${project} slice. Use the project focus to order investigation and implementation effort; it does not narrow the required feature set.`,
owner, nextReview, serves: [charter],
context: {
parent: charter,
adjustments: [{
group, using: mandate, priorities: [{ goal: focusId, scope: implementation }, { goal: clarity, scope: implementation }],
because: `${focus} This local focus contributes to complete compatibility rather than replacing it.`,
}],
},
},
];
return {
goals: [...guidance, ...behaviorGoals],
submission: { version: 1, contextParent: implementation, guidanceGoals: guidance.map(g => g.id) },
};
}
export function buildTypecheck() {
return {
id: "build.typecheck",
statement: "The code typechecks with no errors under TypeScript's strict mode.",
hold: { max: 0 },
measure: { from: "artifact:typecheck", version: 2, unit: "errors", value: (t: { errors: number }) => t.errors },
};
}
type TestReport = { ok: boolean; failed: number };
/** With acceptance tags enabled, the runner also reports every unrecognized reference. */
export function buildTests({ validateTags = false } = {}) {
return {
id: "build.tests",
statement: validateTags ? "The test suite passes and its acceptance references exist." : "The test suite passes.",
hold: { max: 0 },
measure: {
from: "artifact:tests",
version: validateTags ? 4 : 2,
unit: validateTags ? "faults" : "failing",
value(report: TestReport & { mistagged?: string[] }) {
if (!validateTags) return report.ok && report.failed === 0 ? 0 : Math.max(1, report.failed);
const failures = report.ok ? report.failed : Math.max(1, report.failed);
if (!Array.isArray(report.mistagged)) throw new Error("Tagged test evidence needs a mistagged array");
return failures + report.mistagged.length;
},
},
};
}
/** A reusable editorial standard for public prose, reviewed against its source facts. */
export function crispAnalyticalAmericanEnglish(judge: Judge, prompt = fileURLToPath(new URL("../goals/judges/crisp-analytical-american-english.md", import.meta.url))) {
return {
id: "prose.crisp-analytical-american-english",
statement: "Use Crisp Analytical American English for reader-facing prose. Lead with the material point, support it with concrete facts, and preserve technical meaning.",
judge,
criteria: {
prompt,
scale: { 1: "Obscures or changes the claim", 3: "Accurate but needs editorial work", 5: "Clear, concrete, and faithful to the evidence" },
},
};
}
/** Review changed user-facing errors using the project's reviewer and the shared recovery rubric. */
export function errorsHumane(judge: Judge, prompt = fileURLToPath(new URL("../goals/judges/errors-humane.md", import.meta.url))) {
return {
id: "errors.humane",
statement: "Errors help the user recover and never expose internals.",
judge,
criteria: {
prompt,
scale: { 1: "Misleading, unsafe, or exposes internals", 3: "Accurate but unhelpful", 5: "Gives an accurate, actionable recovery step" },
},
};
}
/** The harness supplies the reviewer. The package ships the goal’s scoring rubric. */
export function testsFaithful(judge: Judge, prompt = fileURLToPath(new URL("../goals/judges/tests-faithful.md", import.meta.url))) {
return {
id: "tests.faithful",
statement: "Automated feedback makes the stated behavioral contracts checkable and changes easy to verify. The test suite collectively provides credible evidence for the behavior users rely on, including state transitions, failure guarantees and meaningful regressions.",
acceptance: {
clauses: "Taken together, tests cover the stated behavior and important refusals, boundaries and recovery guarantees. Different tests may cover different clauses of one entry, and one test may support several entries; traceability does not imply that each test proves the whole entry.",
"valid-refusals": "A claimed refusal test reaches the condition it intends to exercise. An unrelated setup or validation failure is not evidence for that condition; suitable fixtures, controls or focused assertions make the reason clear.",
"causal-evidence": "Assertions check meaningful observable outcomes and relevant state after failure. Evidence is chosen proportionately to risk; mutation testing and other fault injection can reveal gaps but are optional techniques, not required for every test or clause. Material coverage limitations are disclosed without claiming exhaustive proof.",
clarity: "A reader can identify the scenario, relevant starting state, action and promised outcome of a test, including what failure would mean for the contract. Tests protect observable behavior rather than mirroring implementation steps; types and other automated checks complement tests where they provide relevant evidence.",
},
judge,
criteria: {
prompt,
scale: {
1: "Automated checks give little intelligible evidence of required behavior",
2: "Important contracts or failure guarantees lack credible verification",
3: "Core behavior is checkable but material evidence or scenario-clarity gaps remain",
4: "Clear scenarios credibly verify important contracts and failure boundaries with limited gaps",
5: "Understandable, risk-appropriate feedback makes meaningful behavior changes verifiable with no identified material gaps",
},
},
};
}
/**
* Add author-selected examples of observable behavior to one acceptance statement.
* Examples are specification text. Passing tests still supply demonstrated evidence.
*/
export function acceptanceWithExamples(
rule: string,
examples: readonly { scenario: string; result: string }[],
): string {
if (!rule.trim()) throw new GoalError("an acceptance rule needs a nonempty statement");
if (!examples.length) return rule;
const lines = examples.map(({ scenario, result }) => {
if (!scenario.trim() || !result.trim()) {
throw new GoalError("an acceptance example needs a nonempty scenario and result");
}
return `- ${scenario.trim()} → ${result.trim()}`;
});
return `${rule.trimEnd()}\n\nExamples\n${lines.join("\n")}`;
}
export { compatibilityReadme, javascriptCompatibilityReadme } from "./compatibility-readme.ts";
export { defineVisualLanguage, mnmxVisualLanguage, visualLanguageGoal, type VisualLanguage } from "./visual-language.ts";