@intentius/chant-lexicon-cedar 0.44.8 → 0.44.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (149) hide show
  1. package/README.md +106 -2
  2. package/dist/agentcore/embed.d.ts +189 -0
  3. package/dist/agentcore/embed.d.ts.map +1 -0
  4. package/dist/agentcore/enforcement.d.ts +76 -0
  5. package/dist/agentcore/enforcement.d.ts.map +1 -0
  6. package/dist/agentcore/scan.d.ts +46 -0
  7. package/dist/agentcore/scan.d.ts.map +1 -0
  8. package/dist/codegen/docs-dogwood.d.ts +21 -0
  9. package/dist/codegen/docs-dogwood.d.ts.map +1 -0
  10. package/dist/codegen/docs.d.ts.map +1 -1
  11. package/dist/codegen/package.d.ts.map +1 -1
  12. package/dist/config.d.ts +25 -0
  13. package/dist/config.d.ts.map +1 -1
  14. package/dist/dogwood/cli.d.ts +247 -0
  15. package/dist/dogwood/cli.d.ts.map +1 -0
  16. package/dist/dogwood/event-schema.d.ts +161 -0
  17. package/dist/dogwood/event-schema.d.ts.map +1 -0
  18. package/dist/dogwood/index.d.ts +39 -0
  19. package/dist/dogwood/index.d.ts.map +1 -0
  20. package/dist/dogwood/macros.d.ts +96 -0
  21. package/dist/dogwood/macros.d.ts.map +1 -0
  22. package/dist/dogwood/policy.d.ts +120 -0
  23. package/dist/dogwood/policy.d.ts.map +1 -0
  24. package/dist/dogwood/replay-activity.d.ts +196 -0
  25. package/dist/dogwood/replay-activity.d.ts.map +1 -0
  26. package/dist/dogwood/replay-op.d.ts +165 -0
  27. package/dist/dogwood/replay-op.d.ts.map +1 -0
  28. package/dist/dogwood/scan.d.ts +109 -0
  29. package/dist/dogwood/scan.d.ts.map +1 -0
  30. package/dist/dogwood/serialize.d.ts +66 -0
  31. package/dist/dogwood/serialize.d.ts.map +1 -0
  32. package/dist/dogwood/temporal.d.ts +259 -0
  33. package/dist/dogwood/temporal.d.ts.map +1 -0
  34. package/dist/dogwood/trace.d.ts +215 -0
  35. package/dist/dogwood/trace.d.ts.map +1 -0
  36. package/dist/dogwood/upstream.d.ts +41 -0
  37. package/dist/dogwood/upstream.d.ts.map +1 -0
  38. package/dist/dogwood/window.d.ts +73 -0
  39. package/dist/dogwood/window.d.ts.map +1 -0
  40. package/dist/index.d.ts +12 -0
  41. package/dist/index.d.ts.map +1 -1
  42. package/dist/integrity.json +15 -3
  43. package/dist/lint/audit-catalog.d.ts.map +1 -1
  44. package/dist/lint/post-synth/dogwood-helpers.d.ts +63 -0
  45. package/dist/lint/post-synth/dogwood-helpers.d.ts.map +1 -0
  46. package/dist/lint/post-synth/dwdc010.d.ts +25 -0
  47. package/dist/lint/post-synth/dwdc010.d.ts.map +1 -0
  48. package/dist/lint/post-synth/dwdc011.d.ts +19 -0
  49. package/dist/lint/post-synth/dwdc011.d.ts.map +1 -0
  50. package/dist/lint/post-synth/dwdc012.d.ts +21 -0
  51. package/dist/lint/post-synth/dwdc012.d.ts.map +1 -0
  52. package/dist/lint/post-synth/dwdc013.d.ts +33 -0
  53. package/dist/lint/post-synth/dwdc013.d.ts.map +1 -0
  54. package/dist/lint/post-synth/dwde010.d.ts +32 -0
  55. package/dist/lint/post-synth/dwde010.d.ts.map +1 -0
  56. package/dist/lint/post-synth/dwde011.d.ts +33 -0
  57. package/dist/lint/post-synth/dwde011.d.ts.map +1 -0
  58. package/dist/lint/post-synth/dwds010.d.ts +24 -0
  59. package/dist/lint/post-synth/dwds010.d.ts.map +1 -0
  60. package/dist/lint/post-synth/index.d.ts.map +1 -1
  61. package/dist/manifest.json +1 -1
  62. package/dist/okf/index.md +7 -0
  63. package/dist/okf/rules/DWDC010.md +11 -0
  64. package/dist/okf/rules/DWDC011.md +11 -0
  65. package/dist/okf/rules/DWDC012.md +11 -0
  66. package/dist/okf/rules/DWDC013.md +15 -0
  67. package/dist/okf/rules/DWDE010.md +11 -0
  68. package/dist/okf/rules/DWDE011.md +11 -0
  69. package/dist/okf/rules/DWDS010.md +11 -0
  70. package/dist/okf/types/Policy.md +1 -0
  71. package/dist/op/activities/index.d.ts +18 -0
  72. package/dist/op/activities/index.d.ts.map +1 -0
  73. package/dist/plugin.d.ts.map +1 -1
  74. package/dist/policy-text.d.ts +53 -0
  75. package/dist/policy-text.d.ts.map +1 -0
  76. package/dist/rules/dogwood-helpers.ts +139 -0
  77. package/dist/rules/dwdc010.ts +62 -0
  78. package/dist/rules/dwdc011.ts +61 -0
  79. package/dist/rules/dwdc012.ts +46 -0
  80. package/dist/rules/dwdc013.ts +64 -0
  81. package/dist/rules/dwde010.ts +130 -0
  82. package/dist/rules/dwde011.ts +108 -0
  83. package/dist/rules/dwds010.ts +46 -0
  84. package/dist/serializer.d.ts +10 -18
  85. package/dist/serializer.d.ts.map +1 -1
  86. package/dist/skills/chant-cedar-authoring.md +180 -0
  87. package/dist/skills/chant-cedar-avp-embedding.md +125 -0
  88. package/dist/skills/chant-cedar-dogwood.md +327 -0
  89. package/dist/skills/chant-cedar-meta-policy.md +119 -0
  90. package/package.json +7 -2
  91. package/src/agentcore/embed.test.ts +254 -0
  92. package/src/agentcore/embed.ts +399 -0
  93. package/src/agentcore/enforcement.test.ts +43 -0
  94. package/src/agentcore/enforcement.ts +92 -0
  95. package/src/agentcore/scan.ts +119 -0
  96. package/src/codegen/docs-dogwood.ts +1119 -0
  97. package/src/codegen/docs.ts +66 -1
  98. package/src/codegen/package.ts +3 -2
  99. package/src/config.test.ts +12 -0
  100. package/src/config.ts +28 -0
  101. package/src/dogwood/cli.test.ts +513 -0
  102. package/src/dogwood/cli.ts +666 -0
  103. package/src/dogwood/event-schema.test.ts +218 -0
  104. package/src/dogwood/event-schema.ts +318 -0
  105. package/src/dogwood/index.ts +271 -0
  106. package/src/dogwood/macros.test.ts +104 -0
  107. package/src/dogwood/macros.ts +229 -0
  108. package/src/dogwood/policy.test.ts +94 -0
  109. package/src/dogwood/policy.ts +141 -0
  110. package/src/dogwood/replay-activity.test.ts +481 -0
  111. package/src/dogwood/replay-activity.ts +506 -0
  112. package/src/dogwood/replay-op.ts +242 -0
  113. package/src/dogwood/scan.ts +287 -0
  114. package/src/dogwood/serialize.test.ts +331 -0
  115. package/src/dogwood/serialize.ts +246 -0
  116. package/src/dogwood/temporal.test.ts +272 -0
  117. package/src/dogwood/temporal.ts +592 -0
  118. package/src/dogwood/testdata/custom-kinds.dwschema +17 -0
  119. package/src/dogwood/testdata/default-macros.dw +23 -0
  120. package/src/dogwood/testdata/lowered-read-after-login.json +13 -0
  121. package/src/dogwood/testdata/max-window-raised.dwschema +25 -0
  122. package/src/dogwood/testdata/pinned.dwschema +31 -0
  123. package/src/dogwood/testdata/read-after-login.cedarschema +20 -0
  124. package/src/dogwood/testdata/read-after-login.dw +17 -0
  125. package/src/dogwood/testdata/temporal-policies.dw +53 -0
  126. package/src/dogwood/trace.test.ts +231 -0
  127. package/src/dogwood/trace.ts +471 -0
  128. package/src/dogwood/upstream.ts +41 -0
  129. package/src/dogwood/window.ts +124 -0
  130. package/src/index.ts +76 -0
  131. package/src/lint/audit-catalog.ts +64 -0
  132. package/src/lint/post-synth/dogwood-helpers.ts +139 -0
  133. package/src/lint/post-synth/dwd-post-synth.test.ts +374 -0
  134. package/src/lint/post-synth/dwdc010.ts +62 -0
  135. package/src/lint/post-synth/dwdc011.ts +61 -0
  136. package/src/lint/post-synth/dwdc012.ts +46 -0
  137. package/src/lint/post-synth/dwdc013.ts +64 -0
  138. package/src/lint/post-synth/dwde-post-synth.test.ts +368 -0
  139. package/src/lint/post-synth/dwde010.ts +130 -0
  140. package/src/lint/post-synth/dwde011.ts +108 -0
  141. package/src/lint/post-synth/dwds010.ts +46 -0
  142. package/src/lint/post-synth/index.ts +14 -0
  143. package/src/lint/post-synth/post-synth.test.ts +7 -3
  144. package/src/op/activities/index.ts +27 -0
  145. package/src/plugin.test.ts +3 -2
  146. package/src/plugin.ts +30 -0
  147. package/src/policy-text.ts +128 -0
  148. package/src/serializer.ts +71 -109
  149. package/src/skills/chant-cedar-dogwood.md +327 -0
@@ -0,0 +1,471 @@
1
+ /**
2
+ * Typed construction of dogwood replay traces (#1661, epic #1646).
3
+ *
4
+ * A trace is one event per line, and the line grammar recorded by the #1657
5
+ * verification (§6, read from `dogwood-language/src/interpreter/log_parse.rs`
6
+ * at the pinned SHA) is:
7
+ *
8
+ * ```
9
+ * @<timestamp> [scope(principal: <uid>, resource: <uid>)]
10
+ * [entities(<uid>: { <attrs> } [in [<uid>, …]], …)]
11
+ * [request_context(<group>: { … }, …)]
12
+ * <Ns>::Action::"<Name>"::<kind>(<field>: <value>, …)
13
+ * ```
14
+ *
15
+ * The three envelopes are optional and must appear in that order; the trailing
16
+ * group is the logged record. There is no comment syntax — a `//` is an
17
+ * ordinary part of a value, so URLs survive — blank lines are skipped, and a
18
+ * leading BOM is stripped.
19
+ *
20
+ * Two things in that format silently weaken a replay rather than failing it,
21
+ * and both are what this module exists to make hard:
22
+ *
23
+ * 1. **`request_context(…)` and the logged record are different bags.** The
24
+ * Cedar request is built from the first; temporal predicates match against
25
+ * the second. A field needed by both and supplied to only one weakens
26
+ * either the Cedar check or the temporal check, and the replay still exits
27
+ * 0 with a verdict that looks authoritative. So {@link traceEvent} writes a
28
+ * `context` group into *both* bags by default, and dropping one is an
29
+ * explicit per-event `bags` opt-out that has to be typed out.
30
+ * 2. **Actions must be fully qualified.** `Drupe::Action::"Transfer"`, never
31
+ * `Transfer` — a short name leaves the temporal predicate unmatched while
32
+ * Cedar still authorizes. {@link traceEvent} rejects anything that is not
33
+ * `Ns::…::"Name"` at construction.
34
+ *
35
+ * {@link auditTrace} is the same two checks applied to a trace this module did
36
+ * not build — the AgentCore session history #1661 leaves to the aws lexicon,
37
+ * or a `.log` recorded by hand. A trace is a trace, wherever it came from.
38
+ */
39
+
40
+ import { escapeCedarString } from "../policy-text";
41
+
42
+ // ── Names ─────────────────────────────────────────────────────────
43
+
44
+ /** `Drupe::Action::"Read"`, `Drupe::OAuthUser::"alice"` — a qualified uid. */
45
+ const QUALIFIED_UID = /^[A-Za-z_][A-Za-z0-9_]*(::[A-Za-z_][A-Za-z0-9_]*)+::"[^"]*"$/;
46
+ /** A bare field, group or event-kind name. */
47
+ const IDENT = /^[A-Za-z_][A-Za-z0-9_]*$/;
48
+
49
+ function assertUid(value: string, what: string): string {
50
+ if (!QUALIFIED_UID.test(value)) {
51
+ throw new Error(`dogwood: ${what} must be fully qualified, like Ns::Type::"id" — got "${value}"`);
52
+ }
53
+ return value;
54
+ }
55
+
56
+ function assertIdent(value: string, what: string): string {
57
+ if (!IDENT.test(value)) throw new Error(`dogwood: ${what} must be an identifier — got "${value}"`);
58
+ return value;
59
+ }
60
+
61
+ // ── Values ────────────────────────────────────────────────────────
62
+
63
+ /** `Ns::Type::"id"` in value position. */
64
+ export interface TraceEntityRef {
65
+ readonly traceValue: "entity";
66
+ readonly uid: string;
67
+ }
68
+
69
+ /** `1.50` — Cedar's decimal surface form, which a JS number cannot carry. */
70
+ export interface TraceDecimal {
71
+ readonly traceValue: "decimal";
72
+ readonly text: string;
73
+ }
74
+
75
+ /** Surface text passed through untouched — the escape hatch, used sparingly. */
76
+ export interface TraceRaw {
77
+ readonly traceValue: "raw";
78
+ readonly text: string;
79
+ }
80
+
81
+ /** A tagged value: one this module renders specially rather than by JS type. */
82
+ export type TraceTagged = TraceEntityRef | TraceDecimal | TraceRaw;
83
+
84
+ /** Anything that can sit in a trace field, in Cedar surface forms. */
85
+ export type TraceValue =
86
+ | string
87
+ | number
88
+ | boolean
89
+ | TraceTagged
90
+ | readonly TraceValue[]
91
+ | { readonly [key: string]: TraceValue };
92
+
93
+ /** A named group of fields — what one `request_context` envelope entry holds. */
94
+ export type TraceFields = { readonly [key: string]: TraceValue };
95
+
96
+ /** `Ns::Type::"id"`. Validated at construction, so a short name cannot slip through. */
97
+ export function entityRef(uid: string): TraceEntityRef {
98
+ return { traceValue: "entity", uid: assertUid(uid, "an entity reference") };
99
+ }
100
+
101
+ /** A Cedar decimal, written as it should appear (`"1.50"`). */
102
+ export function decimalValue(text: string): TraceDecimal {
103
+ if (!/^-?\d+\.\d+$/.test(text)) {
104
+ throw new Error(`dogwood: a trace decimal looks like "1.50" — got "${text}"`);
105
+ }
106
+ return { traceValue: "decimal", text };
107
+ }
108
+
109
+ /** Surface text, rendered verbatim. For values this module has no shape for. */
110
+ export function rawValue(text: string): TraceRaw {
111
+ return { traceValue: "raw", text };
112
+ }
113
+
114
+ function isTagged(value: TraceValue): value is TraceTagged {
115
+ return typeof value === "object" && value !== null && !Array.isArray(value) && "traceValue" in value;
116
+ }
117
+
118
+ /** Render one value in the Cedar surface form the trace parser reads. */
119
+ export function renderTraceValue(value: TraceValue): string {
120
+ if (typeof value === "string") return `"${escapeCedarString(value)}"`;
121
+ if (typeof value === "boolean") return value ? "true" : "false";
122
+ if (typeof value === "number") {
123
+ if (!Number.isInteger(value)) {
124
+ throw new Error(
125
+ `dogwood: ${String(value)} is not an integer — a trace decimal must be written with decimalValue("1.50") so its scale survives`,
126
+ );
127
+ }
128
+ return String(value);
129
+ }
130
+ if (Array.isArray(value)) return `[${value.map(renderTraceValue).join(", ")}]`;
131
+ if (isTagged(value)) {
132
+ if (value.traceValue === "entity") return value.uid;
133
+ if (value.traceValue === "decimal") return value.text;
134
+ return value.text;
135
+ }
136
+ return renderTraceFields(value as TraceFields);
137
+ }
138
+
139
+ /** `{ a: 1, b: "x" }` — a record body, braces included. */
140
+ export function renderTraceFields(fields: TraceFields): string {
141
+ const parts = Object.entries(fields).map(
142
+ ([key, value]) => `${assertIdent(key, "a trace field name")}: ${renderTraceValue(value)}`,
143
+ );
144
+ return `{ ${parts.join(", ")} }`;
145
+ }
146
+
147
+ // ── Envelopes ─────────────────────────────────────────────────────
148
+
149
+ /** The `scope(principal: …, resource: …)` envelope. Both are entity uids. */
150
+ export interface TraceScope {
151
+ readonly principal: string;
152
+ readonly resource: string;
153
+ }
154
+
155
+ /** One `entities(…)` entry: a uid, its attributes, and its parents. */
156
+ export interface TraceEntityDecl {
157
+ readonly uid: string;
158
+ readonly attrs?: TraceFields;
159
+ /** `in [<uid>, …]` — the entity's parents in the hierarchy. */
160
+ readonly parents?: readonly string[];
161
+ }
162
+
163
+ /** `Ns::Type::"id": { … } in [ … ]`. */
164
+ export function traceEntity(uid: string, attrs?: TraceFields, parents?: readonly string[]): TraceEntityDecl {
165
+ return {
166
+ uid: assertUid(uid, "an entity declaration"),
167
+ ...(attrs ? { attrs } : {}),
168
+ ...(parents ? { parents: parents.map((p) => assertUid(p, "an entity parent")) } : {}),
169
+ };
170
+ }
171
+
172
+ // ── Events ────────────────────────────────────────────────────────
173
+
174
+ /**
175
+ * One trace line, fully resolved: every envelope decided, both bags settled.
176
+ *
177
+ * Built by {@link traceEvent} rather than by hand — the constructor is where
178
+ * the both-bags default and the qualified-action check live. The type stays
179
+ * public because a trace fetched from somewhere else (an AgentCore session
180
+ * history, a recorded `.log`) is normalized into it and then handed to
181
+ * {@link auditTrace}.
182
+ */
183
+ export interface TraceEvent {
184
+ /** The `i64` after `@`. */
185
+ readonly timestamp: number;
186
+ /** Fully qualified: `Ns::Action::"Name"`. */
187
+ readonly action: string;
188
+ /** `request`, `response`, `error` conventionally — author-defined in truth. */
189
+ readonly kind: string;
190
+ /** The trailing logged record — what temporal predicates match against. */
191
+ readonly record: TraceFields;
192
+ /** The `request_context(…)` envelope — what the Cedar request is built from. */
193
+ readonly requestContext?: TraceFields;
194
+ readonly scope?: TraceScope;
195
+ readonly entities?: readonly TraceEntityDecl[];
196
+ }
197
+
198
+ /**
199
+ * Which bags a `context` group lands in.
200
+ *
201
+ * `both` is the default and the only one that keeps a replay honest. The other
202
+ * two exist so a test can *demonstrate* the weakening rather than only
203
+ * describe it, and so a trace that genuinely has no Cedar-side counterpart for
204
+ * a field can say so out loud instead of by omission.
205
+ */
206
+ export type TraceBags = "both" | "record-only" | "context-only";
207
+
208
+ /** What {@link traceEvent} takes. */
209
+ export interface TraceEventInput {
210
+ readonly timestamp: number;
211
+ /** Fully qualified: `Ns::Action::"Name"`. A short name throws. */
212
+ readonly action: string;
213
+ /** Default `request` — the only kind the default event schema decides on. */
214
+ readonly kind?: string;
215
+ /**
216
+ * Named field groups (`input`, `output`, …). Each lands in **both** the
217
+ * `request_context` envelope and the logged record unless {@link bags} says
218
+ * otherwise.
219
+ */
220
+ readonly context?: { readonly [group: string]: TraceFields };
221
+ /**
222
+ * Fields that belong to the logged record only — `callerPrincipal`,
223
+ * `callerResource`, `requestId`, `sessionId` and the rest of the event
224
+ * schema's own injections. These are never part of the Cedar request.
225
+ */
226
+ readonly record?: TraceFields;
227
+ readonly scope?: TraceScope;
228
+ readonly entities?: readonly TraceEntityDecl[];
229
+ /** Explicit opt-out of both-bag population. See {@link TraceBags}. */
230
+ readonly bags?: TraceBags;
231
+ }
232
+
233
+ /**
234
+ * Build one trace event with both bags populated.
235
+ *
236
+ * Every `context` group is written to the `request_context` envelope *and*
237
+ * merged into the logged record, because that is the only combination in which
238
+ * the Cedar check and the temporal check both see the field. Dropping one is a
239
+ * typed decision (`bags`), not an omission.
240
+ */
241
+ export function traceEvent(input: TraceEventInput): TraceEvent {
242
+ const action = assertUid(input.action, "a trace action");
243
+ const kind = assertIdent(input.kind ?? "request", "an event kind");
244
+ const bags = input.bags ?? "both";
245
+
246
+ const groups = input.context ?? {};
247
+ for (const group of Object.keys(groups)) assertIdent(group, "a request-context group");
248
+
249
+ const record: Record<string, TraceValue> = {};
250
+ if (bags !== "context-only") Object.assign(record, groups);
251
+ Object.assign(record, input.record ?? {});
252
+
253
+ const context: Record<string, TraceValue> = {};
254
+ if (bags !== "record-only") Object.assign(context, groups);
255
+
256
+ return {
257
+ timestamp: input.timestamp,
258
+ action,
259
+ kind,
260
+ record,
261
+ ...(Object.keys(context).length > 0 ? { requestContext: context } : {}),
262
+ ...(input.scope
263
+ ? {
264
+ scope: {
265
+ principal: assertUid(input.scope.principal, "a scope principal"),
266
+ resource: assertUid(input.scope.resource, "a scope resource"),
267
+ },
268
+ }
269
+ : {}),
270
+ ...(input.entities && input.entities.length > 0 ? { entities: input.entities } : {}),
271
+ };
272
+ }
273
+
274
+ // ── Rendering ─────────────────────────────────────────────────────
275
+
276
+ function renderScope(scope: TraceScope): string {
277
+ return `scope(principal: ${scope.principal}, resource: ${scope.resource})`;
278
+ }
279
+
280
+ function renderEntities(entities: readonly TraceEntityDecl[]): string {
281
+ const parts = entities.map((e) => {
282
+ const attrs = renderTraceFields(e.attrs ?? {});
283
+ const parents = e.parents && e.parents.length > 0 ? ` in [${e.parents.join(", ")}]` : "";
284
+ return `${e.uid}: ${attrs}${parents}`;
285
+ });
286
+ return `entities(${parts.join(", ")})`;
287
+ }
288
+
289
+ function renderGroups(fields: TraceFields): string {
290
+ const parts = Object.entries(fields).map(
291
+ ([group, value]) => `${assertIdent(group, "a request-context group")}: ${renderTraceValue(value)}`,
292
+ );
293
+ return `request_context(${parts.join(", ")})`;
294
+ }
295
+
296
+ /** One event as the single line the trace parser reads. Never ends in a newline. */
297
+ export function renderTraceLine(event: TraceEvent): string {
298
+ if (!Number.isInteger(event.timestamp)) {
299
+ throw new Error(`dogwood: a trace timestamp is an i64 — got ${String(event.timestamp)}`);
300
+ }
301
+
302
+ const parts = [`@${event.timestamp}`];
303
+ if (event.scope) parts.push(renderScope(event.scope));
304
+ if (event.entities && event.entities.length > 0) parts.push(renderEntities(event.entities));
305
+ if (event.requestContext && Object.keys(event.requestContext).length > 0) {
306
+ parts.push(renderGroups(event.requestContext));
307
+ }
308
+
309
+ const record = Object.entries(event.record).map(
310
+ ([key, value]) => `${assertIdent(key, "a trace field name")}: ${renderTraceValue(value)}`,
311
+ );
312
+ parts.push(`${event.action}::${event.kind}(${record.join(", ")})`);
313
+
314
+ return parts.join(" ");
315
+ }
316
+
317
+ /** A whole trace, one event per line, newline-terminated. */
318
+ export function renderTrace(events: readonly TraceEvent[]): string {
319
+ return events.map(renderTraceLine).join("\n") + "\n";
320
+ }
321
+
322
+ // ── Auditing a trace this module did not build ────────────────────
323
+
324
+ /** What {@link auditTrace} can find. */
325
+ export type TraceIssueKind =
326
+ | "single-bag"
327
+ | "no-request-context"
328
+ | "empty-record"
329
+ | "out-of-order";
330
+
331
+ /** One finding against a trace, indexed by its position in the event list. */
332
+ export interface TraceIssue {
333
+ readonly kind: TraceIssueKind;
334
+ /** 0-based position in the event list — a trace has no line numbers of its own. */
335
+ readonly index: number;
336
+ readonly timestamp: number;
337
+ readonly message: string;
338
+ }
339
+
340
+ /** Options for {@link auditTrace} and {@link traceFixture}. */
341
+ export interface TraceAuditOptions {
342
+ /**
343
+ * Event kinds that produce a decision, and so build a Cedar request.
344
+ *
345
+ * Default `["request"]`, which is the convention the default event schema
346
+ * follows — the truth is whichever kinds the project's `.dwschema` marks
347
+ * `decision`, and that file is not visible from here. A history-only event
348
+ * never becomes a Cedar request, so an absent `request_context` on one is
349
+ * not a weakening and is not reported.
350
+ */
351
+ readonly decisionKinds?: readonly string[];
352
+ }
353
+
354
+ /**
355
+ * The both-bags and ordering checks, applied to any trace.
356
+ *
357
+ * Every finding here is something that makes a replay *weaker* rather than
358
+ * something that makes it fail — which is exactly the class a green replay run
359
+ * hides. A trace built by {@link traceEvent} produces none of them unless a
360
+ * `bags` opt-out was taken deliberately.
361
+ */
362
+ export function auditTrace(events: readonly TraceEvent[], options: TraceAuditOptions = {}): TraceIssue[] {
363
+ const issues: TraceIssue[] = [];
364
+ const decisionKinds = new Set(options.decisionKinds ?? ["request"]);
365
+ let previous: number | undefined;
366
+
367
+ events.forEach((event, index) => {
368
+ const at = { index, timestamp: event.timestamp };
369
+ const context = event.requestContext ?? {};
370
+ const contextKeys = Object.keys(context);
371
+ const decides = decisionKinds.has(event.kind);
372
+
373
+ if (decides && contextKeys.length === 0) {
374
+ issues.push({
375
+ ...at,
376
+ kind: "no-request-context",
377
+ message: `${event.action}::${event.kind} has no request_context envelope, so the Cedar request it is evaluated against carries no context — every context.* test in a policy silently misses`,
378
+ });
379
+ }
380
+
381
+ for (const group of contextKeys) {
382
+ if (!(group in event.record)) {
383
+ issues.push({
384
+ ...at,
385
+ kind: "single-bag",
386
+ message: `${event.action}::${event.kind} puts "${group}" in request_context but not in the logged record, so temporal predicates over ${group}.* silently miss`,
387
+ });
388
+ }
389
+ }
390
+
391
+ for (const group of Object.keys(event.record)) {
392
+ // Only groups (records) are candidates for the Cedar side; the event
393
+ // schema's own scalar injections (callerPrincipal, requestId, …) belong
394
+ // to the logged record alone and are not a single-bag finding.
395
+ const value = event.record[group];
396
+ const isGroup = typeof value === "object" && value !== null && !Array.isArray(value) && !isTagged(value);
397
+ if (decides && isGroup && contextKeys.length > 0 && !(group in context)) {
398
+ issues.push({
399
+ ...at,
400
+ kind: "single-bag",
401
+ message: `${event.action}::${event.kind} puts "${group}" in the logged record but not in request_context, so context.${group}.* is absent from the Cedar request`,
402
+ });
403
+ }
404
+ }
405
+
406
+ if (Object.keys(event.record).length === 0) {
407
+ issues.push({
408
+ ...at,
409
+ kind: "empty-record",
410
+ message: `${event.action}::${event.kind} logs no fields at all, so no temporal predicate can match it`,
411
+ });
412
+ }
413
+
414
+ if (previous !== undefined && event.timestamp < previous) {
415
+ issues.push({
416
+ ...at,
417
+ kind: "out-of-order",
418
+ message: `timestamp ${event.timestamp} follows ${previous} — the interpreter accumulates history in file order, so an out-of-order line changes what a window sees`,
419
+ });
420
+ }
421
+ previous = event.timestamp;
422
+ });
423
+
424
+ return issues;
425
+ }
426
+
427
+ // ── Fixtures ──────────────────────────────────────────────────────
428
+
429
+ /** Options for {@link traceFixture}. */
430
+ export interface TraceFixtureOptions extends TraceAuditOptions {
431
+ /**
432
+ * Issue kinds to tolerate. Empty by default: a fixture that weakens its own
433
+ * replay throws at build time rather than producing a green run that proves
434
+ * nothing.
435
+ */
436
+ readonly allow?: readonly TraceIssueKind[];
437
+ }
438
+
439
+ /** A built trace: the events, the text, and whatever the audit tolerated. */
440
+ export interface TraceFixture {
441
+ readonly events: readonly TraceEvent[];
442
+ readonly text: string;
443
+ readonly issues: readonly TraceIssue[];
444
+ }
445
+
446
+ /**
447
+ * Assemble events into trace text, refusing to produce a weakened one.
448
+ *
449
+ * The inversion of the trap: the default is a trace that populates both bags,
450
+ * and every way of getting a weaker one — a `bags` opt-out on an event, a
451
+ * hand-normalized event with an empty record — has to be named in `allow`
452
+ * before this will hand it back.
453
+ */
454
+ export function traceFixture(
455
+ events: readonly TraceEvent[],
456
+ options: TraceFixtureOptions = {},
457
+ ): TraceFixture {
458
+ const allow = new Set(options.allow ?? []);
459
+ const issues = auditTrace(events, options);
460
+ const blocking = issues.filter((i) => !allow.has(i.kind));
461
+
462
+ if (blocking.length > 0) {
463
+ const detail = blocking.map((i) => ` [${i.kind}] @${i.timestamp}: ${i.message}`).join("\n");
464
+ throw new Error(
465
+ `dogwood: this trace would weaken its own replay rather than fail it:\n${detail}\n` +
466
+ `Fix the events, or pass { allow: [${[...new Set(blocking.map((i) => `"${i.kind}"`))].join(", ")}] } to say the weakening is the point.`,
467
+ );
468
+ }
469
+
470
+ return { events, text: renderTrace(events), issues };
471
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * The dogwood upstream pin.
3
+ *
4
+ * Not a `upstreamPin` on the plugin: that slot belongs to the cedar grammar
5
+ * (`@cedar-policy/cedar-wasm`, see `../spec/pin.ts`), and self-upgrade tooling
6
+ * bumps exactly one thing per lexicon. Dogwood's pin is a git SHA recorded by
7
+ * #1657, because upstream has no version to key off — zero tags, zero
8
+ * releases, and a workspace version of `1.0.0` that is an Amazon-internal
9
+ * package artifact every future sync will also report.
10
+ *
11
+ * The blob hashes are the narrow content pin the #1657 report recommends. The
12
+ * whole tree hash moves on every sync including docs-only ones, which makes it
13
+ * too noisy to gate on; these seven files are the surface chant actually
14
+ * depends on. The three `.pest` grammars pin the language, `default_macros.dw`
15
+ * pins the standard aggregate library (which is a file a sync can edit and a
16
+ * caller can replace with `--macros`), and the three `dogwood-cli/src` files
17
+ * pin the JSON report structs that are #1659's integration surface.
18
+ *
19
+ * Movement risk is structural, not incidental: content arrives as squashed
20
+ * "Sync from internal source" commits from a publish bot, against a repository
21
+ * nobody outside Amazon can see, with no changelog and no version bump.
22
+ */
23
+
24
+ /** The pinned upstream revision and the files chant's surface is built against. */
25
+ export const DOGWOOD_UPSTREAM = {
26
+ owner: "dogwood-policy",
27
+ repo: "dogwood",
28
+ /** Default-branch SHA verified in #1657 (committed 2026-08-06). */
29
+ revision: "5063bcc2d6d6cf5024d1b0498e6cc8ef52cbcf0c",
30
+ license: "Apache-2.0",
31
+ /** Git blob hashes at {@link revision} — the narrow content pin. */
32
+ contents: {
33
+ "dogwood-language/src/parser/grammar.pest": "adb0801303ee1b735585fe22a5d85175ecf6772c",
34
+ "dogwood-language/src/extension/temporal/grammar.pest": "dc31fe1634b5c37173f0a999619e9834069b7a22",
35
+ "dogwood-language/src/event_schema/grammar.pest": "bd3b064447dc0d09cc2f8eb28a7c657e746cc8a2",
36
+ "dogwood-language/configuration/default_macros.dw": "ecd67e5edcd566aa66b05ad51bc472afbaf22a7a",
37
+ "dogwood-cli/src/ops.rs": "2924c7eb0e569a745ff19c2d84cbba782fc56502",
38
+ "dogwood-cli/src/main.rs": "bfd68c9ff05883ed48e5738f658b5925542d817d",
39
+ "dogwood-cli/src/error.rs": "43f12afbbf25ad94e25130c83227eefd86f8d516",
40
+ },
41
+ } as const;
@@ -0,0 +1,124 @@
1
+ /**
2
+ * Temporal windows — the one thing dogwood's past-only operators cannot omit.
3
+ *
4
+ * `formerly`, `previous` and `since` all take a mandatory `within <n><unit>`
5
+ * clause; the unit is one of `s`, `m`, `h`, `d` and nothing else. Upstream's
6
+ * `temporal/grammar.pest` spells that out:
7
+ *
8
+ * ```
9
+ * within = { "within" ~ within_payload }
10
+ * within_payload = { param_ref | (integer ~ time_unit) }
11
+ * time_unit = { "s" | "m" | "h" | "d" }
12
+ * ```
13
+ *
14
+ * Typing the window as a value rather than as free text is what makes
15
+ * "a `formerly` without a window" unrepresentable in the builders (#1658's
16
+ * third lint wall) — you cannot call {@link formerly} without one.
17
+ *
18
+ * The `param_ref` arm (`within ?w`) is legal only inside a macro body; it is
19
+ * modelled by {@link MacroWindow} rather than by this type, so an ordinary
20
+ * policy cannot accidentally emit a sigil the expander would reject.
21
+ */
22
+
23
+ /** The four units upstream's grammar admits. Anything else does not parse. */
24
+ export type TimeUnit = "s" | "m" | "h" | "d";
25
+
26
+ /** A `within` payload: a positive integer and one of the four units. */
27
+ export interface TemporalWindow {
28
+ readonly value: number;
29
+ readonly unit: TimeUnit;
30
+ }
31
+
32
+ /**
33
+ * A window as written in a `.dw` file (`"1h"`, `"30m"`, `"7d"`).
34
+ *
35
+ * The template-literal arm means `formerly("1h", …)` type-checks and
36
+ * `formerly("1w", …)` does not, without anyone writing a runtime check first.
37
+ */
38
+ export type WindowLike = TemporalWindow | `${number}${TimeUnit}`;
39
+
40
+ /**
41
+ * `within ?w` — a window a macro takes as a parameter.
42
+ *
43
+ * The other arm of upstream's `within_payload`. Legal only inside a macro
44
+ * body; the expander resolves it against the call site's bare interval
45
+ * argument (`once(1h, …)`), which is why the call side has no `within`.
46
+ */
47
+ export interface WindowParam {
48
+ readonly param: string;
49
+ }
50
+
51
+ /** Either a concrete window or a macro parameter standing in for one. */
52
+ export type WindowValue = TemporalWindow | WindowParam;
53
+
54
+ const WINDOW_TEXT = /^(\d+)([smhd])$/;
55
+ const PARAM_TEXT = /^\?[A-Za-z_][A-Za-z0-9_]*$/;
56
+
57
+ /** True when the payload is `?w` rather than `1h`. */
58
+ export function isWindowParam(value: WindowValue): value is WindowParam {
59
+ return "param" in value;
60
+ }
61
+
62
+ /**
63
+ * `within ?w` inside a macro body.
64
+ *
65
+ * Exported from `./macros.ts` too, which is where the sigil rules are
66
+ * documented and where a reader looking for it will be.
67
+ */
68
+ export function windowParam(param: string): WindowParam {
69
+ if (!PARAM_TEXT.test(param)) {
70
+ throw new Error(`dogwood: a window parameter carries the "?" sigil — got "${param}"`);
71
+ }
72
+ return { param };
73
+ }
74
+
75
+ /** Seconds in one of each unit — the scale `max_window` comparisons run on. */
76
+ const UNIT_SECONDS: Record<TimeUnit, number> = { s: 1, m: 60, h: 3600, d: 86400 };
77
+
78
+ /** Narrow a {@link WindowLike} to the structured form, validating as it goes. */
79
+ export function window(value: WindowLike): TemporalWindow {
80
+ if (typeof value !== "string") {
81
+ if (!Number.isInteger(value.value) || value.value < 0) {
82
+ throw new Error(`dogwood: a temporal window must be a non-negative integer, got ${String(value.value)}`);
83
+ }
84
+ if (!(value.unit in UNIT_SECONDS)) {
85
+ throw new Error(`dogwood: a temporal window unit must be s, m, h or d, got "${String(value.unit)}"`);
86
+ }
87
+ return { value: value.value, unit: value.unit };
88
+ }
89
+
90
+ const match = WINDOW_TEXT.exec(value);
91
+ if (!match) {
92
+ throw new Error(`dogwood: "${value}" is not a temporal window — write an integer and one of s, m, h, d (for example "1h")`);
93
+ }
94
+ return { value: Number(match[1]), unit: match[2] as TimeUnit };
95
+ }
96
+
97
+ /** `1h` — the surface form, in a `within` clause or as a macro-call argument. */
98
+ export function renderWindow(value: WindowLike): string {
99
+ const w = window(value);
100
+ return `${w.value}${w.unit}`;
101
+ }
102
+
103
+ /** A `within` payload: `1h`, or the `?w` a macro body defers to its call site. */
104
+ export function renderWindowValue(value: WindowValue): string {
105
+ return isWindowParam(value) ? value.param : renderWindow(value);
106
+ }
107
+
108
+ /** Narrow a window argument, letting a `?w` parameter through unchanged. */
109
+ export function windowValue(value: WindowLike | WindowParam): WindowValue {
110
+ return typeof value === "object" && "param" in value ? windowParam(value.param) : window(value);
111
+ }
112
+
113
+ /** The window in seconds, so `90m` and `1h` are comparable to a `max_window`. */
114
+ export function windowSeconds(value: WindowLike): number {
115
+ const w = window(value);
116
+ return w.value * UNIT_SECONDS[w.unit];
117
+ }
118
+
119
+ /**
120
+ * Upstream's fallback cap. `ServiceSchema::defaults()` and an event schema
121
+ * with no `max_window` directive both look back at most 24 hours, per the
122
+ * comment atop `event_schema/grammar.pest` ("absent → a 24h default").
123
+ */
124
+ export const DEFAULT_MAX_WINDOW: TemporalWindow = { value: 24, unit: "h" };