diff --git a/lexicons/cedar/README.md b/lexicons/cedar/README.md
index 37e43ab5b7..84bdad21bf 100644
--- a/lexicons/cedar/README.md
+++ b/lexicons/cedar/README.md
@@ -17,6 +17,11 @@ INTENTIUS/chant#1645: the upstream pin (#1648), the scaffold and serializer
import/reconcile (#1653), the docs/LSP/MCP/skills/composites surface (#1654),
and CI/publishing onboarding (#1655).
+Landing beside it, and pre-release on its own terms, is the dogwood temporal
+dialect (epic #1646) — see [The dogwood dialect](#the-dogwood-dialect-pre-release).
+It is a surface *inside* this lexicon rather than a sibling, so the eight
+sub-issues above are still the whole of Cedar itself.
+
## The policy model
A policy is a `Cedar::Policy` entity whose props are:
@@ -159,6 +164,57 @@ policy. AVP policy stores are taggable and individual policies are not, so
chant's per-policy ownership marker rides in the policy description — the
design record is `src/avp/OWNERSHIP.md`.
+## The dogwood dialect (pre-release)
+
+[Dogwood](https://github.com/dogwood-policy/dogwood) is Cedar with temporal
+operators: a policy can depend on what already happened in a session, so
+approval-before-action, rate limits and budgets become policy rather than
+application code. It ships here as a dialect rather than as a sibling lexicon —
+a `.dw` file stripped of Cedar semantics is meaningless, and the head of a
+`.dw` policy is Cedar's, byte for byte. Its checks are under the `DWD` id
+family, declared on the serializer's `extraRulePrefixes`.
+
+```ts
+import { TemporalPolicy, TemporalEventSchema, dogwood } from "@intentius/chant-lexicon-cedar";
+
+export const events = new TemporalEventSchema({ schema: dogwood.defaultEventSchema() });
+
+export const readAfterLogin = new TemporalPolicy({
+ action: { eq: 'Drupe::Action::"Read"' },
+ whenTemporal: [
+ dogwood.formerly("1h", dogwood.predicate('Drupe::Action::"Login"', "response", {
+ "input.user": dogwood.ctx("input.user"),
+ })),
+ ],
+});
+```
+
+A build holding temporal policies emits `policies.dw` beside the `.cedar`
+outputs, plus `events.dwschema` and `macros.dw` where those are declared.
+
+The builders target dogwood's **parser primitives** — `formerly`, `previous`,
+`since`, `exists`, `tp()`, `count for … where`, `sum … for … where` — because
+those are the only temporal keywords in the grammar. `count_within`,
+`sum_within` and `count_distinct_within` are macros in a default library that
+a caller passing `--macros` replaces wholesale, so they are expressible as
+calls (`dogwood.countWithin`) and never as operators. `dogwood.defaultMacroLibrary()`
+emits the same definitions into a project's own file for anyone who would
+rather not depend on the far end's.
+
+Three walls run in the build with no dogwood binary anywhere: a temporal
+predicate naming an event kind the emitted `.dwschema` never declares
+(DWDC010), a window past the schema's `max_window` or upstream's 24h default
+(DWDC011), and a `formerly`/`previous`/`since` with no window (DWDC012, which
+the typed builders already make unrepresentable). DWDS010 reports an event
+schema that pins nothing — supplying any schema opts out of upstream's
+`callerPrincipal` pin, which widens every temporal predicate to cross-principal.
+
+Pre-release. Upstream is a read-only squash-sync mirror of an internal Amazon
+repository with no tags, no releases and no stability statement, and its README
+says it is not intended for production use. The revision this is built against
+is recorded in `src/dogwood/upstream.ts`; full `.dw` validation shells to the
+`dogwood` binary and is deliberately not part of any gating check.
+
## Commands
```bash
@@ -175,7 +231,9 @@ npm run docs:build # build the Starlight site in docs/
- `src/plugin.ts` — LexiconPlugin with all lifecycle methods
- `src/serializer.ts` — `.cedar` text and JSON policy-set output
+- `src/policy-text.ts` — policy-head rendering shared by every renderer
- `src/avp/` — AVP embedding, the policy-store readers, and the ownership channel
+- `src/dogwood/` — the temporal dialect: builders, `.dw`/`.dwschema` output
- `src/import/` — `chant import` parser, generator and round-trip fixtures
- `src/detect.ts` — which documents belong to this lexicon
- `src/codegen/` — code generation, docs, and packaging pipelines
diff --git a/lexicons/cedar/src/dogwood/event-schema.test.ts b/lexicons/cedar/src/dogwood/event-schema.test.ts
new file mode 100644
index 0000000000..1a3e99d581
--- /dev/null
+++ b/lexicons/cedar/src/dogwood/event-schema.test.ts
@@ -0,0 +1,218 @@
+/**
+ * Event-schema round trip: typed authoring in, `.dwschema` text out, asserted
+ * against fixtures whose shapes are upstream's.
+ *
+ * The fixtures under `./testdata/` are adapted from
+ * `dogwood-policy/dogwood`'s shipped examples and its bundled default schema
+ * (Apache-2.0; each file carries its provenance in a header comment). They are
+ * not byte copies — upstream aligns field types in columns and chant does not
+ * — so what is pinned here is the surface: the directive, the declarations,
+ * the spreads, the selectors, and where the pins land.
+ */
+import { describe, test, expect } from "vitest";
+import { readFileSync } from "fs";
+import { join } from "path";
+import { fileURLToPath } from "url";
+import {
+ concrete,
+ declaredEventKinds,
+ defaultEventSchema,
+ eventDeclaration,
+ eventSchema,
+ field,
+ pinContext,
+ pinPrincipal,
+ pinnedField,
+ principalType,
+ record,
+ renderEventSchema,
+ resourceType,
+ spreadInputs,
+ spreadOutputs,
+} from "./event-schema";
+import { readEventSchema } from "./scan";
+
+const TESTDATA = join(fileURLToPath(new URL(".", import.meta.url)), "testdata");
+const UPSTREAM = "dogwood-policy/dogwood@5063bcc2d6d6cf5024d1b0498e6cc8ef52cbcf0c";
+
+function fixture(name: string): string {
+ return readFileSync(join(TESTDATA, name), "utf-8");
+}
+
+/** The provenance header each fixture carries above the emitted bytes. */
+function attribution(...sources: string[]): string {
+ return [
+ `// Adapted from ${UPSTREAM} (Apache-2.0):`,
+ ...sources.map((s) => `// ${s}`),
+ "// Upstream's shape; the bytes are what chant's typed builders emit.",
+ "",
+ "",
+ ].join("\n");
+}
+
+// ── The default shape ──────────────────────────────────────────────
+
+describe("the default (pinned) event schema", () => {
+ test("round-trips to upstream's pinned.dwschema shape", () => {
+ expect(fixture("pinned.dwschema")).toBe(
+ attribution("dogwood-language/configuration/event-schemas/pinned.dwschema") +
+ renderEventSchema(defaultEventSchema()),
+ );
+ });
+
+ test("every kind pins callerPrincipal to the deciding request's principal", () => {
+ const text = renderEventSchema(defaultEventSchema());
+ expect(text.match(/pin callerPrincipal: principalType\(A\) = principal,/g)).toHaveLength(3);
+ expect(readEventSchema(text).hasPin).toBe(true);
+ });
+
+ test("request is the deciding kind; response and error are history", () => {
+ const text = renderEventSchema(defaultEventSchema());
+ expect(text).toContain("decision event ::request {");
+ expect(text).toContain("\nevent ::response {");
+ expect(text).toContain("\nevent ::error {");
+ expect(declaredEventKinds(defaultEventSchema())).toEqual(["request", "response", "error"]);
+ });
+
+ test("dropping the pin is a named argument, and says so in the file", () => {
+ const text = renderEventSchema(defaultEventSchema({ pinCallerPrincipal: false }));
+ expect(text).not.toContain("pin callerPrincipal");
+ expect(text).toContain("// Cross-principal: callerPrincipal is NOT pinned");
+ expect(readEventSchema(text).hasPin).toBe(false);
+ });
+});
+
+// ── max_window ─────────────────────────────────────────────────────
+
+describe("the max_window directive", () => {
+ const raised = () =>
+ eventSchema(
+ [
+ eventDeclaration(
+ "request",
+ [
+ spreadInputs(),
+ field("callerPrincipal", principalType()),
+ field("callerResource", resourceType()),
+ field("requestId", concrete("String")),
+ ],
+ { decision: true },
+ ),
+ eventDeclaration("response", [
+ spreadInputs(),
+ spreadOutputs(),
+ field("callerPrincipal", principalType()),
+ field("callerResource", resourceType()),
+ field("requestId", concrete("String")),
+ ]),
+ ],
+ {
+ maxWindow: "30d",
+ comment:
+ "Raises the look-back cap from the 24h default to 30 days. The directive\nmust come first, before any event declaration.\n\nNo pinned field: this schema correlates across principals on purpose.",
+ },
+ );
+
+ test("round-trips to upstream's max_window_raised shape", () => {
+ expect(fixture("max-window-raised.dwschema")).toBe(
+ attribution("dogwood-docs/examples/max_window_raised/event.dwschema") + renderEventSchema(raised()),
+ );
+ });
+
+ test("the directive precedes every declaration, as the grammar requires", () => {
+ const lines = renderEventSchema(raised()).split("\n");
+ const directive = lines.findIndex((l) => l.startsWith("max_window"));
+ const firstEvent = lines.findIndex((l) => l.includes("event ::"));
+ expect(directive).toBeGreaterThan(-1);
+ expect(directive).toBeLessThan(firstEvent);
+ });
+
+ test("the scanner reads the cap back out", () => {
+ const facts = readEventSchema(renderEventSchema(raised()));
+ expect(facts.maxWindowText).toBe("30d");
+ expect(facts.maxWindowSeconds).toBe(30 * 86400);
+ });
+
+ test("an absent directive reads back as upstream's 24h default", () => {
+ const facts = readEventSchema(renderEventSchema(defaultEventSchema()));
+ expect(facts.maxWindowText).toBeUndefined();
+ expect(facts.maxWindowSeconds).toBe(24 * 3600);
+ });
+});
+
+// ── Author-defined kinds ───────────────────────────────────────────
+
+describe("author-defined event kinds", () => {
+ const custom = () =>
+ eventSchema(
+ [
+ eventDeclaration("attempt", [spreadInputs(), field("actor", principalType())], { decision: true }),
+ eventDeclaration("outcome", [spreadInputs(), spreadOutputs(), field("actor", principalType())]),
+ ],
+ {
+ comment:
+ "Author-defined event kinds — `attempt` decides, `outcome` is history — and\na renamed injected principal field.",
+ },
+ );
+
+ test("round-trips to upstream's login_attempt_custom_kind shape", () => {
+ expect(fixture("custom-kinds.dwschema")).toBe(
+ attribution("dogwood-docs/examples/login_attempt_custom_kind/event.dwschema") + renderEventSchema(custom()),
+ );
+ });
+
+ test("request/response are conventional, not required", () => {
+ expect(declaredEventKinds(custom())).toEqual(["attempt", "outcome"]);
+ expect(readEventSchema(renderEventSchema(custom())).kinds).toEqual(["attempt", "outcome"]);
+ });
+});
+
+// ── Field forms ────────────────────────────────────────────────────
+
+describe("field forms", () => {
+ test("a record type nests, and its members are addressed as name.member", () => {
+ const text = renderEventSchema(
+ eventSchema([
+ eventDeclaration("request", [
+ spreadInputs(),
+ field("session", record([field("id", concrete("String")), field("tenant", concrete("String"))])),
+ ]),
+ ]),
+ );
+ expect(text).toContain(" session: {\n id: String,\n tenant: String,\n },");
+ });
+
+ test("a context pin renders its dotted path", () => {
+ const text = renderEventSchema(
+ eventSchema([
+ eventDeclaration("request", [pinnedField("tenant", concrete("String"), pinContext("input.tenant"))]),
+ ]),
+ );
+ expect(text).toContain(" pin tenant: String = context.input.tenant,");
+ });
+
+ test("a scope pin may carry an attribute tail", () => {
+ const text = renderEventSchema(
+ eventSchema([
+ eventDeclaration("request", [pinnedField("dept", concrete("String"), pinPrincipal("dept"))]),
+ ]),
+ );
+ expect(text).toContain(" pin dept: String = principal.dept,");
+ });
+
+ test("pinning a whole record is refused — upstream requires a leaf", () => {
+ expect(() => pinnedField("group", record([field("a", concrete("String"))]), pinPrincipal())).toThrow(
+ /must be a leaf/,
+ );
+ });
+
+ test("a duplicated event kind is refused at construction", () => {
+ expect(() =>
+ eventSchema([eventDeclaration("request", []), eventDeclaration("request", [])]),
+ ).toThrow(/declared twice/);
+ });
+
+ test("a schema with no declarations is refused", () => {
+ expect(() => eventSchema([])).toThrow(/at least one event kind/);
+ });
+});
diff --git a/lexicons/cedar/src/dogwood/event-schema.ts b/lexicons/cedar/src/dogwood/event-schema.ts
new file mode 100644
index 0000000000..834b99ffc9
--- /dev/null
+++ b/lexicons/cedar/src/dogwood/event-schema.ts
@@ -0,0 +1,318 @@
+/**
+ * Typed authoring for the `.dwschema` event-schema DSL.
+ *
+ * The `.dwschema`/`.cedarschema` question the epic flagged was a false alarm
+ * (#1657 §2): they are the two halves of one schema. The required half is the
+ * Cedar action schema (`--policy-schema`); this file is the optional half, the
+ * service side, which says what event *kinds* exist and what fields each one
+ * carries. Upstream's grammar is 136 lines of pest and is purely syntactic —
+ * it never consults an action schema, which is why every declaration is
+ * written against a symbolic action binder ``:
+ *
+ * ```
+ * decision event ::request {
+ * ...inputs(A),
+ * pin callerPrincipal: principalType(A) = principal,
+ * callerResource: resourceType(A),
+ * requestId: String,
+ * }
+ * ```
+ *
+ * That symbolic binder is why DWDC010 can check an event *kind* against the
+ * emitted schema but not an action: the schema names no actions at all.
+ *
+ * ## The pin, and why opting out is explicit here
+ *
+ * `ServiceSchema::defaults()` — what runs when no `--event-schema` is passed —
+ * pins `callerPrincipal = principal` on every kind, so every temporal
+ * predicate is correlated to the current request's principal and events from
+ * other principals are invisible. Supplying *any* event schema opts out of the
+ * default wholesale, so a schema emitted without that pin silently widens
+ * every temporal predicate in the policy set to cross-principal.
+ *
+ * {@link defaultEventSchema} therefore carries the pin, and dropping it takes
+ * a named argument (`pinCallerPrincipal: false`) that also stamps a comment
+ * into the emitted file. DWDS010 reports the resulting schema either way, so
+ * the choice is visible in the build and not only in the source.
+ */
+
+import { renderWindow, window, type TemporalWindow, type WindowLike } from "./window";
+
+const IDENT = /^[A-Za-z_][A-Za-z0-9_]*$/;
+const TYPE_NAME = /^[A-Za-z_][A-Za-z0-9_]*(::[A-Za-z_][A-Za-z0-9_]*)*$/;
+
+function assertIdent(value: string, what: string): string {
+ if (!IDENT.test(value)) throw new Error(`dogwood: ${what} must be an identifier — got "${value}"`);
+ return value;
+}
+
+// ── Field types ───────────────────────────────────────────────────
+
+/** The four selectors that read from the bound action. */
+export type EventSelector = "inputs" | "outputs" | "principalType" | "resourceType";
+
+/** `principalType(A)`, a nested `{ … }` record, or a concrete Cedar type. */
+export type EventFieldType =
+ | { readonly type: "selector"; readonly selector: EventSelector }
+ | { readonly type: "record"; readonly fields: readonly EventField[] }
+ | { readonly type: "concrete"; readonly name: string };
+
+/** `principalType(A)` — the action's principal entity type. */
+export function principalType(): EventFieldType {
+ return { type: "selector", selector: "principalType" };
+}
+
+/** `resourceType(A)` — the action's resource entity type. */
+export function resourceType(): EventFieldType {
+ return { type: "selector", selector: "resourceType" };
+}
+
+/** `String`, `Long`, `MyApp::OAuthUser` — a concrete (possibly qualified) type. */
+export function concrete(name: string): EventFieldType {
+ if (!TYPE_NAME.test(name)) throw new Error(`dogwood: a field type must be a Cedar type name — got "${name}"`);
+ return { type: "concrete", name };
+}
+
+/** `{ … }` — the named field becomes a group addressed as `name.member`. */
+export function record(fields: EventField[]): EventFieldType {
+ return { type: "record", fields };
+}
+
+// ── Pins ──────────────────────────────────────────────────────────
+
+/**
+ * The right-hand side of a pin: the request-side value the field is forced to
+ * match. `principal`/`resource` (with an optional attribute tail) or a
+ * `context.`.
+ */
+export type PinTarget =
+ | { readonly ref: "principal" | "resource"; readonly attrs: readonly string[] }
+ | { readonly ref: "context"; readonly path: readonly string[] };
+
+/** `= principal`, or `= principal.dept`. */
+export function pinPrincipal(...attrs: string[]): PinTarget {
+ for (const a of attrs) assertIdent(a, "a pin attribute");
+ return { ref: "principal", attrs };
+}
+
+/** `= resource`, or `= resource.owner`. */
+export function pinResource(...attrs: string[]): PinTarget {
+ for (const a of attrs) assertIdent(a, "a pin attribute");
+ return { ref: "resource", attrs };
+}
+
+/** `= context.input.user`. At least one path segment; `context` alone is not a pin. */
+export function pinContext(path: string): PinTarget {
+ const segments = path.split(".");
+ if (segments.length === 0 || segments[0] === "") {
+ throw new Error("dogwood: a context pin needs at least one path segment (context.)");
+ }
+ for (const s of segments) assertIdent(s, "a context pin segment");
+ return { ref: "context", path: segments };
+}
+
+// ── Fields ────────────────────────────────────────────────────────
+
+/** `...inputs(A)` / `...outputs(A)` — splice every field the selector yields. */
+export interface SpreadField {
+ readonly field: "spread";
+ readonly selector: Extract;
+}
+
+/** `[pin] name: [= ]`. */
+export interface NamedField {
+ readonly field: "named";
+ readonly name: string;
+ readonly type: EventFieldType;
+ readonly pin?: PinTarget;
+}
+
+/** One entry in an event declaration's field list. */
+export type EventField = SpreadField | NamedField;
+
+/** `...inputs(A)`. */
+export function spreadInputs(): SpreadField {
+ return { field: "spread", selector: "inputs" };
+}
+
+/** `...outputs(A)`. */
+export function spreadOutputs(): SpreadField {
+ return { field: "spread", selector: "outputs" };
+}
+
+/** `name: ` — an injected field with an explicit type. */
+export function field(name: string, type: EventFieldType): NamedField {
+ return { field: "named", name: assertIdent(name, "a field name"), type };
+}
+
+/**
+ * `pin name: = ` — a correlation against the decision request.
+ *
+ * Upstream requires the `pin` prefix and the `= …` clause together, and a
+ * pinned field must be a leaf (never a record type), so both are enforced here
+ * rather than deferred to the parser.
+ */
+export function pinnedField(name: string, type: EventFieldType, target: PinTarget): NamedField {
+ if (type.type === "record") {
+ throw new Error(`dogwood: a pinned field must be a leaf, and "${name}" is a record type`);
+ }
+ return { field: "named", name: assertIdent(name, "a field name"), type, pin: target };
+}
+
+// ── Declarations ──────────────────────────────────────────────────
+
+/** `[decision] event ::kind { fields }`. */
+export interface EventDeclaration {
+ /** `request`, `response`, `error`, or anything the author chooses. */
+ readonly kind: string;
+ /** True for the kind that carries the authorization decision. */
+ readonly decision?: boolean;
+ readonly fields: readonly EventField[];
+ /** Emitted as `// …` above the declaration. */
+ readonly comment?: string;
+}
+
+/** One `event` declaration. */
+export function eventDeclaration(
+ kind: string,
+ fields: EventField[],
+ options: { decision?: boolean; comment?: string } = {},
+): EventDeclaration {
+ return { kind: assertIdent(kind, "an event kind"), fields, decision: options.decision, comment: options.comment };
+}
+
+/** A whole `.dwschema` file. */
+export interface EventSchema {
+ /** `max_window = 30d`. Omitted means upstream's 24h default applies. */
+ readonly maxWindow?: TemporalWindow;
+ /** The action binder name, `A` by convention. */
+ readonly binder: string;
+ readonly events: readonly EventDeclaration[];
+ /** Header comment lines, emitted above everything. */
+ readonly comment?: string;
+}
+
+/** Assemble a schema, defaulting the action binder to `A`. */
+export function eventSchema(
+ events: EventDeclaration[],
+ options: { maxWindow?: WindowLike; binder?: string; comment?: string } = {},
+): EventSchema {
+ if (events.length === 0) throw new Error("dogwood: an event schema declares at least one event kind");
+ const kinds = new Set();
+ for (const e of events) {
+ if (kinds.has(e.kind)) throw new Error(`dogwood: event kind "${e.kind}" is declared twice`);
+ kinds.add(e.kind);
+ }
+ return {
+ maxWindow: options.maxWindow === undefined ? undefined : window(options.maxWindow),
+ binder: assertIdent(options.binder ?? "A", "an action binder"),
+ events,
+ comment: options.comment,
+ };
+}
+
+/**
+ * The default event-schema shape: `request` (deciding), `response` and `error`,
+ * each pinned to the request's principal.
+ *
+ * This reproduces `configuration/event-schemas/pinned.dwschema`, which is what
+ * `ServiceSchema::defaults()` uses. Emitting it explicitly is the honest thing
+ * to do the moment a project supplies *any* event schema, because supplying
+ * one opts out of the built-in default entirely.
+ *
+ * @param options.pinCallerPrincipal Drop the pin to allow cross-principal
+ * correlation. A deliberate choice: it widens every temporal predicate in the
+ * policy set, so it stamps a comment into the emitted file and DWDS010 reports
+ * it in the build.
+ */
+export function defaultEventSchema(
+ options: {
+ maxWindow?: WindowLike;
+ pinCallerPrincipal?: boolean;
+ principalField?: string;
+ binder?: string;
+ } = {},
+): EventSchema {
+ const pinned = options.pinCallerPrincipal !== false;
+ const principalField = options.principalField ?? "callerPrincipal";
+
+ const common = (): EventField[] => [
+ pinned
+ ? pinnedField(principalField, principalType(), pinPrincipal())
+ : field(principalField, principalType()),
+ field("callerResource", resourceType()),
+ field("requestId", concrete("String")),
+ field("sessionId", concrete("String")),
+ ];
+
+ return eventSchema(
+ [
+ eventDeclaration("request", [spreadInputs(), ...common()], { decision: true }),
+ eventDeclaration("response", [spreadInputs(), spreadOutputs(), ...common()]),
+ eventDeclaration("error", [spreadInputs(), ...common()]),
+ ],
+ {
+ maxWindow: options.maxWindow,
+ binder: options.binder,
+ comment: pinned
+ ? "The default event-schema shape: request/response/error, each correlated to\nthe deciding request's principal."
+ : `Cross-principal: ${principalField} is NOT pinned, so temporal predicates see\nevents from every principal, not only the deciding request's. This widens\nevery predicate in the policy set and is a deliberate departure from\nupstream's default (see ServiceSchema::defaults).`,
+ },
+ );
+}
+
+// ── Rendering ─────────────────────────────────────────────────────
+
+function renderPinTarget(target: PinTarget): string {
+ return target.ref === "context" ? `context.${target.path.join(".")}` : [target.ref, ...target.attrs].join(".");
+}
+
+function renderFieldType(type: EventFieldType, binder: string, indent: string): string {
+ switch (type.type) {
+ case "selector":
+ return `${type.selector}(${binder})`;
+ case "concrete":
+ return type.name;
+ case "record":
+ return `{\n${renderFields(type.fields, binder, indent + " ")}\n${indent}}`;
+ }
+}
+
+function renderFields(fields: readonly EventField[], binder: string, indent: string): string {
+ return fields
+ .map((f) => {
+ if (f.field === "spread") return `${indent}...${f.selector}(${binder}),`;
+ const pin = f.pin ? ` = ${renderPinTarget(f.pin)}` : "";
+ return `${indent}${f.pin ? "pin " : ""}${f.name}: ${renderFieldType(f.type, binder, indent)}${pin},`;
+ })
+ .join("\n");
+}
+
+function renderComment(comment: string): string[] {
+ return comment.split("\n").map((line) => `// ${line}`.trimEnd());
+}
+
+/** Render a schema to `.dwschema` text. */
+export function renderEventSchema(schema: EventSchema): string {
+ const lines: string[] = [];
+ if (schema.comment) lines.push(...renderComment(schema.comment), "");
+
+ if (schema.maxWindow) {
+ lines.push(`max_window = ${renderWindow(schema.maxWindow)}`, "");
+ }
+
+ for (const [index, event] of schema.events.entries()) {
+ if (index > 0) lines.push("");
+ if (event.comment) lines.push(...renderComment(event.comment));
+ lines.push(`${event.decision ? "decision " : ""}event <${schema.binder}>::${event.kind} {`);
+ if (event.fields.length > 0) lines.push(renderFields(event.fields, schema.binder, " "));
+ lines.push("}");
+ }
+
+ return lines.join("\n") + "\n";
+}
+
+/** Every event kind a schema declares, in declaration order. */
+export function declaredEventKinds(schema: EventSchema): string[] {
+ return schema.events.map((e) => e.kind);
+}
diff --git a/lexicons/cedar/src/dogwood/index.ts b/lexicons/cedar/src/dogwood/index.ts
new file mode 100644
index 0000000000..8e8658b2c6
--- /dev/null
+++ b/lexicons/cedar/src/dogwood/index.ts
@@ -0,0 +1,170 @@
+/**
+ * The dogwood temporal dialect (#1658, epic #1646).
+ *
+ * A dialect of the cedar lexicon, not a lexicon of its own: `.dw` policies are
+ * Cedar policies with temporal clauses, their entity and action schemas are
+ * Cedar schemas, and the rendering is shared with the `.cedar` leg. Checks
+ * ship under the `DWD` id family, declared on the cedar serializer's
+ * `extraRulePrefixes`.
+ *
+ * Pre-release. Upstream (dogwood-policy/dogwood, Apache-2.0) is a read-only
+ * squash-sync mirror with no tags, no releases and no stability statement, and
+ * calls itself "NOT intended for production use". The surface here is built
+ * against the revision recorded in `./upstream.ts` and re-verified per
+ * sub-issue.
+ */
+
+export {
+ DEFAULT_MAX_WINDOW,
+ isWindowParam,
+ renderWindow,
+ renderWindowValue,
+ window,
+ windowParam,
+ windowSeconds,
+ windowValue,
+} from "./window";
+export type { TemporalWindow, TimeUnit, WindowLike, WindowParam, WindowValue } from "./window";
+
+export {
+ and,
+ arrayOf,
+ binderName,
+ bool,
+ call,
+ compare,
+ count,
+ ctx,
+ decimalOf,
+ entityUid,
+ exists,
+ formerly,
+ int,
+ interval,
+ not,
+ predicate,
+ previous,
+ raw,
+ renderCondition,
+ renderTerm,
+ scopeRef,
+ sigilCondition,
+ since,
+ str,
+ sum,
+ temporalMarker,
+ term,
+ tp,
+ typedBinder,
+ varRef,
+ wildcard,
+} from "./temporal";
+export type {
+ AndNode,
+ ArrayTerm,
+ CallNode,
+ ComparisonNode,
+ ComparisonOperator,
+ CountTerm,
+ ExistsNode,
+ FormerlyNode,
+ IntervalArg,
+ MacroArg,
+ NotNode,
+ PredicateNode,
+ PreviousNode,
+ RawCondition,
+ SigilCondition,
+ SinceNode,
+ SumTerm,
+ TemporalCondition,
+ TemporalTerm,
+ TermInput,
+ TermText,
+ TpNode,
+ TypedBinder,
+ WindowArgument,
+} from "./temporal";
+
+export {
+ DEFAULT_MACRO_NAMES,
+ bind,
+ countDistinctWithin,
+ countWithin,
+ defCedarMacro,
+ defTemporalMacro,
+ defaultMacroLibrary,
+ macroCondition,
+ macroTerm,
+ macroWindow,
+ renderMacroDefinition,
+ renderMacroLibrary,
+ sumWithin,
+} from "./macros";
+export type { MacroDefinition, MacroKind } from "./macros";
+
+export {
+ concrete,
+ declaredEventKinds,
+ defaultEventSchema,
+ eventDeclaration,
+ eventSchema,
+ field,
+ pinContext,
+ pinPrincipal,
+ pinResource,
+ pinnedField,
+ principalType,
+ record,
+ renderEventSchema,
+ resourceType,
+ spreadInputs,
+ spreadOutputs,
+} from "./event-schema";
+export type {
+ EventDeclaration,
+ EventField,
+ EventFieldType,
+ EventSchema,
+ EventSelector,
+ NamedField,
+ PinTarget,
+ SpreadField,
+} from "./event-schema";
+
+export {
+ DOGWOOD_EVENT_SCHEMA_FILENAME,
+ DOGWOOD_EVENT_SCHEMA_TYPE,
+ DOGWOOD_LEXICON,
+ DOGWOOD_MACRO_FILENAME,
+ DOGWOOD_MACRO_LIBRARY_TYPE,
+ DOGWOOD_POLICY_FILENAME,
+ DOGWOOD_POLICY_TYPE,
+ TemporalEventSchema,
+ TemporalMacroLibrary,
+ TemporalPolicy,
+} from "./policy";
+export type { EventSchemaProps, MacroLibraryProps, TemporalPolicyProps } from "./policy";
+
+export {
+ DOGWOOD_EVENT_SCHEMA_SUFFIX,
+ DOGWOOD_POLICY_SUFFIX,
+ renderTemporalPolicyText,
+ serializeDogwood,
+} from "./serialize";
+export type { DogwoodSerializeResult } from "./serialize";
+
+export {
+ blankComments,
+ dogwoodPolicyFiles,
+ dogwoodSchemaFiles,
+ effectiveMaxWindowSeconds,
+ readEventSchema,
+ scanPredicates,
+ scanWindowlessOperators,
+ scanWindows,
+ temporalRegions,
+} from "./scan";
+export type { DogwoodArtifact, EventSchemaFacts, TemporalPredicateRef, WindowRef } from "./scan";
+
+export { DOGWOOD_UPSTREAM } from "./upstream";
diff --git a/lexicons/cedar/src/dogwood/macros.test.ts b/lexicons/cedar/src/dogwood/macros.test.ts
new file mode 100644
index 0000000000..2b92ec486e
--- /dev/null
+++ b/lexicons/cedar/src/dogwood/macros.test.ts
@@ -0,0 +1,104 @@
+import { describe, test, expect } from "vitest";
+import {
+ DEFAULT_MACRO_NAMES,
+ bind,
+ defCedarMacro,
+ defTemporalMacro,
+ defaultMacroLibrary,
+ macroCondition,
+ macroTerm,
+ macroWindow,
+ renderMacroDefinition,
+ renderMacroLibrary,
+} from "./macros";
+import { and, count, formerly, renderCondition, tp, typedBinder } from "./temporal";
+
+describe("def-macro authoring", () => {
+ test("a temporal macro renders as upstream's def_decl", () => {
+ const def = defTemporalMacro("once", ["?w", "?s"], formerly(macroWindow("?w"), macroCondition("?s")));
+ expect(renderMacroDefinition(def)).toBe(
+ "def temporal once(?w, ?s) {\n formerly within ?w ?s\n};",
+ );
+ });
+
+ test("a temporal macro body may be a bare aggregation value", () => {
+ const def = defTemporalMacro(
+ "count_within",
+ ["?w", "?s"],
+ count(
+ [typedBinder("$t", "Timepoint")],
+ formerly(macroWindow("?w"), and(macroCondition("?s"), tp("$t"))),
+ ),
+ );
+ expect(renderMacroDefinition(def)).toContain("count for ($t: Timepoint). where formerly within ?w (?s && tp($t))");
+ });
+
+ test("a cedar macro keeps its body as Cedar expression text", () => {
+ const def = defCedarMacro("is_small", ["?n"], "?n < 100");
+ expect(renderMacroDefinition(def)).toBe("def cedar is_small(?n) {\n ?n < 100\n};");
+ });
+
+ test("a comment is emitted above the definition", () => {
+ const def = defCedarMacro("is_small", ["?n"], "?n < 100", "Under a hundred.\nNothing more.");
+ expect(renderMacroDefinition(def).split("\n").slice(0, 2)).toEqual([
+ "// Under a hundred.",
+ "// Nothing more.",
+ ]);
+ });
+
+ test("a parameter without the ? sigil is refused, and the message says which to write", () => {
+ expect(() => defCedarMacro("is_small", ["n"], "n < 100")).toThrow(/carries the "\?" sigil.*"\?n"/s);
+ });
+
+ test("a macro name that is not an identifier is refused", () => {
+ expect(() => defCedarMacro("is small", [], "true")).toThrow(/must be an identifier/);
+ });
+});
+
+describe("the two sigils", () => {
+ test("?p splices a call-site value; $t is a macro-introduced fresh binder", () => {
+ expect(renderCondition(macroCondition("?s"))).toBe("?s");
+ expect(macroTerm("$t").text).toBe("$t");
+ expect(macroTerm("?a").text).toBe("?a");
+ });
+
+ test("a $ sigil is not a window parameter — the expander resolves only ?p there", () => {
+ expect(() => macroWindow("$w")).toThrow(/carries the "\?" sigil/);
+ });
+
+ test("a bare identifier is not a sigil", () => {
+ expect(() => macroCondition("s")).toThrow(/carries the "\?" sigil/);
+ expect(() => macroTerm("a")).toThrow(/carries a "\?" or "\$" sigil/);
+ });
+});
+
+describe("the default library", () => {
+ test("names exactly what upstream's default_macros.dw ships", () => {
+ expect([...DEFAULT_MACRO_NAMES]).toEqual([
+ "count_within",
+ "sum_within",
+ "count_distinct_within",
+ "bind",
+ ]);
+ expect(defaultMacroLibrary().map((d) => d.name)).toEqual([...DEFAULT_MACRO_NAMES]);
+ });
+
+ test("every definition is a temporal macro whose params all carry the sigil", () => {
+ for (const def of defaultMacroLibrary()) {
+ expect(def.kind).toBe("temporal");
+ for (const param of def.params) expect(param.startsWith("?")).toBe(true);
+ }
+ });
+
+ test("bind() is a call, so a policy using it depends on the callee's --macros", () => {
+ const node = bind("n", macroCondition("?A"), macroCondition("?B"));
+ expect(node.op).toBe("call");
+ expect(renderCondition(node)).toBe("bind(n, ?A, ?B)");
+ });
+
+ test("the library renders as a file a --macros flag can point at", () => {
+ const text = renderMacroLibrary(defaultMacroLibrary());
+ expect(text.endsWith("};\n")).toBe(true);
+ expect(text.split("\n\n")).toHaveLength(4);
+ });
+});
diff --git a/lexicons/cedar/src/dogwood/macros.ts b/lexicons/cedar/src/dogwood/macros.ts
new file mode 100644
index 0000000000..feaac7b8ba
--- /dev/null
+++ b/lexicons/cedar/src/dogwood/macros.ts
@@ -0,0 +1,229 @@
+/**
+ * Macro authoring, and the default library as calls rather than operators.
+ *
+ * Upstream's policy grammar carries the macro system in the parser, not in the
+ * docs:
+ *
+ * ```
+ * def_decl = { kw_def ~ def_kind ~ ident ~ "(" ~ param_list? ~ ")" ~ "{" ~ block_inner ~ "}" ~ ";" }
+ * def_kind = { kw_def_cedar | kw_def_temporal }
+ * ```
+ *
+ * A `cedar` macro's body is a Cedar expression; a `temporal` macro's body is a
+ * temporal condition *or* a bare aggregation value (upstream's
+ * `temporal_macro_body_entry` tries `agg_expr` first, which is why
+ * `count_within` can expand into a `count …` that the call site compares).
+ *
+ * Two sigils, and they are not interchangeable. `?p` splices the call-site
+ * argument literally. `$t` is a fresh binder the macro introduces, gensym'd at
+ * every expansion. Both are legal *only* inside a macro body — upstream's
+ * well-formedness pass rejects them anywhere else — which is why they are
+ * validated here at definition time rather than at render time.
+ *
+ * The four wrappers at the bottom are the default library
+ * (`configuration/default_macros.dw`). They are calls, not operators. A caller
+ * who passes `--macros` replaces that library entirely, so a policy built on
+ * them is built on an assumption about the other end; {@link defaultMacroLibrary}
+ * exists so a project can emit the same definitions itself and stop assuming.
+ */
+
+import {
+ call,
+ interval,
+ renderCondition,
+ renderTerm,
+ sigilCondition,
+ varRef,
+ type CallNode,
+ type SigilCondition,
+ type TemporalCondition,
+ type TemporalTerm,
+ type TermText,
+} from "./temporal";
+import { windowParam, type WindowLike, type WindowParam } from "./window";
+
+/** `?w` — a value parameter, spliced from the call site. */
+const PARAM = /^\?[A-Za-z_][A-Za-z0-9_]*$/;
+const IDENT = /^[A-Za-z_][A-Za-z0-9_]*$/;
+
+/** Which sub-parser reads the body: Cedar's, or the temporal sub-language's. */
+export type MacroKind = "cedar" | "temporal";
+
+/** One `def () { };` declaration. */
+export interface MacroDefinition {
+ readonly kind: MacroKind;
+ readonly name: string;
+ /** Parameter names, each carrying the `?` sigil. */
+ readonly params: readonly string[];
+ /** Rendered body text. */
+ readonly body: string;
+ /** Emitted as `// …` lines above the definition. */
+ readonly comment?: string;
+}
+
+function assertMacroName(name: string): string {
+ if (!IDENT.test(name)) throw new Error(`dogwood: a macro name must be an identifier — got "${name}"`);
+ return name;
+}
+
+function assertParams(params: readonly string[]): readonly string[] {
+ for (const p of params) {
+ if (!PARAM.test(p)) {
+ throw new Error(`dogwood: a macro parameter carries the "?" sigil — got "${p}" (write "?${p.replace(/^\?/, "")}")`);
+ }
+ }
+ return params;
+}
+
+/**
+ * `def temporal name(?a, ?b) { … };`
+ *
+ * The body may be a condition or an aggregation term, matching upstream's
+ * `temporal_macro_body_entry`; `sum_within` is an aggregation-bodied macro and
+ * `once` is a condition-bodied one.
+ */
+export function defTemporalMacro(
+ name: string,
+ params: string[],
+ body: TemporalCondition | TemporalTerm,
+ comment?: string,
+): MacroDefinition {
+ return {
+ kind: "temporal",
+ name: assertMacroName(name),
+ params: assertParams(params),
+ body: isTermBody(body) ? renderTerm(body) : renderCondition(body),
+ comment,
+ };
+}
+
+function isTermBody(body: TemporalCondition | TemporalTerm): body is TemporalTerm {
+ return body.op === "term" || body.op === "array" || body.op === "count" || body.op === "sum";
+}
+
+/**
+ * `def cedar name(?a) { … };` — the body is Cedar expression text.
+ *
+ * Cedar's expression grammar is the policy language itself, so it stays a
+ * string here for the same reason `Cedar::Policy`'s `when` does.
+ */
+export function defCedarMacro(
+ name: string,
+ params: string[],
+ body: string,
+ comment?: string,
+): MacroDefinition {
+ return { kind: "cedar", name: assertMacroName(name), params: assertParams(params), body, comment };
+}
+
+// ── The sigils, in the three positions they appear ────────────────
+
+/**
+ * `within ?w` — the window a macro body defers to its call site.
+ *
+ * The call site supplies a bare interval (`once(1h, …)`), not a `within`
+ * clause: the keyword belongs to the operator, so it stays in the body.
+ */
+export function macroWindow(param: string): WindowParam {
+ return windowParam(param);
+}
+
+/** `?s` standing for an entire condition, spliced from the call site. */
+export function macroCondition(param: string): SigilCondition {
+ if (!PARAM.test(param)) throw new Error(`dogwood: a condition parameter carries the "?" sigil — got "${param}"`);
+ return sigilCondition(param);
+}
+
+/** `?a` / `$t` in term or binder position. */
+export function macroTerm(sigil: string): TermText {
+ if (!/^[?$][A-Za-z_][A-Za-z0-9_]*$/.test(sigil)) {
+ throw new Error(`dogwood: a macro term carries a "?" or "$" sigil — got "${sigil}"`);
+ }
+ return varRef(sigil);
+}
+
+/** One definition as `.dw` source. */
+export function renderMacroDefinition(def: MacroDefinition): string {
+ const lines: string[] = [];
+ if (def.comment) {
+ for (const line of def.comment.split("\n")) lines.push(`// ${line}`.trimEnd());
+ }
+ lines.push(`def ${def.kind} ${def.name}(${def.params.join(", ")}) {`);
+ lines.push(` ${def.body}`);
+ lines.push("};");
+ return lines.join("\n");
+}
+
+/** A whole library — the file `--macros` points at, or a policy set's own prelude. */
+export function renderMacroLibrary(defs: readonly MacroDefinition[]): string {
+ return defs.map(renderMacroDefinition).join("\n\n") + "\n";
+}
+
+// ── The default library, as calls ─────────────────────────────────
+
+/** The macro names `configuration/default_macros.dw` ships at the pinned revision. */
+export const DEFAULT_MACRO_NAMES = ["count_within", "sum_within", "count_distinct_within", "bind"] as const;
+
+/**
+ * `count_within(?w, ?s)` — timepoints in the window at which `?s` held.
+ *
+ * A default-library call, not an operator. See this module's header.
+ */
+export function countWithin(w: WindowLike, condition: TemporalCondition): CallNode {
+ return call("count_within", [interval(w), condition]);
+}
+
+/** `sum_within(?a, ?w, ?body)` — `over` names the sum's bound variable. */
+export function sumWithin(over: string, w: WindowLike, body: TemporalCondition): CallNode {
+ return call("sum_within", [varRef(over), interval(w), body]);
+}
+
+/** `count_distinct_within(?k, ?w, ?s)` — distinct String keys `k` for which `s` held. */
+export function countDistinctWithin(key: string, w: WindowLike, condition: TemporalCondition): CallNode {
+ return call("count_distinct_within", [varRef(key), interval(w), condition]);
+}
+
+/** `bind(?n, ?A, ?B)` — names an aggregate result so it can be compared. */
+export function bind(name: string, aggregate: TemporalCondition, body: TemporalCondition): CallNode {
+ return call("bind", [varRef(name), aggregate, body]);
+}
+
+/**
+ * The default library's four definitions, verbatim from upstream's
+ * `dogwood-language/configuration/default_macros.dw` at the pinned revision.
+ *
+ * Emitting these into a project's own `macros.dw` turns an assumption about
+ * the callee's `--macros` into a file the project controls.
+ */
+export function defaultMacroLibrary(): MacroDefinition[] {
+ return [
+ {
+ kind: "temporal",
+ name: "count_within",
+ params: ["?w", "?s"],
+ body: "count for ($t: Timepoint). where (formerly within ?w (?s && tp($t)))",
+ comment: "Counts the timepoints within window `?w` at which condition `?s` held.",
+ },
+ {
+ kind: "temporal",
+ name: "sum_within",
+ params: ["?a", "?w", "?body"],
+ body: "sum ?a for (?a: Long), ($t: Timepoint). where (formerly within ?w (?body && tp($t)))",
+ comment: "Sums the numeric value `?a` over occurrences of `?body` within window `?w`.",
+ },
+ {
+ kind: "temporal",
+ name: "count_distinct_within",
+ params: ["?k", "?w", "?s"],
+ body: "count for (?k: String). where (formerly within ?w ?s)",
+ comment: "Counts the distinct key values `?k` for which `?s` held within window `?w`.",
+ },
+ {
+ kind: "temporal",
+ name: "bind",
+ params: ["?n", "?A", "?B"],
+ body: "exists (?n: Long). (?A == ?n && ?B)",
+ comment: 'A "let"-style binder: names an aggregate result `?n` and uses it in `?B`.',
+ },
+ ];
+}
diff --git a/lexicons/cedar/src/dogwood/policy.test.ts b/lexicons/cedar/src/dogwood/policy.test.ts
new file mode 100644
index 0000000000..e4fbdb2816
--- /dev/null
+++ b/lexicons/cedar/src/dogwood/policy.test.ts
@@ -0,0 +1,94 @@
+/**
+ * The entity classes, driven the way a policy file drives them.
+ *
+ * The golden serializer test builds its entities by hand so the rendering is
+ * pinned independently of the runtime factory. This one closes the other half:
+ * that `new TemporalPolicy({ … })` produces a Declarable the cedar serializer
+ * recognises, with the props it was given.
+ */
+import { describe, test, expect } from "vitest";
+import type { Declarable } from "@intentius/chant/declarable";
+import { cedarSerializer } from "../serializer";
+import {
+ DOGWOOD_EVENT_SCHEMA_FILENAME,
+ DOGWOOD_EVENT_SCHEMA_TYPE,
+ DOGWOOD_LEXICON,
+ DOGWOOD_MACRO_FILENAME,
+ DOGWOOD_POLICY_FILENAME,
+ DOGWOOD_POLICY_TYPE,
+ TemporalEventSchema,
+ TemporalMacroLibrary,
+ TemporalPolicy,
+} from "./policy";
+import { ctx, formerly, predicate } from "./temporal";
+import { defaultEventSchema } from "./event-schema";
+import { defaultMacroLibrary } from "./macros";
+
+function files(entities: Map): Record {
+ const out = cedarSerializer.serialize(entities);
+ return typeof out === "string" ? {} : (out.files ?? {});
+}
+
+describe("the dogwood entity classes", () => {
+ test("a TemporalPolicy is a cedar-lexicon Declarable of its own entity type", () => {
+ const policy = new TemporalPolicy({ whenTemporal: [] });
+ expect(policy.entityType).toBe(DOGWOOD_POLICY_TYPE);
+ expect(policy.lexicon).toBe(DOGWOOD_LEXICON);
+ expect(policy.kind).toBe("resource");
+ });
+
+ test("the dialect's entity types are namespaced apart from Cedar::Policy", () => {
+ expect(DOGWOOD_POLICY_TYPE).toBe("Dogwood::TemporalPolicy");
+ expect(DOGWOOD_EVENT_SCHEMA_TYPE).toBe("Dogwood::EventSchema");
+ });
+
+ test("a declared policy reaches the .dw output through the serializer", () => {
+ const entities = new Map([
+ [
+ "readAfterLogin",
+ new TemporalPolicy({
+ action: { eq: 'Drupe::Action::"Read"' },
+ principal: { is: "Drupe::OAuthUser" },
+ annotations: { owner: "platform" },
+ whenTemporal: [
+ formerly("1h", predicate('Drupe::Action::"Login"', "response", { "input.user": ctx("input.user") })),
+ ],
+ }),
+ ],
+ ]);
+
+ const text = files(entities)[DOGWOOD_POLICY_FILENAME];
+ expect(text).toContain('@id("read-after-login")');
+ expect(text).toContain('@owner("platform")');
+ expect(text).toContain(" principal is Drupe::OAuthUser,");
+ expect(text).toContain(' action == Drupe::Action::"Read",');
+ expect(text).toContain("formerly within 1h");
+ });
+
+ test("an event schema and a macro library each reach their own file", () => {
+ const entities = new Map([
+ ["events", new TemporalEventSchema({ schema: defaultEventSchema({ maxWindow: "12h" }) })],
+ ["macros", new TemporalMacroLibrary({ macros: defaultMacroLibrary() })],
+ ]);
+
+ const written = files(entities);
+ expect(written[DOGWOOD_EVENT_SCHEMA_FILENAME]).toContain("max_window = 12h");
+ expect(written[DOGWOOD_MACRO_FILENAME]).toContain("def temporal count_within(?w, ?s) {");
+ });
+
+ test("an inline macro library lands in the policy set, not a separate file", () => {
+ const entities = new Map([
+ ["macros", new TemporalMacroLibrary({ macros: defaultMacroLibrary(), inline: true })],
+ [
+ "p",
+ new TemporalPolicy({
+ whenTemporal: [formerly("1h", predicate('Ns::Action::"A"', "request"))],
+ }),
+ ],
+ ]);
+
+ const written = files(entities);
+ expect(written[DOGWOOD_MACRO_FILENAME]).toBeUndefined();
+ expect(written[DOGWOOD_POLICY_FILENAME]).toContain("def temporal count_within(?w, ?s) {");
+ });
+});
diff --git a/lexicons/cedar/src/dogwood/policy.ts b/lexicons/cedar/src/dogwood/policy.ts
new file mode 100644
index 0000000000..01ef2b4435
--- /dev/null
+++ b/lexicons/cedar/src/dogwood/policy.ts
@@ -0,0 +1,141 @@
+/**
+ * The dogwood entity model: a temporal policy, an event schema, a macro library.
+ *
+ * `Dogwood::TemporalPolicy` is `Cedar::Policy` plus the two clause forms
+ * upstream's policy grammar adds. Its head — annotations, effect, the three
+ * scope positions — is Cedar's, byte for byte, which is why `./serialize.ts`
+ * renders it with the cedar serializer's own `renderPolicyHead` rather than a
+ * copy of it. Only the `cond` rule differs:
+ *
+ * ```
+ * cond = { cond_kw ~ (extension_marker | guardrails_tag? ~ "{" ~ expr ~ "}") }
+ * ```
+ *
+ * — so a clause is `when { … }`, `when guardrails { … }`, or
+ * `when temporal { … }`, and the same three under `unless`. `guardrails` is
+ * transparent sugar for a bare Cedar expression (upstream discards the tag
+ * during lowering); `temporal { … }` is a genuine sub-language dispatched to a
+ * different parser.
+ *
+ * These are not schema-driven the way `Cedar::Policy`'s generated class is.
+ * Codegen's input is the project's `.cedarschema`, which says nothing about
+ * event kinds or temporal operators, so the dialect's classes are written here
+ * and typed against the builders in `./temporal.ts`.
+ */
+
+import type { Declarable } from "@intentius/chant/declarable";
+import { createResource } from "@intentius/chant/runtime";
+import type { CedarEffect, CedarScope } from "../serializer";
+import type { TemporalCondition } from "./temporal";
+import type { EventSchema } from "./event-schema";
+import type { MacroDefinition } from "./macros";
+
+/** The lexicon these entities belong to — dogwood is a dialect of cedar, not a lexicon. */
+export const DOGWOOD_LEXICON = "cedar";
+
+/** The `entityType` of a temporal policy. */
+export const DOGWOOD_POLICY_TYPE = "Dogwood::TemporalPolicy";
+
+/** The `entityType` of an event schema. */
+export const DOGWOOD_EVENT_SCHEMA_TYPE = "Dogwood::EventSchema";
+
+/** The `entityType` of a macro library. */
+export const DOGWOOD_MACRO_LIBRARY_TYPE = "Dogwood::MacroLibrary";
+
+/** The `.dw` policy set written beside the cedar outputs. */
+export const DOGWOOD_POLICY_FILENAME = "policies.dw";
+
+/** The `.dwschema` event schema — what `dogwood validate --event-schema` reads. */
+export const DOGWOOD_EVENT_SCHEMA_FILENAME = "events.dwschema";
+
+/** The macro library — what `dogwood validate --macros` reads. */
+export const DOGWOOD_MACRO_FILENAME = "macros.dw";
+
+/**
+ * The props of a `Dogwood::TemporalPolicy`.
+ *
+ * The first six mirror `CedarPolicyProps` exactly. The rest are the dialect's.
+ */
+export interface TemporalPolicyProps {
+ /** Defaults to `permit` when omitted. */
+ effect?: CedarEffect;
+ /** Defaults to unconstrained (`{}`) when omitted. */
+ principal?: CedarScope;
+ /** Defaults to unconstrained (`{}`) when omitted. */
+ action?: CedarScope;
+ /** Defaults to unconstrained (`{}`) when omitted. */
+ resource?: CedarScope;
+ /** Cedar expression strings, each emitted as its own `when { … }` clause. */
+ when?: string[];
+ /** Cedar expression strings, each emitted as its own `unless { … }` clause. */
+ unless?: string[];
+ /** Emitted as `@key("value")`; an explicit `id` wins over the logical name. */
+ annotations?: Record;
+
+ /** Each emitted as its own `when temporal { … }` clause. */
+ whenTemporal?: TemporalCondition[];
+ /** Each emitted as its own `unless temporal { … }` clause. */
+ unlessTemporal?: TemporalCondition[];
+ /**
+ * Cedar expression strings emitted as `when guardrails { … }`.
+ *
+ * The tag carries no separate grammar — upstream parses the body as an
+ * ordinary Cedar expression and discards the tag when lowering. It marks a
+ * clause as a guardrail for a human reader and for whatever reads the source
+ * after chant; it does not change what the policy means.
+ */
+ whenGuardrails?: string[];
+ /** As {@link whenGuardrails}, negated. */
+ unlessGuardrails?: string[];
+}
+
+/**
+ * A temporal policy. Declare one per policy, the same way as `Cedar::Policy`:
+ *
+ * ```ts
+ * export const readAfterLogin = new TemporalPolicy({
+ * action: { eq: 'Drupe::Action::"Read"' },
+ * whenTemporal: [
+ * formerly("1h", predicate('Drupe::Action::"Login"', "response", {
+ * "input.user": ctx("input.user"),
+ * })),
+ * ],
+ * });
+ * ```
+ */
+export const TemporalPolicy = createResource(DOGWOOD_POLICY_TYPE, DOGWOOD_LEXICON, {}) as unknown as new (
+ props: TemporalPolicyProps,
+) => Declarable;
+
+/** The props of a `Dogwood::EventSchema`. */
+export interface EventSchemaProps {
+ /** Built with `eventSchema()` or `defaultEventSchema()`. */
+ schema: EventSchema;
+ /** Defaults to {@link DOGWOOD_EVENT_SCHEMA_FILENAME}. */
+ filename?: string;
+}
+
+/** The service half of the schema, emitted as `.dwschema` text. */
+export const TemporalEventSchema = createResource(DOGWOOD_EVENT_SCHEMA_TYPE, DOGWOOD_LEXICON, {}) as unknown as new (
+ props: EventSchemaProps,
+) => Declarable;
+
+/** The props of a `Dogwood::MacroLibrary`. */
+export interface MacroLibraryProps {
+ macros: MacroDefinition[];
+ /** Defaults to {@link DOGWOOD_MACRO_FILENAME}. Ignored when `inline` is set. */
+ filename?: string;
+ /**
+ * Emit the definitions at the top of the policy set instead of into their own
+ * file.
+ *
+ * A policy set's own `def` shadows a same-named library macro, so inlining is
+ * how a project stops depending on whoever runs the CLI passing `--macros`.
+ */
+ inline?: boolean;
+}
+
+/** A `def cedar` / `def temporal` library, emitted as `.dw` text. */
+export const TemporalMacroLibrary = createResource(DOGWOOD_MACRO_LIBRARY_TYPE, DOGWOOD_LEXICON, {}) as unknown as new (
+ props: MacroLibraryProps,
+) => Declarable;
diff --git a/lexicons/cedar/src/dogwood/scan.ts b/lexicons/cedar/src/dogwood/scan.ts
new file mode 100644
index 0000000000..aa2aca78fc
--- /dev/null
+++ b/lexicons/cedar/src/dogwood/scan.ts
@@ -0,0 +1,287 @@
+/**
+ * Reading the emitted dogwood artifacts back, for the DWD post-synth checks.
+ *
+ * The checks judge the *text*, not the in-memory model, for the same reason
+ * the CED checks judge `policies.cedar.json`: `chant audit` runs over a
+ * checked-in artifact chant did not write, and a wall that only fires on
+ * chant's own output is not a wall. It also means the typed builders and the
+ * walls are independent — DWDC012 catches a windowless `formerly` even though
+ * the builders cannot construct one, because `raw()` and a hand-written `.dw`
+ * both can.
+ *
+ * This is scanning, not parsing. Upstream owns the parser and #1659 owns
+ * shelling to it; what is here is the subset of the surface that answers the
+ * three questions the walls ask, plus enough comment handling not to be fooled
+ * by a commented-out clause.
+ */
+
+import type { PostSynthContext } from "@intentius/chant/lint/post-synth";
+import { DEFAULT_MAX_WINDOW, windowSeconds, type TimeUnit } from "./window";
+import { DOGWOOD_EVENT_SCHEMA_SUFFIX, DOGWOOD_POLICY_SUFFIX } from "./serialize";
+
+/** One emitted artifact, with everything needed to name it in a finding. */
+export interface DogwoodArtifact {
+ /** The lexicon output it came from. */
+ lexicon: string;
+ /** The filename, which is what a finding points the reader at. */
+ source: string;
+ /** The file's text. */
+ text: string;
+}
+
+/** Every `.dw` policy file in the build output. */
+export function dogwoodPolicyFiles(ctx: PostSynthContext): DogwoodArtifact[] {
+ return filesWithSuffix(ctx, DOGWOOD_POLICY_SUFFIX);
+}
+
+/** Every `.dwschema` event-schema file in the build output. */
+export function dogwoodSchemaFiles(ctx: PostSynthContext): DogwoodArtifact[] {
+ return filesWithSuffix(ctx, DOGWOOD_EVENT_SCHEMA_SUFFIX);
+}
+
+function filesWithSuffix(ctx: PostSynthContext, suffix: string): DogwoodArtifact[] {
+ const found: DogwoodArtifact[] = [];
+ for (const [lexicon, output] of ctx.outputs) {
+ if (typeof output === "string") continue;
+ for (const [filename, content] of Object.entries(output.files ?? {})) {
+ if (typeof content !== "string") continue;
+ if (!filename.endsWith(suffix)) continue;
+ found.push({ lexicon, source: filename, text: content });
+ }
+ }
+ return found;
+}
+
+// ── Comments ──────────────────────────────────────────────────────
+
+/**
+ * Blank out `//` comments, leaving string literals intact.
+ *
+ * String literals stay because a predicate's action id lives inside one
+ * (`Drupe::Action::"Read"`), and blanking those would blind every scan below.
+ * The walk is string-aware in the other direction too: a `//` inside a quoted
+ * value (a URL, say) is not a comment.
+ *
+ * Comment bytes become spaces so every offset in the result still lines up
+ * with the original file.
+ */
+export function blankComments(text: string): string {
+ const out = text.split("");
+ let inString = false;
+ for (let i = 0; i < text.length; i++) {
+ const ch = text[i];
+ if (inString) {
+ if (ch === "\\") {
+ i++;
+ continue;
+ }
+ if (ch === '"') inString = false;
+ continue;
+ }
+ if (ch === '"') {
+ inString = true;
+ continue;
+ }
+ if (ch === "/" && text[i + 1] === "/") {
+ while (i < text.length && text[i] !== "\n") {
+ out[i] = " ";
+ i++;
+ }
+ }
+ }
+ return out.join("");
+}
+
+// ── Temporal regions ──────────────────────────────────────────────
+
+/**
+ * The stretches of a `.dw` file that the temporal sub-parser reads: every
+ * `temporal { … }` marker body, and every `def temporal … { … }` macro body.
+ *
+ * Scanning only these is what keeps a Cedar `when { … }` clause from being
+ * mistaken for temporal source — `context.retryWindow == 3` should not read as
+ * a window, and a Cedar attribute named `since` is not the `since` operator.
+ */
+export function temporalRegions(text: string): string[] {
+ const source = blankComments(text);
+ const regions: string[] = [];
+
+ const markers = /\btemporal\s*\{/g;
+ for (let m = markers.exec(source); m !== null; m = markers.exec(source)) {
+ const body = matchedBlock(source, m.index + m[0].length - 1);
+ if (body !== undefined) regions.push(body);
+ }
+
+ const macros = /\bdef\s+temporal\s+[A-Za-z_][A-Za-z0-9_]*\s*\([^)]*\)\s*\{/g;
+ for (let m = macros.exec(source); m !== null; m = macros.exec(source)) {
+ const body = matchedBlock(source, m.index + m[0].length - 1);
+ if (body !== undefined) regions.push(body);
+ }
+
+ return regions;
+}
+
+/** The text between `text[open]` (a `{`) and its matching `}`, or undefined. */
+function matchedBlock(text: string, open: number): string | undefined {
+ let depth = 0;
+ let inString = false;
+ for (let i = open; i < text.length; i++) {
+ const ch = text[i];
+ if (inString) {
+ if (ch === "\\") i++;
+ else if (ch === '"') inString = false;
+ continue;
+ }
+ if (ch === '"') inString = true;
+ else if (ch === "{") depth++;
+ else if (ch === "}") {
+ depth--;
+ if (depth === 0) return text.slice(open + 1, i);
+ }
+ }
+ return undefined;
+}
+
+// ── What the walls ask ────────────────────────────────────────────
+
+/** One `Ns::Action::"Name"::kind` predicate head found in temporal source. */
+export interface TemporalPredicateRef {
+ /** The qualified action, quoted id and all. */
+ action: string;
+ /** The event kind segment after the quoted id. */
+ kind: string;
+}
+
+const PREDICATE = /([A-Za-z_][A-Za-z0-9_]*(?:::[A-Za-z_][A-Za-z0-9_]*)*::"[^"]*")::([A-Za-z_][A-Za-z0-9_]*)/g;
+
+/** Every temporal predicate head in a `.dw` file, in source order. */
+export function scanPredicates(text: string): TemporalPredicateRef[] {
+ const refs: TemporalPredicateRef[] = [];
+ for (const region of temporalRegions(text)) {
+ for (let m = PREDICATE.exec(region); m !== null; m = PREDICATE.exec(region)) {
+ refs.push({ action: m[1], kind: m[2] });
+ }
+ PREDICATE.lastIndex = 0;
+ }
+ return refs;
+}
+
+/** One window literal found in temporal source. */
+export interface WindowRef {
+ /** As written: `48h`. */
+ text: string;
+ seconds: number;
+ /** `within` for an operator's window, `argument` for a bare macro-call interval. */
+ position: "within" | "argument";
+}
+
+const WITHIN_WINDOW = /\bwithin\s+(\d+)([smhd])\b/g;
+/** A bare interval in macro-call argument position: `once(1h, …)`, `f(a, 30m)`. */
+const ARGUMENT_WINDOW = /[(,]\s*(\d+)([smhd])\s*(?=[,)])/g;
+
+/**
+ * Every window literal in a `.dw` file's temporal source.
+ *
+ * Both shapes count against `max_window`: a macro-call interval is the window
+ * a `within ?w` in the macro body resolves to, so `once(48h, …)` looks back
+ * exactly as far as `formerly within 48h` does.
+ */
+export function scanWindows(text: string): WindowRef[] {
+ const windows: WindowRef[] = [];
+ for (const region of temporalRegions(text)) {
+ for (let m = WITHIN_WINDOW.exec(region); m !== null; m = WITHIN_WINDOW.exec(region)) {
+ windows.push(windowRef(m[1], m[2], "within"));
+ }
+ WITHIN_WINDOW.lastIndex = 0;
+ for (let m = ARGUMENT_WINDOW.exec(region); m !== null; m = ARGUMENT_WINDOW.exec(region)) {
+ windows.push(windowRef(m[1], m[2], "argument"));
+ }
+ ARGUMENT_WINDOW.lastIndex = 0;
+ }
+ return windows;
+}
+
+function windowRef(value: string, unit: string, position: WindowRef["position"]): WindowRef {
+ const w = { value: Number(value), unit: unit as TimeUnit };
+ return { text: `${w.value}${w.unit}`, seconds: windowSeconds(w), position };
+}
+
+/**
+ * Every `formerly` / `previous` / `since` that is not followed by a `within`.
+ *
+ * Unrepresentable through the builders — {@link formerly} and its siblings all
+ * take the window as an argument — but reachable through `raw()`, through a
+ * hand-written `.dw`, and through an audit of a file chant never wrote.
+ */
+export function scanWindowlessOperators(text: string): string[] {
+ const found: string[] = [];
+ const pattern = /\b(formerly|previous|since)\b(?!\s+within\b)/g;
+ for (const region of temporalRegions(text)) {
+ for (let m = pattern.exec(region); m !== null; m = pattern.exec(region)) {
+ found.push(m[1]);
+ }
+ pattern.lastIndex = 0;
+ }
+ return found;
+}
+
+// ── The event schema side ─────────────────────────────────────────
+
+/** What a `.dwschema` file says, as far as the walls need to know. */
+export interface EventSchemaFacts {
+ /** Every declared event kind. */
+ kinds: string[];
+ /** The `max_window` directive in seconds, or upstream's 24h default when absent. */
+ maxWindowSeconds: number;
+ /** As written (`30d`), or undefined when the directive is absent. */
+ maxWindowText?: string;
+ /** True when at least one field carries a `pin … = …`. */
+ hasPin: boolean;
+}
+
+const EVENT_DECL = /\bevent\s*<\s*[A-Za-z_][A-Za-z0-9_]*\s*>\s*::\s*([A-Za-z_][A-Za-z0-9_]*)/g;
+const MAX_WINDOW = /\bmax_window\s*=\s*(\d+)([smhd])\b/;
+const PINNED_FIELD = /\bpin\s+[A-Za-z_][A-Za-z0-9_]*\s*:/;
+
+/** Read a `.dwschema` file's declarations. */
+export function readEventSchema(text: string): EventSchemaFacts {
+ const source = blankComments(text);
+
+ const kinds: string[] = [];
+ for (let m = EVENT_DECL.exec(source); m !== null; m = EVENT_DECL.exec(source)) {
+ if (!kinds.includes(m[1])) kinds.push(m[1]);
+ }
+ EVENT_DECL.lastIndex = 0;
+
+ const max = MAX_WINDOW.exec(source);
+ return {
+ kinds,
+ maxWindowSeconds: max
+ ? windowSeconds({ value: Number(max[1]), unit: max[2] as TimeUnit })
+ : windowSeconds(DEFAULT_MAX_WINDOW),
+ maxWindowText: max ? `${max[1]}${max[2]}` : undefined,
+ hasPin: PINNED_FIELD.test(source),
+ };
+}
+
+/**
+ * The look-back cap in force for a build.
+ *
+ * With no emitted schema, `ServiceSchema::defaults()` applies and the cap is
+ * 24h. With several, the tightest one wins — a window legal under one schema
+ * and not another is a window some consumer will reject.
+ */
+export function effectiveMaxWindowSeconds(schemas: EventSchemaFacts[]): { seconds: number; text: string } {
+ if (schemas.length === 0) {
+ return {
+ seconds: windowSeconds(DEFAULT_MAX_WINDOW),
+ text: `${DEFAULT_MAX_WINDOW.value}${DEFAULT_MAX_WINDOW.unit}`,
+ };
+ }
+ let tightest = schemas[0];
+ for (const s of schemas) if (s.maxWindowSeconds < tightest.maxWindowSeconds) tightest = s;
+ return {
+ seconds: tightest.maxWindowSeconds,
+ text: tightest.maxWindowText ?? `${DEFAULT_MAX_WINDOW.value}${DEFAULT_MAX_WINDOW.unit}`,
+ };
+}
diff --git a/lexicons/cedar/src/dogwood/serialize.test.ts b/lexicons/cedar/src/dogwood/serialize.test.ts
new file mode 100644
index 0000000000..cc7e02b88f
--- /dev/null
+++ b/lexicons/cedar/src/dogwood/serialize.test.ts
@@ -0,0 +1,331 @@
+/**
+ * The `.dw` serializer leg, through the cedar serializer that hosts it.
+ *
+ * Exercised end to end rather than through `serializeDogwood` directly,
+ * because the thing worth pinning is that a build holding both kinds of policy
+ * emits both artifacts, from one pass, with ids derived the same way.
+ */
+import { describe, test, expect } from "vitest";
+import { readFileSync } from "fs";
+import { join } from "path";
+import { fileURLToPath } from "url";
+import { DECLARABLE_MARKER, type Declarable } from "@intentius/chant/declarable";
+import type { SerializerResult } from "@intentius/chant/serializer";
+import { cedarSerializer, CEDAR_JSON_FILENAME } from "../serializer";
+import {
+ DOGWOOD_EVENT_SCHEMA_FILENAME,
+ DOGWOOD_EVENT_SCHEMA_TYPE,
+ DOGWOOD_MACRO_FILENAME,
+ DOGWOOD_MACRO_LIBRARY_TYPE,
+ DOGWOOD_POLICY_FILENAME,
+ DOGWOOD_POLICY_TYPE,
+} from "./policy";
+import {
+ and,
+ call,
+ compare,
+ count,
+ ctx,
+ exists,
+ formerly,
+ interval,
+ predicate,
+ since,
+ sum,
+ tp,
+ typedBinder,
+ varRef,
+} from "./temporal";
+import { defTemporalMacro, defaultMacroLibrary, macroCondition, macroWindow, renderMacroLibrary } from "./macros";
+import { defaultEventSchema } from "./event-schema";
+
+const TESTDATA = join(fileURLToPath(new URL(".", import.meta.url)), "testdata");
+const UPSTREAM = "dogwood-policy/dogwood@5063bcc2d6d6cf5024d1b0498e6cc8ef52cbcf0c";
+
+function fixture(name: string): string {
+ return readFileSync(join(TESTDATA, name), "utf-8");
+}
+
+function attribution(...sources: string[]): string {
+ return [
+ `// Adapted from ${UPSTREAM} (Apache-2.0):`,
+ ...sources.map((s) => `// ${s}`),
+ "// Upstream's shape; the bytes are what chant's typed builders emit.",
+ "",
+ "",
+ ].join("\n");
+}
+
+function mock(entityType: string, props: Record): Declarable {
+ return {
+ [DECLARABLE_MARKER]: true,
+ lexicon: "cedar",
+ entityType,
+ kind: "resource",
+ props,
+ } as unknown as Declarable;
+}
+
+function result(entities: Map): SerializerResult {
+ const out = cedarSerializer.serialize(entities);
+ if (typeof out === "string") throw new Error(`expected a SerializerResult, got: ${JSON.stringify(out)}`);
+ return out;
+}
+
+// ── The golden policy set ──────────────────────────────────────────
+
+/**
+ * One inline macro library and four policies, each modelled on a shipped
+ * upstream example: approval-before-action, a `sum` budget, a `since`
+ * sequencing rule with a guardrail, and a `count` rate limit.
+ */
+function goldenEntities(): Map {
+ const sumFormerly = defTemporalMacro(
+ "sum_formerly",
+ ["?a", "?w", "?body"],
+ sum(
+ "?a",
+ [typedBinder("?a", "Long"), typedBinder("$t", "Timepoint")],
+ formerly(macroWindow("?w"), and(macroCondition("?body"), tp("$t"))),
+ ),
+ "Sums the numeric value `?a` over occurrences of `?body` within window `?w`.",
+ );
+
+ return new Map([
+ ["library", mock(DOGWOOD_MACRO_LIBRARY_TYPE, { macros: [sumFormerly], inline: true })],
+ [
+ "readAfterLogin",
+ mock(DOGWOOD_POLICY_TYPE, {
+ annotations: { id: "read_after_login" },
+ action: { eq: 'Drupe::Action::"Read"' },
+ whenTemporal: [
+ formerly("1h", predicate('Drupe::Action::"Login"', "response", { "input.user": ctx("input.user") })),
+ ],
+ }),
+ ],
+ [
+ "transferSumOver100",
+ mock(DOGWOOD_POLICY_TYPE, {
+ annotations: { id: "transfer_sum_over_100" },
+ action: { eq: 'Drupe::Action::"Alert"' },
+ whenTemporal: [
+ exists(
+ typedBinder("total", "Long"),
+ and(
+ compare(
+ call("sum_formerly", [
+ varRef("a"),
+ interval("1h"),
+ predicate('Drupe::Action::"Transfer"', "request", {
+ "input.user": varRef("_"),
+ "input.amount": varRef("a"),
+ }),
+ ]),
+ "==",
+ varRef("total"),
+ ),
+ compare(varRef("total"), ">", 100),
+ ),
+ ),
+ ],
+ }),
+ ],
+ [
+ "noToolAfterSensitiveRead",
+ mock(DOGWOOD_POLICY_TYPE, {
+ effect: "forbid",
+ annotations: { id: "no_tool_after_sensitive_read" },
+ action: { eq: 'Drupe::Action::"Invoke"' },
+ whenGuardrails: ['context.input.tool != "audit"'],
+ whenTemporal: [
+ since(
+ predicate('Drupe::Action::"Read"', "response", { "output.classification": varRef("c") }),
+ "30m",
+ predicate('Drupe::Action::"Login"', "request"),
+ ),
+ ],
+ unless: ['principal in Drupe::Group::"breakglass"'],
+ }),
+ ],
+ [
+ "rateLimited",
+ mock(DOGWOOD_POLICY_TYPE, {
+ annotations: { id: "rate_limited" },
+ action: { eq: 'Drupe::Action::"Transfer"' },
+ whenTemporal: [
+ compare(
+ count(
+ [typedBinder("t", "Timepoint")],
+ formerly("15m", and(predicate('Drupe::Action::"Transfer"', "request"), tp("t"))),
+ ),
+ "<",
+ 5,
+ ),
+ ],
+ }),
+ ],
+ ]);
+}
+
+describe("the .dw golden output", () => {
+ test("matches the fixture byte for byte", () => {
+ const files = result(goldenEntities()).files ?? {};
+ expect(files[DOGWOOD_POLICY_FILENAME]).toBe(
+ fixture("temporal-policies.dw").slice(
+ attribution(
+ "dogwood-docs/examples/read_after_login/policy.dw",
+ "dogwood-docs/examples/temporal_sum_formerly_transfer/policy.dw",
+ "dogwood-docs/examples/read_heartbeat_since_login_30s/policy.dw",
+ "dogwood-docs/examples/temporal_count_formerly_login/policy.dw",
+ ).length,
+ ),
+ );
+ });
+
+ test("the head is Cedar's — annotations, effect, three scope positions", () => {
+ const text = result(goldenEntities()).files?.[DOGWOOD_POLICY_FILENAME] ?? "";
+ expect(text).toContain('@id("read_after_login")\npermit (\n principal,\n action == Drupe::Action::"Read",\n resource\n)');
+ expect(text).toContain('@id("no_tool_after_sensitive_read")\nforbid (');
+ });
+
+ test("inline macro definitions come before the policies that call them", () => {
+ const text = result(goldenEntities()).files?.[DOGWOOD_POLICY_FILENAME] ?? "";
+ expect(text.indexOf("def temporal sum_formerly")).toBeLessThan(text.indexOf("@id("));
+ });
+
+ test("every clause form the dialect adds is emitted", () => {
+ const text = result(goldenEntities()).files?.[DOGWOOD_POLICY_FILENAME] ?? "";
+ expect(text).toContain("when temporal {");
+ expect(text).toContain('when guardrails { context.input.tool != "audit" }');
+ expect(text).toContain('unless { principal in Drupe::Group::"breakglass" }');
+ });
+});
+
+// ── Ids and the cedar half ─────────────────────────────────────────
+
+describe("the two halves of one policy set", () => {
+ const cedarPolicy = () =>
+ mock("Cedar::Policy", {
+ action: { eq: 'Drupe::Action::"List"' },
+ when: ["principal == resource.owner"],
+ });
+
+ test("a build with both emits both, in one pass", () => {
+ const entities = new Map([
+ ["allowOwnerList", cedarPolicy()],
+ [
+ "readAfterLogin",
+ mock(DOGWOOD_POLICY_TYPE, {
+ action: { eq: 'Drupe::Action::"Read"' },
+ whenTemporal: [formerly("1h", predicate('Drupe::Action::"Login"', "response"))],
+ }),
+ ],
+ ]);
+ const out = result(entities);
+ expect(out.primary).toContain('@id("allow-owner-list")');
+ expect(out.primary).not.toContain("temporal");
+ expect(Object.keys(out.files ?? {})).toContain(CEDAR_JSON_FILENAME);
+ expect(out.files?.[DOGWOOD_POLICY_FILENAME]).toContain('@id("read-after-login")');
+ });
+
+ test("policy ids are derived the same way on both legs", () => {
+ const entities = new Map([
+ [
+ "allowAdminRead",
+ mock(DOGWOOD_POLICY_TYPE, {
+ whenTemporal: [formerly("1h", predicate('Ns::Action::"A"', "request"))],
+ }),
+ ],
+ ]);
+ expect(result(entities).files?.[DOGWOOD_POLICY_FILENAME]).toContain('@id("allow-admin-read")');
+ });
+
+ test("a temporal-only build still emits its files, with an empty cedar primary", () => {
+ const entities = new Map([
+ [
+ "readAfterLogin",
+ mock(DOGWOOD_POLICY_TYPE, {
+ whenTemporal: [formerly("1h", predicate('Ns::Action::"A"', "request"))],
+ }),
+ ],
+ ]);
+ const out = result(entities);
+ expect(out.primary).toBe("");
+ expect(out.files?.[CEDAR_JSON_FILENAME]).toBeUndefined();
+ expect(out.files?.[DOGWOOD_POLICY_FILENAME]).toContain("when temporal {");
+ });
+
+ test("a cedar-only build is untouched by the dialect", () => {
+ const entities = new Map([["allowOwnerList", cedarPolicy()]]);
+ const out = result(entities);
+ expect(Object.keys(out.files ?? {})).toEqual([CEDAR_JSON_FILENAME]);
+ expect(out.warnings).toBeUndefined();
+ });
+
+ test("an empty build is still the empty string", () => {
+ expect(cedarSerializer.serialize(new Map())).toBe("");
+ });
+
+ test("the DWD id family is declared on the serializer", () => {
+ expect(cedarSerializer.extraRulePrefixes).toEqual(["DWD"]);
+ });
+});
+
+// ── The companion files ────────────────────────────────────────────
+
+describe("event schemas and macro libraries", () => {
+ test("an event schema entity becomes .dwschema text", () => {
+ const entities = new Map([
+ ["events", mock(DOGWOOD_EVENT_SCHEMA_TYPE, { schema: defaultEventSchema() })],
+ ]);
+ const files = result(entities).files ?? {};
+ expect(files[DOGWOOD_EVENT_SCHEMA_FILENAME]).toContain("decision event ::request {");
+ });
+
+ test("an explicit filename is honoured, so several schemas can coexist", () => {
+ const entities = new Map([
+ ["a", mock(DOGWOOD_EVENT_SCHEMA_TYPE, { schema: defaultEventSchema() })],
+ ["b", mock(DOGWOOD_EVENT_SCHEMA_TYPE, { schema: defaultEventSchema({ maxWindow: "30d" }), filename: "gateway.dwschema" })],
+ ]);
+ const files = result(entities).files ?? {};
+ expect(files[DOGWOOD_EVENT_SCHEMA_FILENAME]).not.toContain("max_window");
+ expect(files["gateway.dwschema"]).toContain("max_window = 30d");
+ });
+
+ test("two schemas on one filename warn rather than emitting something upstream rejects", () => {
+ const entities = new Map([
+ ["a", mock(DOGWOOD_EVENT_SCHEMA_TYPE, { schema: defaultEventSchema() })],
+ ["b", mock(DOGWOOD_EVENT_SCHEMA_TYPE, { schema: defaultEventSchema({ maxWindow: "30d" }) })],
+ ]);
+ const out = result(entities);
+ expect(out.warnings?.[0]).toMatch(/both target events\.dwschema/);
+ expect(out.files?.[DOGWOOD_EVENT_SCHEMA_FILENAME]).not.toContain("max_window");
+ });
+
+ test("a non-inline macro library becomes its own file", () => {
+ const entities = new Map([
+ ["defaults", mock(DOGWOOD_MACRO_LIBRARY_TYPE, { macros: defaultMacroLibrary() })],
+ ]);
+ const files = result(entities).files ?? {};
+ expect(files[DOGWOOD_MACRO_FILENAME]).toBe(
+ fixture("default-macros.dw").slice(
+ attribution("dogwood-language/configuration/default_macros.dw").length,
+ ),
+ );
+ });
+
+ test("the emitted default library is upstream's, definition for definition", () => {
+ const text = renderMacroLibrary(defaultMacroLibrary());
+ for (const name of ["count_within", "sum_within", "count_distinct_within", "bind"]) {
+ expect(text).toContain(`def temporal ${name}(`);
+ }
+ });
+
+ test("an empty macro library warns rather than writing an empty file", () => {
+ const entities = new Map([
+ ["empty", mock(DOGWOOD_MACRO_LIBRARY_TYPE, { macros: [] })],
+ ]);
+ const out = cedarSerializer.serialize(entities);
+ expect(typeof out === "string" ? undefined : out.warnings?.[0]).toMatch(/declares no macros/);
+ });
+});
diff --git a/lexicons/cedar/src/dogwood/serialize.ts b/lexicons/cedar/src/dogwood/serialize.ts
new file mode 100644
index 0000000000..57e6750931
--- /dev/null
+++ b/lexicons/cedar/src/dogwood/serialize.ts
@@ -0,0 +1,209 @@
+/**
+ * The `.dw` serializer leg.
+ *
+ * Runs inside the cedar serializer, not beside it: `serializeDogwood` is
+ * called once the cedar policies have been rendered, and its files land in the
+ * same `SerializerResult`. That is the whole point of shipping dogwood as a
+ * dialect — a `.dw` file stripped of Cedar semantics is meaningless, and a
+ * project's temporal policies and its plain Cedar policies are one policy set
+ * with two halves.
+ *
+ * Nothing here re-implements Cedar rendering. The policy head comes from
+ * `../serializer`'s `renderPolicyHead`, the scope forms from its
+ * `renderScope`, and the `when`/`unless` bodies from its `conditionStrings`,
+ * so a change to how a scope is written moves both outputs at once.
+ */
+
+import type { Declarable } from "@intentius/chant/declarable";
+import { isPropertyDeclarable } from "@intentius/chant/declarable";
+import { walkValue, type SerializerVisitor } from "@intentius/chant/serializer-walker";
+import { conditionStrings, getProps, isRecord, renderPolicyHead, resolvePolicyId } from "../policy-text";
+import { renderCondition, type TemporalCondition } from "./temporal";
+import { renderEventSchema, type EventSchema } from "./event-schema";
+import { renderMacroLibrary, type MacroDefinition } from "./macros";
+import {
+ DOGWOOD_EVENT_SCHEMA_FILENAME,
+ DOGWOOD_EVENT_SCHEMA_TYPE,
+ DOGWOOD_MACRO_FILENAME,
+ DOGWOOD_MACRO_LIBRARY_TYPE,
+ DOGWOOD_POLICY_FILENAME,
+ DOGWOOD_POLICY_TYPE,
+} from "./policy";
+
+/** Files ending in this carry dogwood policy text. */
+export const DOGWOOD_POLICY_SUFFIX = ".dw";
+
+/** Files ending in this carry an event schema. */
+export const DOGWOOD_EVENT_SCHEMA_SUFFIX = ".dwschema";
+
+/** What the leg produced: files to write, and anything the build should say out loud. */
+export interface DogwoodSerializeResult {
+ files: Record;
+ warnings: string[];
+}
+
+// ── Clause rendering ──────────────────────────────────────────────
+
+function temporalConditions(value: unknown): TemporalCondition[] {
+ if (value === undefined || value === null) return [];
+ const list = Array.isArray(value) ? value : [value];
+ return list.filter((node): node is TemporalCondition => isRecord(node) && typeof node.op === "string");
+}
+
+/**
+ * One policy, in `.dw` surface syntax.
+ *
+ * Clause order is fixed rather than authored: every `when` form, then every
+ * `unless` form. Cedar evaluates a policy's conditions as a conjunction, and
+ * so does dogwood, so the order carries no meaning — fixing it means a policy
+ * that gains a temporal clause does not reshuffle the ones already there.
+ */
+export function renderTemporalPolicyText(id: string, props: Record): string {
+ const lines = renderPolicyHead(id, props);
+
+ for (const clause of conditionStrings(props.when)) lines.push(`when { ${clause} }`);
+ for (const clause of conditionStrings(props.whenGuardrails)) lines.push(`when guardrails { ${clause} }`);
+ for (const node of temporalConditions(props.whenTemporal)) {
+ lines.push("when temporal {", ` ${renderCondition(node)}`, "}");
+ }
+
+ for (const clause of conditionStrings(props.unless)) lines.push(`unless { ${clause} }`);
+ for (const clause of conditionStrings(props.unlessGuardrails)) lines.push(`unless guardrails { ${clause} }`);
+ for (const node of temporalConditions(props.unlessTemporal)) {
+ lines.push("unless temporal {", ` ${renderCondition(node)}`, "}");
+ }
+
+ return lines.join("\n") + ";";
+}
+
+// ── The walker ────────────────────────────────────────────────────
+
+/**
+ * Same visitor contract as the cedar serializer's: a reference collapses to
+ * the text a policy names it by. The temporal AST is plain data, so the walker
+ * passes it through untouched while still resolving any Declarable a scope
+ * position holds.
+ */
+const dogwoodVisitor: SerializerVisitor = {
+ attrRef: (logicalName, attribute) => `${logicalName}.${attribute}`,
+ resourceRef: (logicalName) => logicalName,
+ propertyDeclarable: (entity, walk) => {
+ const out: Record = {};
+ for (const [key, value] of Object.entries(getProps(entity))) {
+ if (key === "entityType" || key === "lexicon") continue;
+ if (value === undefined) continue;
+ out[key] = walk(value);
+ }
+ return out;
+ },
+};
+
+// ── The leg ───────────────────────────────────────────────────────
+
+/**
+ * Render every dogwood entity in the build.
+ *
+ * Returns `undefined` when the build holds no temporal policies, event schemas
+ * or macro libraries at all — a cedar-only project sees no `.dw` output and no
+ * behaviour change.
+ *
+ * Ids come from `resolvePolicyId`, the same rule `cedarPolicyRecords` uses, so
+ * a policy's `@id` does not depend on which leg rendered it.
+ */
+export function serializeDogwood(entities: Map): DogwoodSerializeResult | undefined {
+ // Reverse map first: walkValue resolves a Declarable reference by identity,
+ // so every entity has to be known before any of them is walked.
+ const entityNames = new Map();
+ for (const [name, entity] of entities) {
+ entityNames.set(entity, name);
+ }
+
+ const policyText: string[] = [];
+ const inlineMacros: MacroDefinition[] = [];
+ const macroFiles = new Map();
+ const schemaFiles = new Map();
+ const warnings: string[] = [];
+
+ for (const [name, entity] of entities) {
+ if (isPropertyDeclarable(entity)) continue;
+ if (
+ entity.entityType !== DOGWOOD_POLICY_TYPE &&
+ entity.entityType !== DOGWOOD_EVENT_SCHEMA_TYPE &&
+ entity.entityType !== DOGWOOD_MACRO_LIBRARY_TYPE
+ ) {
+ continue;
+ }
+
+ const props = walkValue(getProps(entity), entityNames, dogwoodVisitor) as Record;
+
+ if (entity.entityType === DOGWOOD_POLICY_TYPE) {
+ policyText.push(renderTemporalPolicyText(resolvePolicyId(name, props), props));
+ continue;
+ }
+
+ if (entity.entityType === DOGWOOD_MACRO_LIBRARY_TYPE) {
+ const defs = Array.isArray(props.macros) ? (props.macros as MacroDefinition[]) : [];
+ if (defs.length === 0) {
+ warnings.push(`dogwood: macro library "${name}" declares no macros, so nothing was emitted for it`);
+ continue;
+ }
+ if (props.inline === true) {
+ inlineMacros.push(...defs);
+ continue;
+ }
+ const filename = typeof props.filename === "string" ? props.filename : DOGWOOD_MACRO_FILENAME;
+ macroFiles.set(filename, [...(macroFiles.get(filename) ?? []), ...defs]);
+ continue;
+ }
+
+ // DOGWOOD_EVENT_SCHEMA_TYPE
+ const schema = props.schema;
+ if (!isRecord(schema) || !Array.isArray(schema.events)) {
+ warnings.push(`dogwood: event schema "${name}" has no \`schema\` prop, so no .dwschema was written for it`);
+ continue;
+ }
+ const filename = typeof props.filename === "string" ? props.filename : DOGWOOD_EVENT_SCHEMA_FILENAME;
+ const existing = schemaFiles.get(filename);
+ if (existing) {
+ // Two schemas cannot share a file: `max_window` is a single directive at
+ // the top, so concatenating them would emit something upstream rejects.
+ warnings.push(
+ `dogwood: event schemas "${existing.name}" and "${name}" both target ${filename}; only "${existing.name}" was written — give one of them an explicit \`filename\``,
+ );
+ continue;
+ }
+ schemaFiles.set(filename, { name, schema: schema as unknown as EventSchema });
+ }
+
+ // Warnings alone are enough to report: a dogwood entity that produced no
+ // file is exactly the case worth saying out loud, and returning `undefined`
+ // here would swallow the reason.
+ if (
+ policyText.length === 0 &&
+ inlineMacros.length === 0 &&
+ macroFiles.size === 0 &&
+ schemaFiles.size === 0 &&
+ warnings.length === 0
+ ) {
+ return undefined;
+ }
+
+ const files: Record = {};
+
+ if (policyText.length > 0 || inlineMacros.length > 0) {
+ const sections: string[] = [];
+ if (inlineMacros.length > 0) sections.push(renderMacroLibrary(inlineMacros).trimEnd());
+ sections.push(...policyText);
+ files[DOGWOOD_POLICY_FILENAME] = sections.join("\n\n") + "\n";
+ }
+
+ for (const [filename, defs] of macroFiles) {
+ files[filename] = renderMacroLibrary(defs);
+ }
+
+ for (const [filename, { schema }] of schemaFiles) {
+ files[filename] = renderEventSchema(schema);
+ }
+
+ return { files, warnings };
+}
diff --git a/lexicons/cedar/src/dogwood/temporal.test.ts b/lexicons/cedar/src/dogwood/temporal.test.ts
new file mode 100644
index 0000000000..0502af0181
--- /dev/null
+++ b/lexicons/cedar/src/dogwood/temporal.test.ts
@@ -0,0 +1,272 @@
+import { describe, test, expect } from "vitest";
+import {
+ and,
+ arrayOf,
+ bool,
+ call,
+ compare,
+ count,
+ ctx,
+ decimalOf,
+ entityUid,
+ exists,
+ formerly,
+ int,
+ interval,
+ not,
+ predicate,
+ previous,
+ raw,
+ renderCondition,
+ renderTerm,
+ scopeRef,
+ since,
+ str,
+ sum,
+ temporalMarker,
+ term,
+ tp,
+ typedBinder,
+ varRef,
+ wildcard,
+} from "./temporal";
+import { countDistinctWithin, countWithin, macroCondition, macroWindow, sumWithin } from "./macros";
+import { renderWindow, window, windowSeconds } from "./window";
+
+// ── Windows ────────────────────────────────────────────────────────
+
+describe("temporal windows", () => {
+ test("a window is an integer and one of the four units", () => {
+ expect(window("90m")).toEqual({ value: 90, unit: "m" });
+ expect(renderWindow({ value: 7, unit: "d" })).toBe("7d");
+ });
+
+ test("a unit outside s/m/h/d is refused", () => {
+ // @ts-expect-error — "1w" is not assignable to WindowLike
+ expect(() => window("1w")).toThrow(/not a temporal window/);
+ });
+
+ test("windows are comparable across units", () => {
+ expect(windowSeconds("90m")).toBe(windowSeconds({ value: 5400, unit: "s" }));
+ expect(windowSeconds("2d")).toBeGreaterThan(windowSeconds("24h"));
+ });
+});
+
+// ── Terms ──────────────────────────────────────────────────────────
+
+describe("terms", () => {
+ test("literals render in Cedar's surface forms", () => {
+ expect(renderTerm(str('he said "hi"'))).toBe('"he said \\"hi\\""');
+ expect(renderTerm(int(-3))).toBe("-3");
+ expect(renderTerm(bool(true))).toBe("true");
+ expect(renderTerm(decimalOf("1.50"))).toBe('decimal("1.50")');
+ expect(renderTerm(wildcard())).toBe("*");
+ expect(renderTerm(arrayOf(1, 2, str("x")))).toBe('[1, 2, "x"]');
+ });
+
+ test("a non-integer is refused rather than silently truncated", () => {
+ expect(() => int(1.5)).toThrow(/whole number/);
+ });
+
+ test("paths and UIDs are distinct constructions, not guessed from a string", () => {
+ expect(renderTerm(ctx("input.user"))).toBe("context.input.user");
+ expect(renderTerm(scopeRef("principal", "dept"))).toBe("principal.dept");
+ expect(renderTerm(entityUid('Drupe::OAuthUser::"alice"'))).toBe('Drupe::OAuthUser::"alice"');
+ expect(renderTerm(varRef("total"))).toBe("total");
+ });
+
+ test("a malformed entity UID is refused at construction", () => {
+ expect(() => entityUid("Drupe::OAuthUser")).toThrow(/entity UID/);
+ });
+});
+
+// ── The parser primitives ──────────────────────────────────────────
+
+describe("predicates", () => {
+ test("action, kind and named arguments", () => {
+ const node = predicate('Drupe::Action::"Login"', "response", { "input.user": ctx("input.user") });
+ expect(renderCondition(node)).toBe(
+ 'Drupe::Action::"Login"::response{ input.user: context.input.user }',
+ );
+ });
+
+ test("no arguments still renders the mandatory braces", () => {
+ expect(renderCondition(predicate('Drupe::Action::"Login"', "request"))).toBe(
+ 'Drupe::Action::"Login"::request{}',
+ );
+ });
+
+ test("an unqualified action is refused", () => {
+ expect(() => predicate("Login", "request")).toThrow(/predicate action/);
+ });
+
+ test("a field path must be dotted identifiers", () => {
+ expect(() => predicate('Ns::Action::"A"', "request", { "input user": int(1) })).toThrow(/field path/);
+ });
+});
+
+describe("the past-only operators", () => {
+ const login = predicate('Drupe::Action::"Login"', "request");
+
+ test("formerly and previous take their window as an argument", () => {
+ expect(renderCondition(formerly("1h", login))).toBe('formerly within 1h Drupe::Action::"Login"::request{}');
+ expect(renderCondition(previous("30s", login))).toBe('previous within 30s Drupe::Action::"Login"::request{}');
+ });
+
+ test("since is infix and carries the window on the operator", () => {
+ const read = predicate('Drupe::Action::"Read"', "response");
+ expect(renderCondition(since(read, "30m", login))).toBe(
+ 'Drupe::Action::"Read"::response{} since within 30m Drupe::Action::"Login"::request{}',
+ );
+ });
+
+ test("a window is not optional — there is no arity that omits it", () => {
+ // @ts-expect-error — formerly() has no one-argument form
+ expect(() => formerly(login)).toThrow();
+ });
+
+ test("a macro body may defer the window to its call site", () => {
+ expect(renderCondition(formerly(macroWindow("?w"), macroCondition("?s")))).toBe("formerly within ?w ?s");
+ });
+});
+
+describe("exists, tp and the aggregates", () => {
+ test("exists binds one typed variable over a condition", () => {
+ const node = exists(typedBinder("total", "Long"), compare(varRef("total"), ">", 100));
+ expect(renderCondition(node)).toBe("exists (total: Long). total > 100");
+ });
+
+ test("count names its aggregation domain explicitly", () => {
+ const node = count(
+ [typedBinder("t", "Timepoint")],
+ formerly("1h", and(predicate('Ns::Action::"A"', "request"), tp("t"))),
+ );
+ expect(renderTerm(node)).toBe(
+ 'count for (t: Timepoint). where formerly within 1h (Ns::Action::"A"::request{} && tp(t))',
+ );
+ });
+
+ test("sum names both its bound variable and its domain", () => {
+ const node = sum(
+ "a",
+ [typedBinder("a", "Long"), typedBinder("t", "Timepoint")],
+ predicate('Ns::Action::"A"', "request", { "input.amount": varRef("a") }),
+ );
+ expect(renderTerm(node)).toBe(
+ 'sum a for (a: Long), (t: Timepoint). where Ns::Action::"A"::request{ input.amount: a }',
+ );
+ });
+
+ test("an aggregate with no for-list is refused", () => {
+ expect(() => count([], raw("x"))).toThrow(/at least one typed binder/);
+ });
+});
+
+// ── Precedence ─────────────────────────────────────────────────────
+//
+// The renderer parenthesises rather than relying on the reader knowing the
+// grammar's binding rules. Each of these is a place the tree and the surface
+// syntax would otherwise disagree.
+
+describe("parenthesisation", () => {
+ const a = predicate('Ns::Action::"A"', "request");
+ const b = predicate('Ns::Action::"B"', "request");
+ const c = predicate('Ns::Action::"C"', "request");
+
+ test("an && chain under formerly is parenthesised (atom position)", () => {
+ expect(renderCondition(formerly("1h", and(a, b)))).toBe(
+ 'formerly within 1h (Ns::Action::"A"::request{} && Ns::Action::"B"::request{})',
+ );
+ });
+
+ test("a predicate under formerly is not", () => {
+ expect(renderCondition(formerly("1h", a))).toBe('formerly within 1h Ns::Action::"A"::request{}');
+ });
+
+ test("! negates only its operand, so an && chain under it is parenthesised", () => {
+ expect(renderCondition(not(and(a, b)))).toBe(
+ '!(Ns::Action::"A"::request{} && Ns::Action::"B"::request{})',
+ );
+ expect(renderCondition(not(a))).toBe('!Ns::Action::"A"::request{}');
+ });
+
+ test("since's left operand is a neg_conjunct, so an && chain there is parenthesised", () => {
+ expect(renderCondition(since(and(a, b), "1h", c))).toBe(
+ '(Ns::Action::"A"::request{} && Ns::Action::"B"::request{}) since within 1h Ns::Action::"C"::request{}',
+ );
+ });
+
+ test("since needs no parentheses as an && operand", () => {
+ expect(renderCondition(and(since(a, "1h", b), c))).toBe(
+ 'Ns::Action::"A"::request{} since within 1h Ns::Action::"B"::request{} && Ns::Action::"C"::request{}',
+ );
+ });
+
+ test("exists binds maximally to the right, so it is fenced inside an && chain", () => {
+ const node = and(exists(typedBinder("n", "Long"), compare(varRef("n"), ">", 1)), a);
+ expect(renderCondition(node)).toBe('(exists (n: Long). n > 1) && Ns::Action::"A"::request{}');
+ });
+
+ test("an aggregate in comparison position is fenced off from the operator", () => {
+ const node = compare(count([typedBinder("t", "Timepoint")], a), "<", 5);
+ expect(renderCondition(node)).toBe(
+ '(count for (t: Timepoint). where Ns::Action::"A"::request{}) < 5',
+ );
+ });
+
+ test("a single-operand and() collapses instead of emitting a bare conjunct", () => {
+ expect(renderCondition(and(a))).toBe(renderCondition(a));
+ });
+
+ test("and() with nothing to conjoin is a construction error, not empty text", () => {
+ expect(() => and()).toThrow(/at least one operand/);
+ });
+});
+
+// ── Macro calls ────────────────────────────────────────────────────
+
+describe("macro calls", () => {
+ const a = predicate('Ns::Action::"A"', "request");
+
+ test("a call argument may be an interval, a condition or a term", () => {
+ expect(renderCondition(call("once", [interval("1h"), a]))).toBe(
+ 'once(1h, Ns::Action::"A"::request{})',
+ );
+ expect(renderCondition(call("is_small", [term("context.input.shares")]))).toBe(
+ "is_small(context.input.shares)",
+ );
+ });
+
+ test("the interval argument is bare — `within` belongs to the operator", () => {
+ expect(renderCondition(call("once", [interval("90m")]))).not.toContain("within");
+ });
+
+ test("the default library's aggregates are calls, not operators", () => {
+ expect(renderCondition(countWithin("1h", a))).toBe('count_within(1h, Ns::Action::"A"::request{})');
+ expect(renderCondition(sumWithin("amount", "1h", a))).toBe(
+ 'sum_within(amount, 1h, Ns::Action::"A"::request{})',
+ );
+ expect(renderCondition(countDistinctWithin("user", "24h", a))).toBe(
+ 'count_distinct_within(user, 24h, Ns::Action::"A"::request{})',
+ );
+ });
+});
+
+// ── The extension marker ───────────────────────────────────────────
+
+describe("the temporal marker", () => {
+ test("wraps a condition for embedding mid-expression", () => {
+ const marker = temporalMarker(formerly("1h", predicate('Ns::Action::"A"', "request")));
+ expect(marker).toBe('temporal { formerly within 1h Ns::Action::"A"::request{} }');
+ });
+});
+
+// ── The escape hatch ───────────────────────────────────────────────
+
+describe("raw()", () => {
+ test("passes text through, which is why DWDC012 reads the emitted file", () => {
+ expect(renderCondition(raw("formerly Ns::Action::\"A\"::request{}"))).toBe(
+ 'formerly Ns::Action::"A"::request{}',
+ );
+ });
+});
diff --git a/lexicons/cedar/src/dogwood/temporal.ts b/lexicons/cedar/src/dogwood/temporal.ts
new file mode 100644
index 0000000000..b6750ff388
--- /dev/null
+++ b/lexicons/cedar/src/dogwood/temporal.ts
@@ -0,0 +1,592 @@
+/**
+ * Typed builders for dogwood's temporal sub-language.
+ *
+ * These target the **parser primitives**, not the named aggregates. The #1657
+ * verification (and the correction comment on epic #1646) is explicit about
+ * why: `formerly`, `previous`, `since`, `exists`, `tp()`, `count for … where`
+ * and `sum … for … where` are the only temporal keywords in upstream's
+ * `extension/temporal/grammar.pest`. `count_within`, `sum_within`,
+ * `count_distinct_within` and `bind` are macros in `default_macros.dw` — a
+ * swappable standard library that a caller passing `--macros` replaces
+ * wholesale — and `once` is not even in that library, only in the examples.
+ *
+ * So the aggregates are expressible here as macro *calls* ({@link call}, and
+ * the convenience wrappers in `./macros.ts`), never as first-class operators.
+ * A call that resolves to nothing at the other end is a missing macro, which
+ * is a comprehensible failure; a first-class builder that silently emits a
+ * name the callee's library does not define is not.
+ *
+ * Everything below renders to the surface syntax the pest grammar accepts.
+ * Where the grammar's precedence would bind differently from the tree the
+ * author built, the renderer parenthesises — it never relies on the reader
+ * knowing that `!` binds tighter than `since`, or that an aggregate's `where`
+ * body is greedy.
+ */
+
+import { escapeCedarString } from "../policy-text";
+import {
+ renderWindow,
+ renderWindowValue,
+ window,
+ windowValue,
+ type TemporalWindow,
+ type WindowLike,
+ type WindowParam,
+ type WindowValue,
+} from "./window";
+
+/** What the three past-only operators accept: a window, or a macro's `?w`. */
+export type WindowArgument = WindowLike | WindowParam;
+
+// ── Names ─────────────────────────────────────────────────────────
+
+/** A bare binder or field name. */
+const IDENT = /^[A-Za-z_][A-Za-z0-9_]*$/;
+/** `?p` (call-site value splice) or `$t` (macro-introduced fresh binder). */
+const SIGIL = /^[?$][A-Za-z_][A-Za-z0-9_]*$/;
+/** `input.user`, `output.result` — the dotted path a predicate argument names. */
+const FIELD_PATH = /^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)*$/;
+/** `Drupe::Action::"Read"` — a qualified action with a quoted id. */
+const QUALIFIED_ACTION = /^[A-Za-z_][A-Za-z0-9_]*(::[A-Za-z_][A-Za-z0-9_]*)*::"[^"]*"$/;
+/** `String`, `Long`, `Timepoint`, `MyApp::OAuthUser`. */
+const TYPE_NAME = /^[A-Za-z_][A-Za-z0-9_]*(::[A-Za-z_][A-Za-z0-9_]*)*$/;
+
+function assertName(pattern: RegExp, value: string, what: string): string {
+ if (!pattern.test(value)) throw new Error(`dogwood: ${what} — got "${value}"`);
+ return value;
+}
+
+/**
+ * A binder position: a plain identifier, or a macro sigil.
+ *
+ * The sigils are legal only inside a macro body; upstream's well-formedness
+ * pass rejects them elsewhere. `./macros.ts` is where they belong, and it is
+ * what carries that warning to the author.
+ */
+export function binderName(value: string): string {
+ if (IDENT.test(value) || SIGIL.test(value)) return value;
+ throw new Error(
+ `dogwood: a binder must be an identifier, or a "?param"/"$binder" sigil inside a macro body — got "${value}"`,
+ );
+}
+
+// ── Terms ─────────────────────────────────────────────────────────
+
+/** `(x: T)` — a declaration site in an `exists` or a `for` list. */
+export interface TypedBinder {
+ readonly name: string;
+ readonly type: string;
+}
+
+/** `(t: Timepoint)`, `(amount: Long)`, `($t: Timepoint)` inside a macro. */
+export function typedBinder(name: string, type: string): TypedBinder {
+ return { name: binderName(name), type: assertName(TYPE_NAME, type, "a binder type must be a Cedar type name") };
+}
+
+/** Anything that renders in term position. */
+export type TemporalTerm = TermText | ArrayTerm | CountTerm | SumTerm | CallNode;
+
+/** A leaf term already in its surface form (a literal, a path, an entity UID). */
+export interface TermText {
+ readonly op: "term";
+ readonly text: string;
+}
+
+/** `[a, b, c]`. */
+export interface ArrayTerm {
+ readonly op: "array";
+ readonly items: readonly TemporalTerm[];
+}
+
+/** `count for (t: Timepoint). where φ`. */
+export interface CountTerm {
+ readonly op: "count";
+ readonly binders: readonly TypedBinder[];
+ readonly where: TemporalCondition;
+}
+
+/** `sum a for (a: Long), (t: Timepoint). where φ`. */
+export interface SumTerm {
+ readonly op: "sum";
+ readonly over: string;
+ readonly binders: readonly TypedBinder[];
+ readonly where: TemporalCondition;
+}
+
+/**
+ * What a builder accepts in term position.
+ *
+ * Numbers and booleans lift to literals because there is only one thing they
+ * can mean. A bare `string` deliberately does not: `"alice"` is a Cedar string
+ * literal and `alice` is a binder reference, and guessing which one the author
+ * meant is how a policy silently stops matching. Say which with {@link str},
+ * {@link varRef}, {@link ctx} or {@link entityUid}.
+ */
+export type TermInput = TemporalTerm | number | boolean;
+
+function liftTerm(value: TermInput): TemporalTerm {
+ if (typeof value === "number") return int(value);
+ if (typeof value === "boolean") return bool(value);
+ return value;
+}
+
+/** A raw term, emitted verbatim. The escape hatch for a shape not modelled here. */
+export function term(text: string): TermText {
+ return { op: "term", text };
+}
+
+/** A Cedar string literal: `"alice"`. */
+export function str(value: string): TermText {
+ return term(`"${escapeCedarString(value)}"`);
+}
+
+/** An integer literal. Upstream's grammar admits a leading `-`. */
+export function int(value: number): TermText {
+ if (!Number.isInteger(value)) {
+ throw new Error(`dogwood: an integer term must be a whole number — use decimalOf() for ${value}`);
+ }
+ return term(String(value));
+}
+
+/** `true` / `false`. */
+export function bool(value: boolean): TermText {
+ return term(value ? "true" : "false");
+}
+
+/** `decimal("1.50")` — Cedar's decimal constructor, which dogwood admits as a term. */
+export function decimalOf(value: string): TermText {
+ return term(`decimal("${escapeCedarString(value)}")`);
+}
+
+/** `context.input.user` — a field of the request context record. */
+export function ctx(path: string): TermText {
+ assertName(FIELD_PATH, path, "a context path must be dotted identifiers");
+ return term(`context.${path}`);
+}
+
+/** `principal`, `resource`, `principal.dept` — the request scope entities. */
+export function scopeRef(root: "principal" | "resource", ...attrs: string[]): TermText {
+ for (const attr of attrs) assertName(IDENT, attr, "a scope attribute must be an identifier");
+ return term([root, ...attrs].join("."));
+}
+
+/** `Drupe::OAuthUser::"alice"` — an entity UID literal. */
+export function entityUid(uid: string): TermText {
+ assertName(QUALIFIED_ACTION, uid, 'an entity UID looks like Ns::Type::"id"');
+ return term(uid);
+}
+
+/** A bare binder reference — a `for`-declared variable, or a macro sigil. */
+export function varRef(name: string): TermText {
+ return term(binderName(name));
+}
+
+/** `*` — the grammar's wildcard term. */
+export function wildcard(): TermText {
+ return term("*");
+}
+
+/** `[a, b]`. */
+export function arrayOf(...items: TermInput[]): ArrayTerm {
+ return { op: "array", items: items.map(liftTerm) };
+}
+
+/**
+ * `count for (t: Timepoint). where φ` — the primitive behind `count_within`.
+ *
+ * The `for` list is the aggregation domain and is mandatory in the grammar,
+ * so it is a required argument here too.
+ */
+export function count(binders: TypedBinder[], where: TemporalCondition): CountTerm {
+ if (binders.length === 0) throw new Error("dogwood: count needs at least one typed binder in its for-list");
+ return { op: "count", binders, where };
+}
+
+/** `sum a for (a: Long), (t: Timepoint). where φ` — the primitive behind `sum_within`. */
+export function sum(over: string, binders: TypedBinder[], where: TemporalCondition): SumTerm {
+ if (binders.length === 0) throw new Error("dogwood: sum needs at least one typed binder in its for-list");
+ return { op: "sum", over: binderName(over), binders, where };
+}
+
+// ── Conditions ────────────────────────────────────────────────────
+
+/** Anything that renders in condition position. */
+export type TemporalCondition =
+ | PredicateNode
+ | FormerlyNode
+ | PreviousNode
+ | SinceNode
+ | ExistsNode
+ | TpNode
+ | AndNode
+ | NotNode
+ | ComparisonNode
+ | CallNode
+ | SigilCondition
+ | RawCondition;
+
+/** `Drupe::Action::"Login"::response{ input.user: context.input.user }`. */
+export interface PredicateNode {
+ readonly op: "predicate";
+ readonly action: string;
+ readonly kind: string;
+ readonly args: ReadonlyArray<{ readonly path: string; readonly value: TemporalTerm }>;
+}
+
+/** `formerly within 1h φ`. */
+export interface FormerlyNode {
+ readonly op: "formerly";
+ readonly window: WindowValue;
+ readonly body: TemporalCondition;
+}
+
+/** `previous within 30s φ`. */
+export interface PreviousNode {
+ readonly op: "previous";
+ readonly window: WindowValue;
+ readonly body: TemporalCondition;
+}
+
+/** `φ since within 1h ψ` — infix, with the window on the operator. */
+export interface SinceNode {
+ readonly op: "since";
+ readonly left: TemporalCondition;
+ readonly window: WindowValue;
+ readonly right: TemporalCondition;
+}
+
+/** `exists (total: Long). φ`. */
+export interface ExistsNode {
+ readonly op: "exists";
+ readonly binder: TypedBinder;
+ readonly body: TemporalCondition;
+}
+
+/** `tp(t)` — binds the timepoint under evaluation. */
+export interface TpNode {
+ readonly op: "tp";
+ readonly binder: string;
+}
+
+/** `φ && ψ`. */
+export interface AndNode {
+ readonly op: "and";
+ readonly operands: readonly TemporalCondition[];
+}
+
+/** `!φ`. */
+export interface NotNode {
+ readonly op: "not";
+ readonly body: TemporalCondition;
+}
+
+/** `a == b`, `0 < count …`. */
+export interface ComparisonNode {
+ readonly op: "compare";
+ readonly left: TemporalTerm;
+ readonly operator: ComparisonOperator;
+ readonly right: TemporalTerm;
+}
+
+/** The six operators `cmp_op` admits. */
+export type ComparisonOperator = "==" | "!=" | "<" | "<=" | ">" | ">=";
+
+/** A macro invocation — `once(1h, φ)`. Legal in both condition and term position. */
+export interface CallNode {
+ readonly op: "call";
+ readonly name: string;
+ readonly args: readonly MacroArg[];
+}
+
+/** `1h` as a macro-call argument — bare, with no `within` keyword. */
+export interface IntervalArg {
+ readonly op: "interval";
+ readonly window: TemporalWindow;
+}
+
+/** What a macro call takes: an interval, a condition, or a term. */
+export type MacroArg = IntervalArg | TemporalCondition | TemporalTerm;
+
+/**
+ * Temporal source text emitted verbatim.
+ *
+ * The one builder that can produce something the walls exist to catch — a
+ * `formerly` with no window, an event kind the schema never declared. That is
+ * deliberate: an escape hatch nobody can reach makes the walls untestable, and
+ * DWDC012 reads the serialized text precisely because this exists.
+ */
+export interface RawCondition {
+ readonly op: "raw";
+ readonly text: string;
+}
+
+/**
+ * `?s` — a macro parameter standing for an entire condition.
+ *
+ * Its own node rather than a {@link RawCondition} because the grammar treats
+ * it as an atom (`refinable = (predicate | sigil_cond) ~ field_block*`), so
+ * `formerly within ?w ?s` needs no parentheses where arbitrary raw text would.
+ * Build one with `macroCondition()` in `./macros.ts`, which is where the rule
+ * that sigils are legal only inside a macro body is documented.
+ */
+export interface SigilCondition {
+ readonly op: "sigil";
+ readonly param: string;
+}
+
+// ── Condition builders ────────────────────────────────────────────
+
+/**
+ * `Ns::Action::"Name"::kind{ field: term, … }`.
+ *
+ * The event kind is mandatory in the grammar and author-defined in practice —
+ * `request`/`response`/`error` are the conventional kinds the default event
+ * schema declares, not a fixed set. Which kinds are legal for a given policy
+ * set is the emitted `.dwschema`'s business, and DWDC010's.
+ */
+export function predicate(
+ action: string,
+ kind: string,
+ args: Record = {},
+): PredicateNode {
+ assertName(QUALIFIED_ACTION, action, 'a predicate action looks like Ns::Action::"Name"');
+ assertName(IDENT, kind, "an event kind must be an identifier");
+ return {
+ op: "predicate",
+ action,
+ kind,
+ args: Object.entries(args).map(([path, value]) => ({
+ path: assertName(FIELD_PATH, path, "a predicate field path must be dotted identifiers"),
+ value: liftTerm(value),
+ })),
+ };
+}
+
+/** `formerly within φ` — held at some point in the window. */
+export function formerly(w: WindowArgument, body: TemporalCondition): FormerlyNode {
+ return { op: "formerly", window: windowValue(w), body };
+}
+
+/** `previous within φ` — held at the immediately preceding timepoint in the window. */
+export function previous(w: WindowArgument, body: TemporalCondition): PreviousNode {
+ return { op: "previous", window: windowValue(w), body };
+}
+
+/** `φ since within ψ` — φ has held continuously since ψ, inside the window. */
+export function since(left: TemporalCondition, w: WindowArgument, right: TemporalCondition): SinceNode {
+ return { op: "since", left, window: windowValue(w), right };
+}
+
+/** `exists (name: Type). φ`. */
+export function exists(binder: TypedBinder, body: TemporalCondition): ExistsNode {
+ return { op: "exists", binder, body };
+}
+
+/** `tp(t)`. */
+export function tp(binder: string): TpNode {
+ return { op: "tp", binder: binderName(binder) };
+}
+
+/** `φ && ψ && …`. A single operand collapses to itself. */
+export function and(...operands: TemporalCondition[]): TemporalCondition {
+ if (operands.length === 0) throw new Error("dogwood: and() needs at least one operand");
+ if (operands.length === 1) return operands[0];
+ return { op: "and", operands };
+}
+
+/** `!φ`. */
+export function not(body: TemporalCondition): NotNode {
+ return { op: "not", body };
+}
+
+/** `a b`. */
+export function compare(left: TermInput, operator: ComparisonOperator, right: TermInput): ComparisonNode {
+ return { op: "compare", left: liftTerm(left), operator, right: liftTerm(right) };
+}
+
+/**
+ * A macro invocation.
+ *
+ * Nothing here checks that the macro exists: the library is `--macros`, chosen
+ * by whoever runs `dogwood validate`, and chant is not that. `./macros.ts`
+ * carries typed wrappers for the four the default library ships.
+ */
+export function call(name: string, args: MacroArg[] = []): CallNode {
+ assertName(IDENT, name, "a macro name must be an identifier");
+ return { op: "call", name, args };
+}
+
+/** `1h` in macro-call argument position — the interval without the `within`. */
+export function interval(w: WindowLike): IntervalArg {
+ return { op: "interval", window: window(w) };
+}
+
+/** Temporal source text, passed through untouched. See {@link RawCondition}. */
+export function raw(text: string): RawCondition {
+ return { op: "raw", text };
+}
+
+/** `?s` in condition position. See {@link SigilCondition}. */
+export function sigilCondition(param: string): SigilCondition {
+ if (!SIGIL.test(param)) throw new Error(`dogwood: a condition sigil looks like "?s" — got "${param}"`);
+ return { op: "sigil", param };
+}
+
+// ── Rendering ─────────────────────────────────────────────────────
+
+function isTerm(node: MacroArg): node is TemporalTerm {
+ return node.op === "term" || node.op === "array" || node.op === "count" || node.op === "sum";
+}
+
+function isAggregate(t: TemporalTerm): boolean {
+ return t.op === "count" || t.op === "sum";
+}
+
+/** Render a term. */
+export function renderTerm(t: TemporalTerm): string {
+ switch (t.op) {
+ case "term":
+ return t.text;
+ case "array":
+ return `[${t.items.map(renderTerm).join(", ")}]`;
+ case "count":
+ return `count ${renderForBinders(t.binders)} where ${renderCondition(t.where)}`;
+ case "sum":
+ return `sum ${t.over} ${renderForBinders(t.binders)} where ${renderCondition(t.where)}`;
+ case "call":
+ return renderCall(t);
+ }
+}
+
+function renderForBinders(binders: readonly TypedBinder[]): string {
+ return `for ${binders.map((b) => `(${b.name}: ${b.type})`).join(", ")}.`;
+}
+
+/**
+ * A comparison operand.
+ *
+ * An aggregate's `where` body is greedy, so `count for (…). where φ == 3`
+ * reads `== 3` as part of φ. Upstream's `paren_agg` rule exists for exactly
+ * this and is always legal, so aggregates and macro calls are parenthesised on
+ * both sides rather than only where the greed would actually bite — the
+ * emitted text should not depend on which side of the operator it landed on.
+ */
+function renderComparisonOperand(t: TemporalTerm): string {
+ return isAggregate(t) || t.op === "call" ? `(${renderTerm(t)})` : renderTerm(t);
+}
+
+function renderCall(node: CallNode): string {
+ const args = node.args.map((arg) => {
+ if (arg.op === "interval") return renderWindow(arg.window);
+ if (isTerm(arg)) return renderTerm(arg);
+ return renderCondition(arg);
+ });
+ return `${node.name}(${args.join(", ")})`;
+}
+
+/**
+ * An `atom` — the operand of `formerly`, `previous` and the right of `since`.
+ *
+ * The grammar's `atom` is `"(" condition ")" | tp_op | call | refinable |
+ * comparison`; everything else has to be parenthesised.
+ */
+function renderAtom(node: TemporalCondition): string {
+ switch (node.op) {
+ case "predicate":
+ case "sigil":
+ case "tp":
+ case "call":
+ case "compare":
+ return renderCondition(node);
+ default:
+ return `(${renderCondition(node)})`;
+ }
+}
+
+/**
+ * A `neg_conjunct` — what `!` negates, and what sits left of `since`.
+ *
+ * `!` binds tighter than `since` and `&&`, so `!a since within W b` negates
+ * only `a`. Anything looser gets parentheses.
+ */
+function renderNegConjunct(node: TemporalCondition): string {
+ switch (node.op) {
+ case "and":
+ case "since":
+ case "exists":
+ return `(${renderCondition(node)})`;
+ default:
+ return renderCondition(node);
+ }
+}
+
+/**
+ * A `conjunct_or_since` — one operand of an `&&` chain.
+ *
+ * `since` is allowed here bare (it is part of the same rule). `exists` binds
+ * maximally to the right, so an unparenthesised one would swallow every
+ * operand after it.
+ */
+function renderConjunct(node: TemporalCondition): string {
+ switch (node.op) {
+ case "and":
+ case "exists":
+ return `(${renderCondition(node)})`;
+ default:
+ return renderCondition(node);
+ }
+}
+
+/** Render a temporal condition to the surface syntax the pest grammar accepts. */
+export function renderCondition(node: TemporalCondition): string {
+ switch (node.op) {
+ case "raw":
+ return node.text;
+
+ case "sigil":
+ return node.param;
+
+ case "predicate": {
+ const args = node.args.map((a) => `${a.path}: ${renderTerm(a.value)}`).join(", ");
+ return `${node.action}::${node.kind}{${args.length > 0 ? ` ${args} ` : ""}}`;
+ }
+
+ case "formerly":
+ return `formerly within ${renderWindowValue(node.window)} ${renderAtom(node.body)}`;
+
+ case "previous":
+ return `previous within ${renderWindowValue(node.window)} ${renderAtom(node.body)}`;
+
+ case "since":
+ return `${renderNegConjunct(node.left)} since within ${renderWindowValue(node.window)} ${renderAtom(node.right)}`;
+
+ case "exists":
+ return `exists (${node.binder.name}: ${node.binder.type}). ${renderCondition(node.body)}`;
+
+ case "tp":
+ return `tp(${node.binder})`;
+
+ case "and":
+ return node.operands.map(renderConjunct).join(" && ");
+
+ case "not":
+ return `!${renderNegConjunct(node.body)}`;
+
+ case "compare":
+ return `${renderComparisonOperand(node.left)} ${node.operator} ${renderComparisonOperand(node.right)}`;
+
+ case "call":
+ return renderCall(node);
+ }
+}
+
+/**
+ * `temporal { … }` — the extension marker.
+ *
+ * It is a `primary` in the Cedar expression grammar as well as a clause tag,
+ * so this is also how a temporal condition is embedded mid-expression:
+ * `when { is_small(context.input.shares) && temporal { once(1h, …) } }`.
+ */
+export function temporalMarker(condition: TemporalCondition): string {
+ return `temporal { ${renderCondition(condition)} }`;
+}
diff --git a/lexicons/cedar/src/dogwood/testdata/custom-kinds.dwschema b/lexicons/cedar/src/dogwood/testdata/custom-kinds.dwschema
new file mode 100644
index 0000000000..f80586300b
--- /dev/null
+++ b/lexicons/cedar/src/dogwood/testdata/custom-kinds.dwschema
@@ -0,0 +1,17 @@
+// Adapted from dogwood-policy/dogwood@5063bcc2d6d6cf5024d1b0498e6cc8ef52cbcf0c (Apache-2.0):
+// dogwood-docs/examples/login_attempt_custom_kind/event.dwschema
+// Upstream's shape; the bytes are what chant's typed builders emit.
+
+// Author-defined event kinds — `attempt` decides, `outcome` is history — and
+// a renamed injected principal field.
+
+decision event ::attempt {
+ ...inputs(A),
+ actor: principalType(A),
+}
+
+event ::outcome {
+ ...inputs(A),
+ ...outputs(A),
+ actor: principalType(A),
+}
diff --git a/lexicons/cedar/src/dogwood/testdata/default-macros.dw b/lexicons/cedar/src/dogwood/testdata/default-macros.dw
new file mode 100644
index 0000000000..2743bc8327
--- /dev/null
+++ b/lexicons/cedar/src/dogwood/testdata/default-macros.dw
@@ -0,0 +1,23 @@
+// Adapted from dogwood-policy/dogwood@5063bcc2d6d6cf5024d1b0498e6cc8ef52cbcf0c (Apache-2.0):
+// dogwood-language/configuration/default_macros.dw
+// Upstream's shape; the bytes are what chant's typed builders emit.
+
+// Counts the timepoints within window `?w` at which condition `?s` held.
+def temporal count_within(?w, ?s) {
+ count for ($t: Timepoint). where (formerly within ?w (?s && tp($t)))
+};
+
+// Sums the numeric value `?a` over occurrences of `?body` within window `?w`.
+def temporal sum_within(?a, ?w, ?body) {
+ sum ?a for (?a: Long), ($t: Timepoint). where (formerly within ?w (?body && tp($t)))
+};
+
+// Counts the distinct key values `?k` for which `?s` held within window `?w`.
+def temporal count_distinct_within(?k, ?w, ?s) {
+ count for (?k: String). where (formerly within ?w ?s)
+};
+
+// A "let"-style binder: names an aggregate result `?n` and uses it in `?B`.
+def temporal bind(?n, ?A, ?B) {
+ exists (?n: Long). (?A == ?n && ?B)
+};
diff --git a/lexicons/cedar/src/dogwood/testdata/max-window-raised.dwschema b/lexicons/cedar/src/dogwood/testdata/max-window-raised.dwschema
new file mode 100644
index 0000000000..965d4e698f
--- /dev/null
+++ b/lexicons/cedar/src/dogwood/testdata/max-window-raised.dwschema
@@ -0,0 +1,25 @@
+// Adapted from dogwood-policy/dogwood@5063bcc2d6d6cf5024d1b0498e6cc8ef52cbcf0c (Apache-2.0):
+// dogwood-docs/examples/max_window_raised/event.dwschema
+// Upstream's shape; the bytes are what chant's typed builders emit.
+
+// Raises the look-back cap from the 24h default to 30 days. The directive
+// must come first, before any event declaration.
+//
+// No pinned field: this schema correlates across principals on purpose.
+
+max_window = 30d
+
+decision event ::request {
+ ...inputs(A),
+ callerPrincipal: principalType(A),
+ callerResource: resourceType(A),
+ requestId: String,
+}
+
+event ::response {
+ ...inputs(A),
+ ...outputs(A),
+ callerPrincipal: principalType(A),
+ callerResource: resourceType(A),
+ requestId: String,
+}
diff --git a/lexicons/cedar/src/dogwood/testdata/pinned.dwschema b/lexicons/cedar/src/dogwood/testdata/pinned.dwschema
new file mode 100644
index 0000000000..179e11f494
--- /dev/null
+++ b/lexicons/cedar/src/dogwood/testdata/pinned.dwschema
@@ -0,0 +1,31 @@
+// Adapted from dogwood-policy/dogwood@5063bcc2d6d6cf5024d1b0498e6cc8ef52cbcf0c (Apache-2.0):
+// dogwood-language/configuration/event-schemas/pinned.dwschema
+// Upstream's shape; the bytes are what chant's typed builders emit.
+
+// The default event-schema shape: request/response/error, each correlated to
+// the deciding request's principal.
+
+decision event ::request {
+ ...inputs(A),
+ pin callerPrincipal: principalType(A) = principal,
+ callerResource: resourceType(A),
+ requestId: String,
+ sessionId: String,
+}
+
+event ::response {
+ ...inputs(A),
+ ...outputs(A),
+ pin callerPrincipal: principalType(A) = principal,
+ callerResource: resourceType(A),
+ requestId: String,
+ sessionId: String,
+}
+
+event ::error {
+ ...inputs(A),
+ pin callerPrincipal: principalType(A) = principal,
+ callerResource: resourceType(A),
+ requestId: String,
+ sessionId: String,
+}
diff --git a/lexicons/cedar/src/dogwood/testdata/temporal-policies.dw b/lexicons/cedar/src/dogwood/testdata/temporal-policies.dw
new file mode 100644
index 0000000000..95a5906552
--- /dev/null
+++ b/lexicons/cedar/src/dogwood/testdata/temporal-policies.dw
@@ -0,0 +1,53 @@
+// Adapted from dogwood-policy/dogwood@5063bcc2d6d6cf5024d1b0498e6cc8ef52cbcf0c (Apache-2.0):
+// dogwood-docs/examples/read_after_login/policy.dw
+// dogwood-docs/examples/temporal_sum_formerly_transfer/policy.dw
+// dogwood-docs/examples/read_heartbeat_since_login_30s/policy.dw
+// dogwood-docs/examples/temporal_count_formerly_login/policy.dw
+// Upstream's shape; the bytes are what chant's typed builders emit.
+
+// Sums the numeric value `?a` over occurrences of `?body` within window `?w`.
+def temporal sum_formerly(?a, ?w, ?body) {
+ sum ?a for (?a: Long), ($t: Timepoint). where formerly within ?w (?body && tp($t))
+};
+
+@id("read_after_login")
+permit (
+ principal,
+ action == Drupe::Action::"Read",
+ resource
+)
+when temporal {
+ formerly within 1h Drupe::Action::"Login"::response{ input.user: context.input.user }
+};
+
+@id("transfer_sum_over_100")
+permit (
+ principal,
+ action == Drupe::Action::"Alert",
+ resource
+)
+when temporal {
+ exists (total: Long). (sum_formerly(a, 1h, Drupe::Action::"Transfer"::request{ input.user: _, input.amount: a })) == total && total > 100
+};
+
+@id("no_tool_after_sensitive_read")
+forbid (
+ principal,
+ action == Drupe::Action::"Invoke",
+ resource
+)
+when guardrails { context.input.tool != "audit" }
+when temporal {
+ Drupe::Action::"Read"::response{ output.classification: c } since within 30m Drupe::Action::"Login"::request{}
+}
+unless { principal in Drupe::Group::"breakglass" };
+
+@id("rate_limited")
+permit (
+ principal,
+ action == Drupe::Action::"Transfer",
+ resource
+)
+when temporal {
+ (count for (t: Timepoint). where formerly within 15m (Drupe::Action::"Transfer"::request{} && tp(t))) < 5
+};
diff --git a/lexicons/cedar/src/dogwood/upstream.ts b/lexicons/cedar/src/dogwood/upstream.ts
new file mode 100644
index 0000000000..4671ba4ba7
--- /dev/null
+++ b/lexicons/cedar/src/dogwood/upstream.ts
@@ -0,0 +1,41 @@
+/**
+ * The dogwood upstream pin.
+ *
+ * Not a `upstreamPin` on the plugin: that slot belongs to the cedar grammar
+ * (`@cedar-policy/cedar-wasm`, see `../spec/pin.ts`), and self-upgrade tooling
+ * bumps exactly one thing per lexicon. Dogwood's pin is a git SHA recorded by
+ * #1657, because upstream has no version to key off — zero tags, zero
+ * releases, and a workspace version of `1.0.0` that is an Amazon-internal
+ * package artifact every future sync will also report.
+ *
+ * The blob hashes are the narrow content pin the #1657 report recommends. The
+ * whole tree hash moves on every sync including docs-only ones, which makes it
+ * too noisy to gate on; these seven files are the surface chant actually
+ * depends on. The three `.pest` grammars pin the language, `default_macros.dw`
+ * pins the standard aggregate library (which is a file a sync can edit and a
+ * caller can replace with `--macros`), and the three `dogwood-cli/src` files
+ * pin the JSON report structs that are #1659's integration surface.
+ *
+ * Movement risk is structural, not incidental: content arrives as squashed
+ * "Sync from internal source" commits from a publish bot, against a repository
+ * nobody outside Amazon can see, with no changelog and no version bump.
+ */
+
+/** The pinned upstream revision and the files chant's surface is built against. */
+export const DOGWOOD_UPSTREAM = {
+ owner: "dogwood-policy",
+ repo: "dogwood",
+ /** Default-branch SHA verified in #1657 (committed 2026-08-06). */
+ revision: "5063bcc2d6d6cf5024d1b0498e6cc8ef52cbcf0c",
+ license: "Apache-2.0",
+ /** Git blob hashes at {@link revision} — the narrow content pin. */
+ contents: {
+ "dogwood-language/src/parser/grammar.pest": "adb0801303ee1b735585fe22a5d85175ecf6772c",
+ "dogwood-language/src/extension/temporal/grammar.pest": "dc31fe1634b5c37173f0a999619e9834069b7a22",
+ "dogwood-language/src/event_schema/grammar.pest": "bd3b064447dc0d09cc2f8eb28a7c657e746cc8a2",
+ "dogwood-language/configuration/default_macros.dw": "ecd67e5edcd566aa66b05ad51bc472afbaf22a7a",
+ "dogwood-cli/src/ops.rs": "2924c7eb0e569a745ff19c2d84cbba782fc56502",
+ "dogwood-cli/src/main.rs": "bfd68c9ff05883ed48e5738f658b5925542d817d",
+ "dogwood-cli/src/error.rs": "43f12afbbf25ad94e25130c83227eefd86f8d516",
+ },
+} as const;
diff --git a/lexicons/cedar/src/dogwood/window.ts b/lexicons/cedar/src/dogwood/window.ts
new file mode 100644
index 0000000000..2c29e2366a
--- /dev/null
+++ b/lexicons/cedar/src/dogwood/window.ts
@@ -0,0 +1,124 @@
+/**
+ * Temporal windows — the one thing dogwood's past-only operators cannot omit.
+ *
+ * `formerly`, `previous` and `since` all take a mandatory `within `
+ * clause; the unit is one of `s`, `m`, `h`, `d` and nothing else. Upstream's
+ * `temporal/grammar.pest` spells that out:
+ *
+ * ```
+ * within = { "within" ~ within_payload }
+ * within_payload = { param_ref | (integer ~ time_unit) }
+ * time_unit = { "s" | "m" | "h" | "d" }
+ * ```
+ *
+ * Typing the window as a value rather than as free text is what makes
+ * "a `formerly` without a window" unrepresentable in the builders (#1658's
+ * third lint wall) — you cannot call {@link formerly} without one.
+ *
+ * The `param_ref` arm (`within ?w`) is legal only inside a macro body; it is
+ * modelled by {@link MacroWindow} rather than by this type, so an ordinary
+ * policy cannot accidentally emit a sigil the expander would reject.
+ */
+
+/** The four units upstream's grammar admits. Anything else does not parse. */
+export type TimeUnit = "s" | "m" | "h" | "d";
+
+/** A `within` payload: a positive integer and one of the four units. */
+export interface TemporalWindow {
+ readonly value: number;
+ readonly unit: TimeUnit;
+}
+
+/**
+ * A window as written in a `.dw` file (`"1h"`, `"30m"`, `"7d"`).
+ *
+ * The template-literal arm means `formerly("1h", …)` type-checks and
+ * `formerly("1w", …)` does not, without anyone writing a runtime check first.
+ */
+export type WindowLike = TemporalWindow | `${number}${TimeUnit}`;
+
+/**
+ * `within ?w` — a window a macro takes as a parameter.
+ *
+ * The other arm of upstream's `within_payload`. Legal only inside a macro
+ * body; the expander resolves it against the call site's bare interval
+ * argument (`once(1h, …)`), which is why the call side has no `within`.
+ */
+export interface WindowParam {
+ readonly param: string;
+}
+
+/** Either a concrete window or a macro parameter standing in for one. */
+export type WindowValue = TemporalWindow | WindowParam;
+
+const WINDOW_TEXT = /^(\d+)([smhd])$/;
+const PARAM_TEXT = /^\?[A-Za-z_][A-Za-z0-9_]*$/;
+
+/** True when the payload is `?w` rather than `1h`. */
+export function isWindowParam(value: WindowValue): value is WindowParam {
+ return "param" in value;
+}
+
+/**
+ * `within ?w` inside a macro body.
+ *
+ * Exported from `./macros.ts` too, which is where the sigil rules are
+ * documented and where a reader looking for it will be.
+ */
+export function windowParam(param: string): WindowParam {
+ if (!PARAM_TEXT.test(param)) {
+ throw new Error(`dogwood: a window parameter carries the "?" sigil — got "${param}"`);
+ }
+ return { param };
+}
+
+/** Seconds in one of each unit — the scale `max_window` comparisons run on. */
+const UNIT_SECONDS: Record = { s: 1, m: 60, h: 3600, d: 86400 };
+
+/** Narrow a {@link WindowLike} to the structured form, validating as it goes. */
+export function window(value: WindowLike): TemporalWindow {
+ if (typeof value !== "string") {
+ if (!Number.isInteger(value.value) || value.value < 0) {
+ throw new Error(`dogwood: a temporal window must be a non-negative integer, got ${String(value.value)}`);
+ }
+ if (!(value.unit in UNIT_SECONDS)) {
+ throw new Error(`dogwood: a temporal window unit must be s, m, h or d, got "${String(value.unit)}"`);
+ }
+ return { value: value.value, unit: value.unit };
+ }
+
+ const match = WINDOW_TEXT.exec(value);
+ if (!match) {
+ throw new Error(`dogwood: "${value}" is not a temporal window — write an integer and one of s, m, h, d (for example "1h")`);
+ }
+ return { value: Number(match[1]), unit: match[2] as TimeUnit };
+}
+
+/** `1h` — the surface form, in a `within` clause or as a macro-call argument. */
+export function renderWindow(value: WindowLike): string {
+ const w = window(value);
+ return `${w.value}${w.unit}`;
+}
+
+/** A `within` payload: `1h`, or the `?w` a macro body defers to its call site. */
+export function renderWindowValue(value: WindowValue): string {
+ return isWindowParam(value) ? value.param : renderWindow(value);
+}
+
+/** Narrow a window argument, letting a `?w` parameter through unchanged. */
+export function windowValue(value: WindowLike | WindowParam): WindowValue {
+ return typeof value === "object" && "param" in value ? windowParam(value.param) : window(value);
+}
+
+/** The window in seconds, so `90m` and `1h` are comparable to a `max_window`. */
+export function windowSeconds(value: WindowLike): number {
+ const w = window(value);
+ return w.value * UNIT_SECONDS[w.unit];
+}
+
+/**
+ * Upstream's fallback cap. `ServiceSchema::defaults()` and an event schema
+ * with no `max_window` directive both look back at most 24 hours, per the
+ * comment atop `event_schema/grammar.pest` ("absent → a 24h default").
+ */
+export const DEFAULT_MAX_WINDOW: TemporalWindow = { value: 24, unit: "h" };
diff --git a/lexicons/cedar/src/index.ts b/lexicons/cedar/src/index.ts
index d428c40ffc..7863f4fad1 100644
--- a/lexicons/cedar/src/index.ts
+++ b/lexicons/cedar/src/index.ts
@@ -54,6 +54,30 @@ export type { CedarGenerateOptions, CedarGenerateResult } from "./import/generat
export { CedarTemplateParser, CedarTemplateGenerator } from "./import/adapter";
export { detectTemplate } from "./detect";
+// The dogwood temporal dialect (#1658) — typed temporal builders, the `.dw`
+// serializer leg, `.dwschema` event schemas. Pre-release; see ./dogwood.
+//
+// Namespaced rather than flattened: the temporal sub-language's builders are
+// named after its own grammar (`and`, `not`, `count`, `sum`, `str`, `field`,
+// `record`, `window`), and spilling those into the package root would collide
+// with a schema-generated entity class the moment someone declares one. The
+// three entity classes are re-exported flat because that is what a policy file
+// names.
+export * as dogwood from "./dogwood/index";
+export {
+ DOGWOOD_EVENT_SCHEMA_FILENAME,
+ DOGWOOD_EVENT_SCHEMA_TYPE,
+ DOGWOOD_MACRO_FILENAME,
+ DOGWOOD_MACRO_LIBRARY_TYPE,
+ DOGWOOD_POLICY_FILENAME,
+ DOGWOOD_POLICY_TYPE,
+ TemporalEventSchema,
+ TemporalMacroLibrary,
+ TemporalPolicy,
+} from "./dogwood/policy";
+export type { EventSchemaProps, MacroLibraryProps, TemporalPolicyProps } from "./dogwood/policy";
+export { DOGWOOD_UPSTREAM } from "./dogwood/upstream";
+
// Lint rules
export { rules as cedarLintRules } from "./lint/rules";
diff --git a/lexicons/cedar/src/lint/audit-catalog.ts b/lexicons/cedar/src/lint/audit-catalog.ts
index a8deaa0377..d5687f2093 100644
--- a/lexicons/cedar/src/lint/audit-catalog.ts
+++ b/lexicons/cedar/src/lint/audit-catalog.ts
@@ -127,4 +127,44 @@ export const cedarAuditCatalog: Record = {
'Name the actions the grant needs (action == Action::"read", or action in [ … ]) so it does not widen as the schema gains actions.',
{ category: "security" },
),
+
+ // ── The dogwood dialect (DWD) ──────────────────────────────────
+ //
+ // A second id family under the same lexicon, declared on the serializer as
+ // `extraRulePrefixes` (#1349's mechanism, the way k8s owns ARGO and FLUX).
+ // Dogwood is a dialect of Cedar rather than a peer language — a `.dw` file
+ // stripped of Cedar semantics is meaningless — so its checks ship here, and
+ // its ids are their own family so a reader can tell which surface bit them.
+ DWDC010: auditRule(
+ "DWDC010",
+ "merge-worthy",
+ "guidance",
+ "Dogwood temporal predicate names an undeclared event kind",
+ "Declare the event kind in the emitted .dwschema, or correct the predicate to a kind the schema derives — upstream rejects the policy set otherwise.",
+ { category: "correctness" },
+ ),
+ DWDC011: auditRule(
+ "DWDC011",
+ "merge-worthy",
+ "guidance",
+ "Dogwood temporal window exceeds the event schema's max_window",
+ "Shorten the window, or raise max_window in the event schema. With no schema emitted the cap is upstream's 24h default.",
+ { category: "correctness" },
+ ),
+ DWDC012: auditRule(
+ "DWDC012",
+ "merge-worthy",
+ "guidance",
+ "Dogwood formerly/previous/since is missing its window",
+ "Give the operator a `within ` window — all three past-only operators require one. The typed builders take it as an argument.",
+ { category: "correctness" },
+ ),
+ DWDS010: auditRule(
+ "DWDS010",
+ "report-only",
+ "guidance",
+ "Dogwood event schema pins nothing, widening every temporal predicate",
+ "Pin a field to the deciding request (pin callerPrincipal: principalType(A) = principal), or record that cross-principal correlation is the intent — supplying any event schema opts out of upstream's default pin.",
+ { category: "security" },
+ ),
};
diff --git a/lexicons/cedar/src/lint/post-synth/dwd-post-synth.test.ts b/lexicons/cedar/src/lint/post-synth/dwd-post-synth.test.ts
new file mode 100644
index 0000000000..b9e6ee5a61
--- /dev/null
+++ b/lexicons/cedar/src/lint/post-synth/dwd-post-synth.test.ts
@@ -0,0 +1,256 @@
+/**
+ * The DWD walls.
+ *
+ * Each check reads the emitted text, so every case here is built as a
+ * `PostSynthContext` holding files rather than by driving the serializer —
+ * that is the same shape `chant audit` hands them when it runs over a
+ * checked-in `.dw` chant never wrote.
+ */
+import { describe, test, expect } from "vitest";
+import type { PostSynthContext } from "@intentius/chant/lint/post-synth";
+import type { SerializerResult } from "@intentius/chant/serializer";
+import { postSynthChecks } from "./index";
+import { dwdc010 } from "./dwdc010";
+import { dwdc011 } from "./dwdc011";
+import { dwdc012 } from "./dwdc012";
+import { dwds010 } from "./dwds010";
+import { cedarAuditCatalog } from "../audit-catalog";
+import { renderEventSchema, defaultEventSchema } from "../../dogwood/event-schema";
+import { blankComments, temporalRegions } from "../../dogwood/scan";
+
+function ctxOf(files: Record): PostSynthContext {
+ const output: SerializerResult = { primary: "", files };
+ const outputs = new Map([["cedar", output]]);
+ return {
+ outputs,
+ entities: new Map(),
+ buildResult: { outputs, entities: new Map(), warnings: [], errors: [], sourceFileCount: 1 },
+ };
+}
+
+const PINNED = renderEventSchema(defaultEventSchema());
+
+function policy(body: string): string {
+ return `@id("p")\npermit (\n principal,\n action == Ns::Action::"Read",\n resource\n)\nwhen temporal {\n ${body}\n}\n;\n`;
+}
+
+// ── DWDC010 ────────────────────────────────────────────────────────
+
+describe("DWDC010 — the event kind must be declared", () => {
+ test("a declared kind passes", () => {
+ const ctx = ctxOf({
+ "policies.dw": policy('formerly within 1h Ns::Action::"Login"::response{}'),
+ "events.dwschema": PINNED,
+ });
+ expect(dwdc010.check(ctx)).toEqual([]);
+ });
+
+ test("an undeclared kind is an error naming both the predicate and the declared set", () => {
+ const ctx = ctxOf({
+ "policies.dw": policy('formerly within 1h Ns::Action::"Login"::nosuchkind{}'),
+ "events.dwschema": PINNED,
+ });
+ const [finding, ...rest] = dwdc010.check(ctx);
+ expect(rest).toEqual([]);
+ expect(finding.severity).toBe("error");
+ expect(finding.message).toContain('Ns::Action::"Login"::nosuchkind');
+ expect(finding.message).toContain("error, request, response");
+ expect(finding.entity).toBe("policies.dw");
+ });
+
+ test("author-defined kinds pass against the schema that declares them", () => {
+ const custom = "decision event ::attempt {\n ...inputs(A),\n}\n";
+ const ctx = ctxOf({
+ "policies.dw": policy('formerly within 1h Ns::Action::"Login"::attempt{}'),
+ "events.dwschema": custom,
+ });
+ expect(dwdc010.check(ctx)).toEqual([]);
+ });
+
+ test("silent when no schema was emitted — the far end's defaults decide", () => {
+ const ctx = ctxOf({ "policies.dw": policy('formerly within 1h Ns::Action::"Login"::nosuchkind{}') });
+ expect(dwdc010.check(ctx)).toEqual([]);
+ });
+
+ test("a commented-out predicate is not a finding", () => {
+ const ctx = ctxOf({
+ "policies.dw": `// formerly within 1h Ns::Action::"Login"::nosuchkind{}\n${policy('formerly within 1h Ns::Action::"Login"::request{}')}`,
+ "events.dwschema": PINNED,
+ });
+ expect(dwdc010.check(ctx)).toEqual([]);
+ });
+
+ test("a Cedar when clause is not temporal source, so it is not scanned", () => {
+ const cedarOnly = `@id("p")\npermit (\n principal,\n action,\n resource\n)\nwhen { context.kind == "nosuchkind" };\n`;
+ const ctx = ctxOf({ "policies.dw": cedarOnly, "events.dwschema": PINNED });
+ expect(dwdc010.check(ctx)).toEqual([]);
+ });
+
+ test("the same predicate twice is reported once", () => {
+ const body = 'formerly within 1h Ns::Action::"Login"::bogus{} && previous within 1h Ns::Action::"Login"::bogus{}';
+ const ctx = ctxOf({ "policies.dw": policy(body), "events.dwschema": PINNED });
+ expect(dwdc010.check(ctx)).toHaveLength(1);
+ });
+});
+
+// ── DWDC011 ────────────────────────────────────────────────────────
+
+describe("DWDC011 — the window must fit inside max_window", () => {
+ test("a window inside the default 24h cap passes with no schema emitted", () => {
+ const ctx = ctxOf({ "policies.dw": policy('formerly within 1h Ns::Action::"Login"::request{}') });
+ expect(dwdc011.check(ctx)).toEqual([]);
+ });
+
+ test("48h under the default 24h cap is an error even with no schema", () => {
+ const ctx = ctxOf({ "policies.dw": policy('formerly within 48h Ns::Action::"Login"::request{}') });
+ const [finding] = dwdc011.check(ctx);
+ expect(finding.severity).toBe("error");
+ expect(finding.message).toContain("looks back 48h");
+ expect(finding.message).toContain("24h");
+ expect(finding.message).toContain("no event schema was emitted");
+ });
+
+ test("raising max_window in the schema licenses the longer window", () => {
+ const raised = `max_window = 30d\n\n${PINNED.split("\n").slice(3).join("\n")}`;
+ const ctx = ctxOf({
+ "policies.dw": policy('formerly within 7d Ns::Action::"Login"::request{}'),
+ "events.dwschema": raised,
+ });
+ expect(dwdc011.check(ctx)).toEqual([]);
+ });
+
+ test("an emitted schema with no directive still caps at 24h", () => {
+ const ctx = ctxOf({
+ "policies.dw": policy('formerly within 25h Ns::Action::"Login"::request{}'),
+ "events.dwschema": PINNED,
+ });
+ expect(dwdc011.check(ctx)).toHaveLength(1);
+ });
+
+ test("the tightest of several schemas wins", () => {
+ const raised = `max_window = 30d\n\n${PINNED.split("\n").slice(3).join("\n")}`;
+ const ctx = ctxOf({
+ "policies.dw": policy('formerly within 7d Ns::Action::"Login"::request{}'),
+ "events.dwschema": raised,
+ "gateway.dwschema": PINNED,
+ });
+ expect(dwdc011.check(ctx)).toHaveLength(1);
+ });
+
+ test("a macro-call interval counts — it is the window the body resolves to", () => {
+ const ctx = ctxOf({ "policies.dw": policy('once(48h, Ns::Action::"Login"::request{})') });
+ const [finding] = dwdc011.check(ctx);
+ expect(finding.message).toContain("looks back 48h");
+ });
+
+ test("a window inside a macro definition is scanned too", () => {
+ const dw = `def temporal wide(?s) {\n formerly within 72h ?s\n};\n\n${policy('wide(Ns::Action::"Login"::request{})')}`;
+ const ctx = ctxOf({ "policies.dw": dw });
+ expect(dwdc011.check(ctx)).toHaveLength(1);
+ });
+
+ test("no policy file means nothing to judge", () => {
+ expect(dwdc011.check(ctxOf({ "events.dwschema": PINNED }))).toEqual([]);
+ });
+});
+
+// ── DWDC012 ────────────────────────────────────────────────────────
+
+describe("DWDC012 — the window is not optional", () => {
+ test("a windowed operator passes", () => {
+ const ctx = ctxOf({ "policies.dw": policy('formerly within 1h Ns::Action::"Login"::request{}') });
+ expect(dwdc012.check(ctx)).toEqual([]);
+ });
+
+ test("a bare formerly is an error", () => {
+ const ctx = ctxOf({ "policies.dw": policy('formerly Ns::Action::"Login"::request{}') });
+ const [finding] = dwdc012.check(ctx);
+ expect(finding.severity).toBe("error");
+ expect(finding.message).toContain("`formerly` with no `within` window");
+ });
+
+ test("previous and since are held to the same rule", () => {
+ for (const operator of ["previous", "since"]) {
+ const ctx = ctxOf({ "policies.dw": policy(`${operator} Ns::Action::"Login"::request{}`) });
+ expect(dwdc012.check(ctx)[0]?.message).toContain(`\`${operator}\``);
+ }
+ });
+
+ test("a `within ?w` in a macro body is a window", () => {
+ const dw = `def temporal once(?w, ?s) {\n formerly within ?w ?s\n};\n`;
+ expect(dwdc012.check(ctxOf({ "policies.dw": dw }))).toEqual([]);
+ });
+
+ test("a Cedar attribute named `since` outside a temporal block is not the operator", () => {
+ const cedarOnly = `@id("p")\npermit (\n principal,\n action,\n resource\n)\nwhen { context.since > 3 };\n`;
+ expect(dwdc012.check(ctxOf({ "policies.dw": cedarOnly }))).toEqual([]);
+ });
+});
+
+// ── DWDS010 ────────────────────────────────────────────────────────
+
+describe("DWDS010 — an unpinned schema widens every predicate", () => {
+ test("the default shape's pin satisfies it", () => {
+ expect(dwds010.check(ctxOf({ "events.dwschema": PINNED }))).toEqual([]);
+ });
+
+ test("a schema with no pin is a report-only warning", () => {
+ const unpinned = renderEventSchema(defaultEventSchema({ pinCallerPrincipal: false }));
+ const [finding] = dwds010.check(ctxOf({ "events.dwschema": unpinned }));
+ expect(finding.severity).toBe("warning");
+ expect(finding.message).toContain("declares no pinned field");
+ expect(finding.entity).toBe("events.dwschema");
+ });
+
+ test("a file with no declarations at all is not the pin's problem", () => {
+ expect(dwds010.check(ctxOf({ "events.dwschema": "// nothing here\n" }))).toEqual([]);
+ });
+});
+
+// ── Registration ───────────────────────────────────────────────────
+
+describe("registration", () => {
+ test("every DWD check is auto-discovered into the committed barrel", () => {
+ const ids = postSynthChecks.map((c) => c.id).filter((id) => id.startsWith("DWD"));
+ expect(ids.sort()).toEqual(["DWDC010", "DWDC011", "DWDC012", "DWDS010"]);
+ });
+
+ test("every DWD check has a catalog entry, so `chant audit` can title it", () => {
+ for (const check of postSynthChecks) {
+ if (!check.id.startsWith("DWD")) continue;
+ const meta = cedarAuditCatalog[check.id];
+ expect(meta, `${check.id} is catalogued`).toBeDefined();
+ expect(meta.title.length).toBeGreaterThan(0);
+ expect(meta.remediation.length).toBeGreaterThan(0);
+ }
+ });
+
+ test("the catalog carries no DWD entry without a check behind it", () => {
+ const shipped = new Set(postSynthChecks.map((c) => c.id));
+ const stale = Object.keys(cedarAuditCatalog).filter((id) => id.startsWith("DWD") && !shipped.has(id));
+ expect(stale).toEqual([]);
+ });
+});
+
+// ── The scanner itself ─────────────────────────────────────────────
+
+describe("the text scanner", () => {
+ test("a // inside a string literal is not a comment", () => {
+ const text = 'when temporal { Ns::Action::"a//b"::request{} }';
+ expect(blankComments(text)).toBe(text);
+ });
+
+ test("a comment is blanked without moving any offset", () => {
+ const text = 'x // hidden\ny';
+ const blanked = blankComments(text);
+ expect(blanked).toHaveLength(text.length);
+ expect(blanked).toBe("x \ny");
+ });
+
+ test("a temporal block is extracted through its nested braces", () => {
+ const text = 'when temporal { formerly within 1h Ns::Action::"A"::request{ input.x: 1 } }';
+ expect(temporalRegions(text)).toEqual([
+ ' formerly within 1h Ns::Action::"A"::request{ input.x: 1 } ',
+ ]);
+ });
+});
diff --git a/lexicons/cedar/src/lint/post-synth/dwdc010.ts b/lexicons/cedar/src/lint/post-synth/dwdc010.ts
new file mode 100644
index 0000000000..c1fe651a9d
--- /dev/null
+++ b/lexicons/cedar/src/lint/post-synth/dwdc010.ts
@@ -0,0 +1,62 @@
+/**
+ * DWDC010: a temporal predicate must name an event kind the schema declares
+ *
+ * Upstream rejects this outright — a predicate naming an undeclared kind fails
+ * `dogwood validate` with code `extension`: "predicate
+ * `Drupe::Action::\"Read\"::nosuchkind` does not name a declared event (no
+ * event kind `nosuchkind` derived for action `Read`)". Catching it in
+ * TypeScript is the point of the split epic #1646 drew: everything answerable
+ * without the binary runs always and gates, and this one is answerable.
+ *
+ * The check is on the event *kind*, not the action, and that is not a
+ * shortcut. Upstream's `.dwschema` grammar declares events against a symbolic
+ * action binder — `decision event ::request { … }` — so the file names no
+ * actions at all and cannot be asked whether one exists. The action half of
+ * that upstream error comes from the Cedar action schema
+ * (`--policy-schema`), which is #1659's CLI-gated leg.
+ *
+ * Silent when no `.dwschema` was emitted: with none supplied,
+ * `ServiceSchema::defaults()` decides the kinds at the far end, and guessing
+ * that a project's out-of-band schema matches upstream's default would fail
+ * builds for a policy set that is fine.
+ */
+import type { PostSynthCheck, PostSynthContext, PostSynthDiagnostic } from "@intentius/chant/lint/post-synth";
+import { dogwoodPolicyFiles, dogwoodSchemaFiles, readEventSchema, scanPredicates } from "../../dogwood/scan";
+
+export const dwdc010: PostSynthCheck = {
+ id: "DWDC010",
+ description: "A dogwood temporal predicate names an event kind the emitted .dwschema declares",
+
+ check(ctx: PostSynthContext): PostSynthDiagnostic[] {
+ const schemas = dogwoodSchemaFiles(ctx);
+ if (schemas.length === 0) return [];
+
+ const declared = new Set();
+ for (const schema of schemas) {
+ for (const kind of readEventSchema(schema.text).kinds) declared.add(kind);
+ }
+ if (declared.size === 0) return [];
+
+ const known = [...declared].sort().join(", ");
+ const diagnostics: PostSynthDiagnostic[] = [];
+
+ for (const policies of dogwoodPolicyFiles(ctx)) {
+ const seen = new Set();
+ for (const ref of scanPredicates(policies.text)) {
+ if (declared.has(ref.kind)) continue;
+ const key = `${ref.action}::${ref.kind}`;
+ if (seen.has(key)) continue;
+ seen.add(key);
+ diagnostics.push({
+ checkId: "DWDC010",
+ severity: "error",
+ message: `Dogwood policy set "${policies.source}" has a temporal predicate on ${key}, but the emitted event schema declares no event kind "${ref.kind}" (declared: ${known}).`,
+ entity: policies.source,
+ lexicon: policies.lexicon,
+ });
+ }
+ }
+
+ return diagnostics;
+ },
+};
diff --git a/lexicons/cedar/src/lint/post-synth/dwdc011.ts b/lexicons/cedar/src/lint/post-synth/dwdc011.ts
new file mode 100644
index 0000000000..daef9a81c9
--- /dev/null
+++ b/lexicons/cedar/src/lint/post-synth/dwdc011.ts
@@ -0,0 +1,61 @@
+/**
+ * DWDC011: a temporal window must fit inside the schema's `max_window`
+ *
+ * `formerly within 48h` under a 24h cap is an upstream validation error —
+ * "temporal window `48h` exceeds the maximum allowed window `24h` set by the
+ * event schema's `max_window`" — and it is arithmetic, so it needs no binary.
+ *
+ * Unlike DWDC010 this fires with no `.dwschema` emitted, because the cap
+ * applies either way: `ServiceSchema::defaults()` caps look-back at 24h, and
+ * so does an emitted schema that omits the directive. Where several schemas
+ * are emitted the tightest cap wins — a window one consumer accepts and
+ * another rejects is still a window that will be rejected.
+ *
+ * Macro-call intervals count. `once(48h, …)` expands to `formerly within 48h`
+ * through the default library's `within ?w`, so it looks back exactly as far.
+ */
+import type { PostSynthCheck, PostSynthContext, PostSynthDiagnostic } from "@intentius/chant/lint/post-synth";
+import {
+ dogwoodPolicyFiles,
+ dogwoodSchemaFiles,
+ effectiveMaxWindowSeconds,
+ readEventSchema,
+ scanWindows,
+} from "../../dogwood/scan";
+
+export const dwdc011: PostSynthCheck = {
+ id: "DWDC011",
+ description: "A dogwood temporal window stays inside the event schema's max_window cap",
+
+ check(ctx: PostSynthContext): PostSynthDiagnostic[] {
+ const policyFiles = dogwoodPolicyFiles(ctx);
+ if (policyFiles.length === 0) return [];
+
+ const schemas = dogwoodSchemaFiles(ctx).map((s) => readEventSchema(s.text));
+ const cap = effectiveMaxWindowSeconds(schemas);
+ const source =
+ schemas.length === 0
+ ? "upstream's default cap (no event schema was emitted)"
+ : `the emitted event schema's max_window`;
+
+ const diagnostics: PostSynthDiagnostic[] = [];
+
+ for (const policies of policyFiles) {
+ const reported = new Set();
+ for (const window of scanWindows(policies.text)) {
+ if (window.seconds <= cap.seconds) continue;
+ if (reported.has(window.text)) continue;
+ reported.add(window.text);
+ diagnostics.push({
+ checkId: "DWDC011",
+ severity: "error",
+ message: `Dogwood policy set "${policies.source}" looks back ${window.text}, past the ${cap.text} allowed by ${source}. Raise max_window in the event schema, or shorten the window.`,
+ entity: policies.source,
+ lexicon: policies.lexicon,
+ });
+ }
+ }
+
+ return diagnostics;
+ },
+};
diff --git a/lexicons/cedar/src/lint/post-synth/dwdc012.ts b/lexicons/cedar/src/lint/post-synth/dwdc012.ts
new file mode 100644
index 0000000000..5894ab5a91
--- /dev/null
+++ b/lexicons/cedar/src/lint/post-synth/dwdc012.ts
@@ -0,0 +1,46 @@
+/**
+ * DWDC012: `formerly`, `previous` and `since` carry a mandatory window
+ *
+ * Upstream's grammar makes `within` non-optional on all three:
+ *
+ * ```
+ * once_op = { "formerly" ~ within ~ atom }
+ * previous_op = { "previous" ~ within ~ atom }
+ * conjunct_or_since = { neg_conjunct ~ ("since" ~ within ~ atom)? }
+ * ```
+ *
+ * The typed builders make this unrepresentable — `formerly(window, body)` has
+ * nowhere to put a missing window — which is most of the fix. This check is
+ * the other part: `raw()` exists as an escape hatch, a hand-written `.dw` can
+ * be built by any other tool, and `chant audit` runs over files chant never
+ * emitted. A wall that only holds for the path that cannot breach it is not
+ * a wall.
+ */
+import type { PostSynthCheck, PostSynthContext, PostSynthDiagnostic } from "@intentius/chant/lint/post-synth";
+import { dogwoodPolicyFiles, scanWindowlessOperators } from "../../dogwood/scan";
+
+export const dwdc012: PostSynthCheck = {
+ id: "DWDC012",
+ description: "A dogwood formerly/previous/since operator carries its mandatory within window",
+
+ check(ctx: PostSynthContext): PostSynthDiagnostic[] {
+ const diagnostics: PostSynthDiagnostic[] = [];
+
+ for (const policies of dogwoodPolicyFiles(ctx)) {
+ const seen = new Set();
+ for (const operator of scanWindowlessOperators(policies.text)) {
+ if (seen.has(operator)) continue;
+ seen.add(operator);
+ diagnostics.push({
+ checkId: "DWDC012",
+ severity: "error",
+ message: `Dogwood policy set "${policies.source}" uses \`${operator}\` with no \`within\` window. All three past-only operators require one — write \`${operator} within …\`.`,
+ entity: policies.source,
+ lexicon: policies.lexicon,
+ });
+ }
+ }
+
+ return diagnostics;
+ },
+};
diff --git a/lexicons/cedar/src/lint/post-synth/dwds010.ts b/lexicons/cedar/src/lint/post-synth/dwds010.ts
new file mode 100644
index 0000000000..92a0c82f7c
--- /dev/null
+++ b/lexicons/cedar/src/lint/post-synth/dwds010.ts
@@ -0,0 +1,46 @@
+/**
+ * DWDS010: an emitted event schema with no pinned field widens every predicate
+ *
+ * The #1657 verification is specific about this one. `ServiceSchema::defaults()`
+ * — what runs when nobody passes `--event-schema` — uses
+ * `configuration/event-schemas/pinned.dwschema`, which carries
+ * `pin callerPrincipal: principalType(A) = principal` on every kind. Every
+ * temporal predicate is therefore correlated to the deciding request's
+ * principal, and events from other principals are invisible.
+ *
+ * Supplying any event schema opts out of that default wholesale. So a schema
+ * emitted without a pin does not merely "not add" a correlation: it removes
+ * one the policy author very likely assumed, and every `formerly` in the set
+ * starts matching other principals' events. That is a legitimate design —
+ * cross-principal correlation is the reason to write your own schema — but it
+ * is a decision, and a decision nobody can see in a diff is one nobody made.
+ *
+ * Report-only: chant does not know which the author wanted, only that it
+ * should be said out loud. `defaultEventSchema({ pinCallerPrincipal: false })`
+ * also stamps the reasoning into the emitted file.
+ */
+import type { PostSynthCheck, PostSynthContext, PostSynthDiagnostic } from "@intentius/chant/lint/post-synth";
+import { dogwoodSchemaFiles, readEventSchema } from "../../dogwood/scan";
+
+export const dwds010: PostSynthCheck = {
+ id: "DWDS010",
+ description: "An emitted dogwood event schema pins its temporal predicates to a request-side value",
+
+ check(ctx: PostSynthContext): PostSynthDiagnostic[] {
+ const diagnostics: PostSynthDiagnostic[] = [];
+
+ for (const schema of dogwoodSchemaFiles(ctx)) {
+ const facts = readEventSchema(schema.text);
+ if (facts.kinds.length === 0 || facts.hasPin) continue;
+ diagnostics.push({
+ checkId: "DWDS010",
+ severity: "warning",
+ message: `Dogwood event schema "${schema.source}" declares no pinned field, so temporal predicates correlate across every principal — wider than upstream's default, which pins callerPrincipal to the deciding request's principal. Add a pinned field, or record why cross-principal correlation is wanted.`,
+ entity: schema.source,
+ lexicon: schema.lexicon,
+ });
+ }
+
+ return diagnostics;
+ },
+};
diff --git a/lexicons/cedar/src/lint/post-synth/index.ts b/lexicons/cedar/src/lint/post-synth/index.ts
index e4d9d1fdfa..4ba1d2dde7 100644
--- a/lexicons/cedar/src/lint/post-synth/index.ts
+++ b/lexicons/cedar/src/lint/post-synth/index.ts
@@ -10,6 +10,10 @@ import { cede011 } from "./cede011";
import { ceds010 } from "./ceds010";
import { ceds011 } from "./ceds011";
import { ceds012 } from "./ceds012";
+import { dwdc010 } from "./dwdc010";
+import { dwdc011 } from "./dwdc011";
+import { dwdc012 } from "./dwdc012";
+import { dwds010 } from "./dwds010";
export const postSynthChecks: PostSynthCheck[] = [
cedc010,
@@ -22,4 +26,8 @@ export const postSynthChecks: PostSynthCheck[] = [
ceds010,
ceds011,
ceds012,
+ dwdc010,
+ dwdc011,
+ dwdc012,
+ dwds010,
];
diff --git a/lexicons/cedar/src/lint/post-synth/post-synth.test.ts b/lexicons/cedar/src/lint/post-synth/post-synth.test.ts
index efc2350072..86e53b0ad0 100644
--- a/lexicons/cedar/src/lint/post-synth/post-synth.test.ts
+++ b/lexicons/cedar/src/lint/post-synth/post-synth.test.ts
@@ -12,7 +12,7 @@
import { describe, test, expect } from "vitest";
import { createPostSynthContext, makePostSynthCtxFromFiles } from "@intentius/chant-test-utils";
import type { PostSynthContext } from "@intentius/chant/lint/post-synth";
-import { CEDAR_JSON_FILENAME } from "../../serializer";
+import { CEDAR_JSON_FILENAME, cedarSerializer } from "../../serializer";
import { postSynthChecks } from ".";
import { cedc010 } from "./cedc010";
import { cedc011 } from "./cedc011";
@@ -103,10 +103,14 @@ function ctxWithSchema(
// ── Barrel ─────────────────────────────────────────────────────────
describe("the cedar post-synth barrel", () => {
- test("ships every check exactly once, all under the CED prefix", () => {
+ test("ships every check exactly once, under a declared prefix", () => {
+ // Two id families, both declared on the serializer: CED for Cedar itself,
+ // DWD for the dogwood temporal dialect that ships inside this lexicon
+ // (#1658). An id outside both is what `chant dev check-lexicon` fails on.
+ const declared = [cedarSerializer.rulePrefix, ...(cedarSerializer.extraRulePrefixes ?? [])];
const ids = postSynthChecks.map((c) => c.id);
expect(new Set(ids).size).toBe(ids.length);
- expect(ids.every((id) => id.startsWith("CED"))).toBe(true);
+ expect(ids.filter((id) => !declared.some((p) => id.startsWith(p)))).toEqual([]);
expect(ids.length).toBeGreaterThanOrEqual(10);
});
diff --git a/lexicons/cedar/src/policy-text.ts b/lexicons/cedar/src/policy-text.ts
new file mode 100644
index 0000000000..372f41fbb9
--- /dev/null
+++ b/lexicons/cedar/src/policy-text.ts
@@ -0,0 +1,128 @@
+/**
+ * Cedar policy-text rendering, shared by the `.cedar` serializer, the AVP
+ * statement renderer, and the dogwood dialect's `.dw` leg.
+ *
+ * Upstream's dogwood policy grammar is Cedar's shape — `annotation* effect
+ * "(" scope ")" cond* ";"` — and only the `cond` rule differs, gaining
+ * `guardrails { … }` and `temporal { … }` forms. So everything above the first
+ * clause is common, and it lives here rather than being copied into
+ * `./dogwood/serialize.ts`, where a change to how a scope constraint is
+ * written would have had to be made twice.
+ *
+ * `resolvePolicyId` is here for the same reason it was extracted from
+ * `serialize()` by #1652: it is the only rule linking a chant entity to a
+ * policy id, the AVP observation matches against it, and the `.dw` leg has to
+ * derive ids the same way the `.cedar` leg does. One copy, three callers.
+ *
+ * This module is a leaf on purpose: `./serializer.ts` and `./dogwood/*` both
+ * import it, and neither imports the other's rendering.
+ */
+
+import type { Declarable } from "@intentius/chant/declarable";
+import { isResourceDeclarable } from "@intentius/chant/declarable";
+
+/** A plain object — not null, not an array. */
+export function isRecord(value: unknown): value is Record {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+/** The `props` of a resource-kind Declarable, or `{}` for anything else. */
+export function getProps(entity: Declarable): Record {
+ if (isResourceDeclarable(entity) && isRecord(entity.props)) {
+ return entity.props;
+ }
+ return {};
+}
+
+/** Escape a string for a double-quoted Cedar literal. */
+export function escapeCedarString(value: string): string {
+ return value
+ .replace(/\\/g, "\\\\")
+ .replace(/"/g, '\\"')
+ .replace(/\n/g, "\\n")
+ .replace(/\r/g, "\\r")
+ .replace(/\t/g, "\\t");
+}
+
+/**
+ * Derive a policy id from a logical name: `allowAdminRead` → `allow-admin-read`.
+ * Cedar ids are free-form strings; kebab-case keeps them readable in the
+ * `@id` annotation and stable across a rename-free refactor.
+ */
+export function policyIdFromLogicalName(name: string): string {
+ return name
+ .replace(/([a-z0-9])([A-Z])/g, "$1-$2")
+ .replace(/([A-Z]+)([A-Z][a-z])/g, "$1-$2")
+ .replace(/[\s_]+/g, "-")
+ .toLowerCase();
+}
+
+/**
+ * The Cedar id for a policy: an explicit `annotations.id` when the author gave
+ * one, else derived from the logical name.
+ *
+ * This is the only rule that links a chant entity to a policy in a live AVP
+ * store (#1652) — the observation resolves the same id from the same props and
+ * matches it against the `@id` annotation the statement carries — and it is
+ * also what gives a `.dw` policy the id its `.cedar` sibling would have had.
+ * Two copies of this rule would be a mapping that drifts silently.
+ */
+export function resolvePolicyId(logicalName: string, props: Record): string {
+ const explicit = isRecord(props.annotations) ? props.annotations.id : undefined;
+ return typeof explicit === "string" && explicit.length > 0
+ ? explicit
+ : policyIdFromLogicalName(logicalName);
+}
+
+function refText(value: unknown): string {
+ return String(value);
+}
+
+/** `principal`, `principal == User::"alice"`, `action in [ … ]`, `resource is Photo`. */
+export function renderScope(variable: string, scope: unknown): string {
+ if (!isRecord(scope)) return variable;
+
+ const parts = [variable];
+ if (typeof scope.is === "string") parts.push(`is ${scope.is}`);
+ if (scope.eq !== undefined) parts.push(`== ${refText(scope.eq)}`);
+ if (scope.in !== undefined) {
+ parts.push(
+ Array.isArray(scope.in)
+ ? `in [${scope.in.map(refText).join(", ")}]`
+ : `in ${refText(scope.in)}`,
+ );
+ }
+ return parts.join(" ");
+}
+
+/** A `when`/`unless` prop as a list of clause bodies — one string, or several. */
+export function conditionStrings(value: unknown): string[] {
+ if (value === undefined || value === null) return [];
+ if (Array.isArray(value)) return value.map(refText);
+ return [refText(value)];
+}
+
+/**
+ * Everything above the first clause: the annotations, the effect, and the
+ * three scope positions.
+ */
+export function renderPolicyHead(id: string, props: Record): string[] {
+ const lines: string[] = [];
+
+ // @id first, then the author's own annotations in declaration order.
+ const annotations = isRecord(props.annotations) ? props.annotations : {};
+ lines.push(`@id("${escapeCedarString(id)}")`);
+ for (const [key, value] of Object.entries(annotations)) {
+ if (key === "id" || value === undefined || value === null) continue;
+ lines.push(`@${key}("${escapeCedarString(refText(value))}")`);
+ }
+
+ const effect = props.effect === "forbid" ? "forbid" : "permit";
+ lines.push(`${effect} (`);
+ lines.push(` ${renderScope("principal", props.principal)},`);
+ lines.push(` ${renderScope("action", props.action)},`);
+ lines.push(` ${renderScope("resource", props.resource)}`);
+ lines.push(")");
+
+ return lines;
+}
diff --git a/lexicons/cedar/src/serializer.ts b/lexicons/cedar/src/serializer.ts
index ef284122ce..1fa948931a 100644
--- a/lexicons/cedar/src/serializer.ts
+++ b/lexicons/cedar/src/serializer.ts
@@ -19,14 +19,28 @@
* (#1650) generates typed classes onto exactly this shape, so nothing here
* changes when it lands — the guards become typed expressions rather than
* the opaque Cedar-expression strings they are today.
+ *
+ * A third view arrives when the build holds dogwood entities (#1658): `.dw`
+ * policy text and its `.dwschema`/`macros.dw` companions, rendered by
+ * `./dogwood/serialize.ts` and returned in the same result. Both legs share
+ * `./policy-text.ts` rather than a copy of it, because a `.dw` policy's head
+ * *is* a Cedar policy's head.
*/
import type { Declarable } from "@intentius/chant/declarable";
-import { isPropertyDeclarable, isResourceDeclarable } from "@intentius/chant/declarable";
+import { isPropertyDeclarable } from "@intentius/chant/declarable";
import type { Serializer, SerializerResult } from "@intentius/chant/serializer";
import type { LexiconOutput } from "@intentius/chant/lexicon-output";
import { walkValue, type SerializerVisitor } from "@intentius/chant/serializer-walker";
import { policyToJson, splitPolicySet, templateToJson, type PolicyJson } from "./spec/wasm";
+import { serializeDogwood } from "./dogwood/serialize";
+import {
+ conditionStrings,
+ getProps,
+ isRecord,
+ renderPolicyHead,
+ resolvePolicyId,
+} from "./policy-text";
// ── The policy entity model ───────────────────────────────────────
@@ -74,40 +88,22 @@ export interface CedarPolicyProps {
}
// ── Helpers ───────────────────────────────────────────────────────
-
-function isRecord(value: unknown): value is Record {
- return typeof value === "object" && value !== null && !Array.isArray(value);
-}
-
-function getProps(entity: Declarable): Record {
- if (isResourceDeclarable(entity) && isRecord(entity.props)) {
- return entity.props;
- }
- return {};
-}
-
-/** Escape a string for a double-quoted Cedar literal. */
-export function escapeCedarString(value: string): string {
- return value
- .replace(/\\/g, "\\\\")
- .replace(/"/g, '\\"')
- .replace(/\n/g, "\\n")
- .replace(/\r/g, "\\r")
- .replace(/\t/g, "\\t");
-}
-
-/**
- * Derive a policy id from a logical name: `allowAdminRead` → `allow-admin-read`.
- * Cedar ids are free-form strings; kebab-case keeps them readable in the
- * `@id` annotation and stable across a rename-free refactor.
- */
-export function policyIdFromLogicalName(name: string): string {
- return name
- .replace(/([a-z0-9])([A-Z])/g, "$1-$2")
- .replace(/([A-Z]+)([A-Z][a-z])/g, "$1-$2")
- .replace(/[\s_]+/g, "-")
- .toLowerCase();
-}
+//
+// Rendering the dogwood dialect shares lives in `./policy-text.ts`, along with
+// `resolvePolicyId` — the one rule linking a chant entity to a policy id, which
+// #1652 extracted for the AVP observation and the `.dw` leg needs for the same
+// reason. Re-exported here so this module stays the one import a caller needs.
+
+export {
+ conditionStrings,
+ escapeCedarString,
+ getProps,
+ isRecord,
+ policyIdFromLogicalName,
+ renderPolicyHead,
+ renderScope,
+ resolvePolicyId,
+} from "./policy-text";
// ── Walker visitor ────────────────────────────────────────────────
@@ -131,33 +127,6 @@ const cedarVisitor: SerializerVisitor = {
// ── Cedar policy text ─────────────────────────────────────────────
-function refText(value: unknown): string {
- return String(value);
-}
-
-/** `principal`, `principal == User::"alice"`, `action in [ … ]`, `resource is Photo`. */
-function renderScope(variable: string, scope: unknown): string {
- if (!isRecord(scope)) return variable;
-
- const parts = [variable];
- if (typeof scope.is === "string") parts.push(`is ${scope.is}`);
- if (scope.eq !== undefined) parts.push(`== ${refText(scope.eq)}`);
- if (scope.in !== undefined) {
- parts.push(
- Array.isArray(scope.in)
- ? `in [${scope.in.map(refText).join(", ")}]`
- : `in ${refText(scope.in)}`,
- );
- }
- return parts.join(" ");
-}
-
-function conditionStrings(value: unknown): string[] {
- if (value === undefined || value === null) return [];
- if (Array.isArray(value)) return value.map(refText);
- return [refText(value)];
-}
-
/**
* One policy, as `.cedar` text.
*
@@ -165,24 +134,12 @@ function conditionStrings(value: unknown): string[] {
* nothing else — `AWS::VerifiedPermissions::Policy` carries its policy as
* `Definition.Static.Statement`, a single Cedar policy rather than a set. Two
* renderers would be two dialects; there is one.
+ *
+ * The head comes from `renderPolicyHead`, which the dogwood dialect's `.dw`
+ * leg also calls: three surfaces, one rendering of an annotation and a scope.
*/
export function renderPolicyText(id: string, props: Record): string {
- const lines: string[] = [];
-
- // @id first, then the author's own annotations in declaration order.
- const annotations = isRecord(props.annotations) ? props.annotations : {};
- lines.push(`@id("${escapeCedarString(id)}")`);
- for (const [key, value] of Object.entries(annotations)) {
- if (key === "id" || value === undefined || value === null) continue;
- lines.push(`@${key}("${escapeCedarString(refText(value))}")`);
- }
-
- const effect = props.effect === "forbid" ? "forbid" : "permit";
- lines.push(`${effect} (`);
- lines.push(` ${renderScope("principal", props.principal)},`);
- lines.push(` ${renderScope("action", props.action)},`);
- lines.push(` ${renderScope("resource", props.resource)}`);
- lines.push(")");
+ const lines = renderPolicyHead(id, props);
for (const clause of conditionStrings(props.when)) {
lines.push(`when { ${clause} }`);
@@ -257,22 +214,6 @@ export interface CedarPolicyRecord {
props: Record;
}
-/**
- * The Cedar id for a policy: an explicit `annotations.id` when the author gave
- * one, else derived from the logical name.
- *
- * This is the only rule that links a chant entity to a policy in a live AVP
- * store (#1652) — the observation resolves the same id from the same props and
- * matches it against the `@id` annotation the statement carries. Two copies of
- * this rule would be a mapping that drifts silently, so there is one.
- */
-export function resolvePolicyId(logicalName: string, props: Record): string {
- const explicit = isRecord(props.annotations) ? props.annotations.id : undefined;
- return typeof explicit === "string" && explicit.length > 0
- ? explicit
- : policyIdFromLogicalName(logicalName);
-}
-
/**
* Every `Cedar::Policy` in a build, with references walked and ids resolved.
*
@@ -304,6 +245,11 @@ export const cedarSerializer: Serializer = {
name: "cedar",
rulePrefix: "CED",
+ // The dogwood temporal dialect ships inside this lexicon (epic #1646): a
+ // `.dw` file stripped of Cedar semantics is meaningless, so its checks are
+ // this serializer's, under their own published id family.
+ extraRulePrefixes: ["DWD"],
+
serialize(entities: Map, _outputs?: LexiconOutput[]): string | SerializerResult {
const policyText: string[] = [];
@@ -311,25 +257,41 @@ export const cedarSerializer: Serializer = {
policyText.push(renderPolicyText(id, props));
}
- if (policyText.length === 0) return "";
-
- const primary = policyText.join("\n\n") + "\n";
- const { doc, error } = policySetJSON(primary);
-
- // A policy set Cedar cannot read is a real defect, but it is the lint and
- // post-synth surface's to report (#1651) — the text is still the artifact
- // every evaluator consumes, so it is emitted either way, with the module's
- // own message carried out as a build warning rather than swallowed.
- if (!doc) {
- return {
- primary,
- warnings: [`cedar: the emitted policy text did not parse, so ${CEDAR_JSON_FILENAME} was not written — ${error}`],
- };
+ // The dogwood dialect's own entities (#1658). Emitted from here rather
+ // than from a second serializer because they are one policy set with two
+ // halves — the `.dw` text and the `.cedar` text describe the same system,
+ // and a project holding only temporal policies still gets its files.
+ const dogwood = serializeDogwood(entities);
+
+ if (policyText.length === 0 && !dogwood) return "";
+
+ const files: Record = {};
+ const warnings: string[] = [...(dogwood?.warnings ?? [])];
+ let primary = "";
+
+ if (policyText.length > 0) {
+ primary = policyText.join("\n\n") + "\n";
+ const { doc, error } = policySetJSON(primary);
+
+ // A policy set Cedar cannot read is a real defect, but it is the lint and
+ // post-synth surface's to report (#1651) — the text is still the artifact
+ // every evaluator consumes, so it is emitted either way, with the module's
+ // own message carried out as a build warning rather than swallowed.
+ if (doc) {
+ files[CEDAR_JSON_FILENAME] = JSON.stringify(doc, null, 2) + "\n";
+ } else {
+ warnings.push(
+ `cedar: the emitted policy text did not parse, so ${CEDAR_JSON_FILENAME} was not written — ${error}`,
+ );
+ }
}
+ Object.assign(files, dogwood?.files ?? {});
+
return {
primary,
- files: { [CEDAR_JSON_FILENAME]: JSON.stringify(doc, null, 2) + "\n" },
+ ...(Object.keys(files).length > 0 ? { files } : {}),
+ ...(warnings.length > 0 ? { warnings } : {}),
};
},
};