create-ailk 0.12.0 → 0.13.0

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 (56) hide show
  1. package/dist/module-architecture.js +27 -0
  2. package/package.json +3 -3
  3. package/templates/.env.example +23 -9
  4. package/templates/apps/api/CLAUDE.md +21 -17
  5. package/templates/apps/api/src/__tests__/factories/agent-caller.ts +98 -0
  6. package/templates/apps/api/src/__tests__/factories/in-memory-prisma.ts +321 -0
  7. package/templates/apps/api/src/__tests__/schedule-forwarded-rate-limit.test.ts +117 -0
  8. package/templates/apps/api/src/config/__tests__/hub-require-spoke-key.test.ts +39 -14
  9. package/templates/apps/api/src/config/index.ts +35 -20
  10. package/templates/apps/api/src/lib/__mocks__/prisma-client.js +3 -0
  11. package/templates/apps/api/src/lib/__mocks__/prisma.ts +14 -0
  12. package/templates/apps/api/src/lib/__tests__/agent-store.test.ts +468 -0
  13. package/templates/apps/api/src/lib/__tests__/spoke-store.test.ts +32 -2
  14. package/templates/apps/api/src/lib/agent-store.ts +521 -0
  15. package/templates/apps/api/src/lib/spoke-store.ts +13 -2
  16. package/templates/apps/api/src/middleware/__tests__/auth.bearer-path.test.ts +384 -1
  17. package/templates/apps/api/src/middleware/__tests__/auth.cookie-path.test.ts +61 -0
  18. package/templates/apps/api/src/middleware/__tests__/default-tenant.test.ts +176 -0
  19. package/templates/apps/api/src/middleware/__tests__/rate-limit.test.ts +76 -0
  20. package/templates/apps/api/src/middleware/auth.ts +219 -5
  21. package/templates/apps/api/src/middleware/default-tenant.ts +29 -8
  22. package/templates/apps/api/src/middleware/rate-limit.ts +35 -13
  23. package/templates/apps/api/src/routes/leads/__tests__/spoke.test.ts +76 -15
  24. package/templates/apps/api/src/routes/leads/index.ts +14 -6
  25. package/templates/apps/api/src/routes/project-listings/__tests__/me.test.ts +5 -6
  26. package/templates/apps/api/src/routes/project-listings/index.ts +14 -9
  27. package/templates/apps/api/src/routes/project-listings/me.ts +4 -3
  28. package/templates/apps/api/src/routes/project-listings/patch-copy.ts +7 -5
  29. package/templates/apps/api/src/routes/workspaces/__tests__/inbox-wire-schemas.test.ts +198 -0
  30. package/templates/apps/api/src/server.ts +27 -0
  31. package/templates/apps/api/src/services/__tests__/audit-log.test.ts +374 -57
  32. package/templates/apps/api/src/services/__tests__/leads-inbox.test.ts +25 -2
  33. package/templates/apps/api/src/services/__tests__/spoke-resolution.test.ts +303 -17
  34. package/templates/apps/api/src/services/audit-log.ts +278 -47
  35. package/templates/apps/api/src/services/default-tenant.ts +55 -5
  36. package/templates/apps/api/src/services/leads-inbox.ts +12 -21
  37. package/templates/apps/api/src/services/project-listings.ts +1 -21
  38. package/templates/apps/api/src/services/public-site-resolver.ts +103 -13
  39. package/templates/apps/mcp/CLAUDE.md +44 -5
  40. package/templates/apps/mcp/__tests__/parity.test.ts +53 -1
  41. package/templates/apps/mcp/__tests__/workspace-surface.test.ts +364 -0
  42. package/templates/apps/mcp/src/http-transport.ts +107 -1
  43. package/templates/apps/mcp/src/workspace-server.ts +193 -0
  44. package/templates/apps/web/.env.example +64 -37
  45. package/templates/apps/web/app/v1/[...path]/route.ts +16 -0
  46. package/templates/apps/web/lib/__tests__/relay.test.ts +515 -0
  47. package/templates/apps/web/lib/relay.ts +279 -0
  48. package/templates/apps/web/middleware.ts +5 -4
  49. package/templates/apps/web/next.config.mjs +6 -0
  50. package/templates/database/CHANGELOG.md +25 -0
  51. package/templates/database/__tests__/agents.db.test.ts +235 -0
  52. package/templates/database/__tests__/build.test.ts +131 -0
  53. package/templates/database/auth/schema.prisma +61 -0
  54. package/templates/database/migrations/20261005120000_agents/migration.sql +84 -0
  55. package/templates/database/package.json +3 -3
  56. package/versions.json +34 -34
@@ -1,12 +1,14 @@
1
1
  /**
2
2
  * @file audit-log.test.ts
3
- * @description Unit tests for the agent-action audit writer (#6040,
4
- * REL-017 row 5 / FEAT-084 SUB-096), scored against docs/specs/6040-one-auditlog-row-per-agent-spec.md §5.1.
3
+ * @description Unit tests for the audit writer (#6040, REL-017 row 5 /
4
+ * FEAT-084 SUB-096), scored against docs/specs/6040-one-auditlog-row-per-agent-spec.md §5.1,
5
+ * and its actor-and-domain reshape (#3591 D8,
6
+ * docs/specs/3591-tenant-scoped-agent-auth-secure-spec.md).
5
7
  *
6
8
  * External dependency boundaries mocked:
7
9
  * - apps/api/src/lib/prisma — the repo-standard `__mocks__/prisma.ts`
8
10
  * manual mock (`jest.mock("../../lib/prisma.js")`). Not read directly by
9
- * any case below — `recordAgentAction`'s injectable `AuditWriteClient`
11
+ * any case below — `recordAuditAction`'s injectable `AuditWriteClient`
10
12
  * (D1) means every case supplies its own stub delegate — this mock is
11
13
  * kept only so importing `audit-log.ts` never constructs a real
12
14
  * `PrismaPg` adapter (the repo-standard reason every sibling service
@@ -44,12 +46,16 @@ import { sanitizePII } from "@working-theory/observability";
44
46
 
45
47
  import type { TenantContext } from "../default-tenant.js";
46
48
  import {
49
+ auditActorFor,
47
50
  deriveAuditRowId,
48
- recordAgentAction,
51
+ freshAuditIdempotencyKey,
52
+ recordAgentWrite,
53
+ recordAuditAction,
49
54
  redactPersonalData,
55
+ type AuditActor,
50
56
  type AuditRowDigestInput,
51
57
  type AuditWriteClient,
52
- type RecordAgentActionInput,
58
+ type RecordAuditActionInput,
53
59
  } from "../audit-log.js";
54
60
 
55
61
  // ─── Fixtures ───────────────────────────────────────────────────────────────
@@ -68,9 +74,24 @@ const TENANT: TenantContext = {
68
74
  role: "owner",
69
75
  };
70
76
 
71
- const BASE_INPUT: RecordAgentActionInput = {
77
+ /** An agent actor with the given id, acting for `USER_ID`. */
78
+ function agentActor(agentId: string): AuditActor {
79
+ return {
80
+ type: "agent",
81
+ agentId: agentId as Id<"agent">,
82
+ onBehalfOfUserId: USER_ID as Id<"user">,
83
+ };
84
+ }
85
+
86
+ /** A person actor with the given id. */
87
+ function userActor(userId: string): AuditActor {
88
+ return { type: "user", userId: userId as Id<"user"> };
89
+ }
90
+
91
+ const BASE_INPUT: RecordAuditActionInput = {
72
92
  tenant: TENANT,
73
- actorId: "agent_abc123",
93
+ actor: agentActor("agent_abc123"),
94
+ domain: "commerce",
74
95
  tool: "refund",
75
96
  outcome: "succeeded",
76
97
  idempotencyKey: "req_abc123",
@@ -111,51 +132,72 @@ beforeEach(() => {
111
132
  // ─── AC-1 — exactly one row, carrying the five facts ───────────────────────
112
133
 
113
134
  describe("AC-1 — exactly one row, carrying the five facts", () => {
114
- it("calls create exactly once for one recordAgentAction call", async () => {
135
+ it("calls create exactly once for one recordAuditAction call", async () => {
115
136
  const { db, create } = stubDb();
116
- await recordAgentAction(BASE_INPUT, db);
137
+ await recordAuditAction(BASE_INPUT, db);
117
138
  expect(create).toHaveBeenCalledTimes(1);
118
139
  });
119
140
 
120
141
  it("writes workspaceId from the resolved tenant, satisfying zWorkspaceId", async () => {
121
142
  const { db, create } = stubDb();
122
- await recordAgentAction(BASE_INPUT, db);
143
+ await recordAuditAction(BASE_INPUT, db);
123
144
  const row = firstWrittenRow(create);
124
145
  expect(row.workspaceId).toBe(TENANT.workspaceId);
125
146
  expect(zWorkspaceId.safeParse(row.workspaceId).success).toBe(true);
126
147
  });
127
148
 
128
- it("writes actorType 'agent' unconditionally — a regression guard, not caller-influenced", async () => {
149
+ it("writes an agent actor as actorType 'agent', actorId the agent's id, and metadata.onBehalfOf its person (#3591 D8)", async () => {
129
150
  const { db, create } = stubDb();
130
- await recordAgentAction({ ...BASE_INPUT, outcome: "refused" }, db);
151
+ await recordAuditAction({ ...BASE_INPUT, outcome: "refused" }, db);
131
152
  const row = firstWrittenRow(create);
132
153
  expect(row.actorType).toBe("agent");
154
+ expect(row.actorId).toBe("agent_abc123");
155
+ expect(row.metadata.onBehalfOf).toBe(USER_ID);
133
156
  });
134
157
 
135
- it("writes actorId verbatim", async () => {
158
+ it("writes a person actor as actorType 'user', actorId their user id, and no onBehalfOf (#3591 D8)", async () => {
136
159
  const { db, create } = stubDb();
137
- await recordAgentAction(BASE_INPUT, db);
160
+ await recordAuditAction({ ...BASE_INPUT, actor: userActor(USER_ID) }, db);
138
161
  const row = firstWrittenRow(create);
139
- expect(row.actorId).toBe(BASE_INPUT.actorId);
162
+ expect(row.actorType).toBe("user");
163
+ expect(row.actorId).toBe(USER_ID);
164
+ expect(row.metadata).not.toHaveProperty("onBehalfOf");
140
165
  });
141
166
 
142
- it("writes action as 'agent.commerce.' + tool — the tool name in the column, not only metadata", async () => {
167
+ it("writes action as domain + '.' + tool — never the retired 'agent.commerce.' prefix (#3591 D8)", async () => {
143
168
  const { db, create } = stubDb();
144
- await recordAgentAction({ ...BASE_INPUT, tool: "start_purchase" }, db);
169
+ await recordAuditAction({ ...BASE_INPUT, domain: "inbox", tool: "accept_message" }, db);
145
170
  const row = firstWrittenRow(create);
146
- expect(row.action).toBe("agent.commerce.start_purchase");
171
+ expect(row.action).toBe("inbox.accept_message");
172
+ expect(row.action).not.toMatch(/^agent\.commerce\./);
173
+ });
174
+
175
+ it("writes metadata at v: 2 (#3591 D8)", async () => {
176
+ const { db, create } = stubDb();
177
+ await recordAuditAction(BASE_INPUT, db);
178
+ expect(firstWrittenRow(create).metadata.v).toBe(2);
147
179
  });
148
180
 
181
+ it.each(["", "Inbox", "in box", "inbox.accept", "a".repeat(33)])(
182
+ "refuses a domain outside the identifier grammar (%j)",
183
+ async (domain) => {
184
+ const { db, create } = stubDb();
185
+ const result = await recordAuditAction({ ...BASE_INPUT, domain }, db);
186
+ expect(result.ok).toBe(false);
187
+ expect(create).not.toHaveBeenCalled();
188
+ },
189
+ );
190
+
149
191
  it.each([
150
192
  "succeeded",
151
193
  "failed",
152
194
  "refused",
153
195
  "awaiting_approval",
154
- ] satisfies RecordAgentActionInput["outcome"][])(
155
- "writes metadata.outcome = %s for every AgentActionOutcome member",
196
+ ] satisfies RecordAuditActionInput["outcome"][])(
197
+ "writes metadata.outcome = %s for every AuditActionOutcome member",
156
198
  async (outcome) => {
157
199
  const { db, create } = stubDb();
158
- await recordAgentAction({ ...BASE_INPUT, outcome }, db);
200
+ await recordAuditAction({ ...BASE_INPUT, outcome }, db);
159
201
  const row = firstWrittenRow(create);
160
202
  expect(row.metadata.outcome).toBe(outcome);
161
203
  },
@@ -163,14 +205,14 @@ describe("AC-1 — exactly one row, carrying the five facts", () => {
163
205
 
164
206
  it("omits createdAt so the database clock supplies it — an agent cannot backdate its own row", async () => {
165
207
  const { db, create } = stubDb();
166
- await recordAgentAction(BASE_INPUT, db);
208
+ await recordAuditAction(BASE_INPUT, db);
167
209
  const row = firstWrittenRow(create) as WrittenRow & { createdAt?: unknown };
168
210
  expect(row.createdAt).toBeUndefined();
169
211
  });
170
212
 
171
213
  it("writes an id satisfying zAuditLogId and the migration's literal CHECK regex", async () => {
172
214
  const { db, create } = stubDb();
173
- await recordAgentAction(BASE_INPUT, db);
215
+ await recordAuditAction(BASE_INPUT, db);
174
216
  const row = firstWrittenRow(create);
175
217
  // database/migrations/20260713192429_prefixed_uuid_entity_ids/migration.sql:158
176
218
  expect(row.id).toMatch(
@@ -185,7 +227,7 @@ describe("AC-1 — exactly one row, carrying the five facts", () => {
185
227
  describe("AC-2 — personal data never reaches the stored row in clear form", () => {
186
228
  it("redacts an email and phone number from summary/failureReason on the serialized row", async () => {
187
229
  const { db, create } = stubDb();
188
- await recordAgentAction(
230
+ await recordAuditAction(
189
231
  {
190
232
  ...BASE_INPUT,
191
233
  outcome: "failed",
@@ -206,7 +248,7 @@ describe("AC-2 — personal data never reaches the stored row in clear form", ()
206
248
  const fullWidthAt = "@";
207
249
  const cyrillicA = "а"; // homoglyph for latin "a" — NOT folded by NFKC
208
250
  const summary = `contact jane.doe${fullWidthAt}ex${cyrillicA}mple.com`;
209
- await recordAgentAction({ ...BASE_INPUT, summary }, db);
251
+ await recordAuditAction({ ...BASE_INPUT, summary }, db);
210
252
  const row = firstWrittenRow(create);
211
253
  const serialized = JSON.stringify(row);
212
254
  expect(serialized).not.toContain(summary);
@@ -217,12 +259,13 @@ describe("AC-2 — personal data never reaches the stored row in clear form", ()
217
259
  ["tool", { tool: "refund_jane.doe@example.com" }],
218
260
  ["targetType", { targetType: "jane@example.com" }],
219
261
  ["targetId", { targetId: "jane@example.com" }],
220
- ["actorId", { actorId: "agent jane@example.com" }],
221
- ] as [string, Partial<RecordAgentActionInput>][])(
262
+ ["actorId", { actor: agentActor("agent jane@example.com") }],
263
+ ["onBehalfOf", { actor: { ...agentActor("agent_abc123"), onBehalfOfUserId: "jane@example.com" as Id<"user"> } }],
264
+ ] as [string, Partial<RecordAuditActionInput>][])(
222
265
  "refuses a personal-data-shaped %s rather than writing it verbatim",
223
266
  async (_name, override) => {
224
267
  const { db, create } = stubDb();
225
- const result = await recordAgentAction(
268
+ const result = await recordAuditAction(
226
269
  { ...BASE_INPUT, ...override },
227
270
  db,
228
271
  );
@@ -241,11 +284,11 @@ describe("AC-2 — personal data never reaches the stored row in clear form", ()
241
284
  it.each([
242
285
  ["summary", { summary: "a".repeat(2001) }],
243
286
  ["failureReason", { failureReason: "a".repeat(2001) }],
244
- ] as [string, Partial<RecordAgentActionInput>][])(
287
+ ] as [string, Partial<RecordAuditActionInput>][])(
245
288
  "refuses a %s over the 2000-character cap rather than truncating it",
246
289
  async (_name, override) => {
247
290
  const { db, create } = stubDb();
248
- const result = await recordAgentAction(
291
+ const result = await recordAuditAction(
249
292
  { ...BASE_INPUT, ...override },
250
293
  db,
251
294
  );
@@ -257,7 +300,7 @@ describe("AC-2 — personal data never reaches the stored row in clear form", ()
257
300
 
258
301
  it("refuses an idempotencyKey outside the required identifier grammar (a space)", async () => {
259
302
  const { db, create } = stubDb();
260
- const result = await recordAgentAction(
303
+ const result = await recordAuditAction(
261
304
  { ...BASE_INPUT, idempotencyKey: "req 1" },
262
305
  db,
263
306
  );
@@ -266,13 +309,14 @@ describe("AC-2 — personal data never reaches the stored row in clear form", ()
266
309
  });
267
310
 
268
311
  it.each([
269
- ["actorId", { actorId: "4155550134" }],
312
+ ["actorId", { actor: userActor("4155550134") }],
313
+ ["onBehalfOf", { actor: { ...agentActor("agent_abc123"), onBehalfOfUserId: "4155550134" as Id<"user"> } }],
270
314
  ["idempotencyKey", { idempotencyKey: "4155550134" }],
271
- ] as [string, Partial<RecordAgentActionInput>][])(
315
+ ] as [string, Partial<RecordAuditActionInput>][])(
272
316
  "refuses a charset-valid but personal-data-shaped %s (a bare digit run) rather than silently rewriting an identifier",
273
317
  async (_name, override) => {
274
318
  const { db, create } = stubDb();
275
- const result = await recordAgentAction(
319
+ const result = await recordAuditAction(
276
320
  { ...BASE_INPUT, ...override },
277
321
  db,
278
322
  );
@@ -284,11 +328,11 @@ describe("AC-2 — personal data never reaches the stored row in clear form", ()
284
328
  it.each([
285
329
  ["tool", { tool: "refund" }],
286
330
  ["summary", { summary: "notehere" }],
287
- ] as [string, Partial<RecordAgentActionInput>][])(
331
+ ] as [string, Partial<RecordAuditActionInput>][])(
288
332
  "refuses a %s containing a NUL character — a reliable audit-disable switch if it reached Postgres",
289
333
  async (_name, override) => {
290
334
  const { db, create } = stubDb();
291
- const result = await recordAgentAction(
335
+ const result = await recordAuditAction(
292
336
  { ...BASE_INPUT, ...override },
293
337
  db,
294
338
  );
@@ -299,7 +343,7 @@ describe("AC-2 — personal data never reaches the stored row in clear form", ()
299
343
 
300
344
  it("never stores a hash or pseudonym of the redacted value", async () => {
301
345
  const { db, create } = stubDb();
302
- await recordAgentAction(
346
+ await recordAuditAction(
303
347
  { ...BASE_INPUT, summary: "contact jane.doe@example.com" },
304
348
  db,
305
349
  );
@@ -309,30 +353,30 @@ describe("AC-2 — personal data never reaches the stored row in clear form", ()
309
353
 
310
354
  it("writes exactly the allow-listed metadata keys on the success path", async () => {
311
355
  const { db, create } = stubDb();
312
- await recordAgentAction({ ...BASE_INPUT, summary: "ok" }, db);
356
+ await recordAuditAction({ ...BASE_INPUT, summary: "ok" }, db);
313
357
  const row = firstWrittenRow(create);
314
358
  expect(Object.keys(row.metadata).sort()).toEqual(
315
- ["idempotencyKey", "outcome", "summary", "tool", "v"].sort(),
359
+ ["idempotencyKey", "onBehalfOf", "outcome", "summary", "tool", "v"].sort(),
316
360
  );
317
361
  });
318
362
 
319
363
  it("adds failureReason to the allow-listed metadata keys on the failure path", async () => {
320
364
  const { db, create } = stubDb();
321
- await recordAgentAction(
365
+ await recordAuditAction(
322
366
  { ...BASE_INPUT, outcome: "failed", failureReason: "declined" },
323
367
  db,
324
368
  );
325
369
  const row = firstWrittenRow(create);
326
370
  expect(Object.keys(row.metadata).sort()).toEqual(
327
- ["failureReason", "idempotencyKey", "outcome", "tool", "v"].sort(),
371
+ ["failureReason", "idempotencyKey", "onBehalfOf", "outcome", "tool", "v"].sort(),
328
372
  );
329
373
  });
330
374
 
331
375
  it("declares no member whose purpose is a buyer's identity", () => {
332
- void recordAgentAction({
376
+ void recordAuditAction({
333
377
  ...BASE_INPUT,
334
378
  // @ts-expect-error — `buyerEmail` is not a declared member of
335
- // RecordAgentActionInput (D5(a), D11). This proves the member is
379
+ // RecordAuditActionInput (D5(a), D11). This proves the member is
336
380
  // UNDECLARED, not that no declared member can carry personal data —
337
381
  // `summary` can (D5 concedes this; § 9 SEC-12).
338
382
  buyerEmail: "buyer@example.com",
@@ -351,7 +395,7 @@ describe("AC-2 — personal data never reaches the stored row in clear form", ()
351
395
  describe("AC-3 — a write failure is surfaced, and the block decision is explicit in the code", () => {
352
396
  it("resolves with ok:false rather than throwing on a write failure", async () => {
353
397
  const { db } = stubDb(jest.fn().mockRejectedValue(new Error("boom")));
354
- const result = await recordAgentAction(BASE_INPUT, db);
398
+ const result = await recordAuditAction(BASE_INPUT, db);
355
399
  expect(result).toEqual({
356
400
  ok: false,
357
401
  error: {
@@ -365,7 +409,7 @@ describe("AC-3 — a write failure is surfaced, and the block decision is explic
365
409
  it("never returns or logs the raw error message — Prisma's data argument IS the audit row", async () => {
366
410
  const sentinel = "SENTINEL-jane.doe@example.com";
367
411
  const { db } = stubDb(jest.fn().mockRejectedValue(new Error(sentinel)));
368
- const result = await recordAgentAction(BASE_INPUT, db);
412
+ const result = await recordAuditAction(BASE_INPUT, db);
369
413
  expect(result.ok).toBe(false);
370
414
  if (!result.ok) expect(result.error.message).not.toContain(sentinel);
371
415
  expect(JSON.stringify(mockLoggerError.mock.calls[0])).not.toContain(
@@ -375,7 +419,7 @@ describe("AC-3 — a write failure is surfaced, and the block decision is explic
375
419
 
376
420
  it("logs exactly once at error, with a code but no personal data", async () => {
377
421
  const { db } = stubDb(jest.fn().mockRejectedValue({ code: "P2025" }));
378
- await recordAgentAction(
422
+ await recordAuditAction(
379
423
  { ...BASE_INPUT, summary: "contact jane.doe@example.com" },
380
424
  db,
381
425
  );
@@ -399,7 +443,8 @@ describe("AC-4 — a replay produces no duplicate row", () => {
399
443
  workspaceId: TENANT.workspaceId,
400
444
  actorId: "agent_abc123",
401
445
  actorType: "agent",
402
- action: "agent.commerce.refund",
446
+ onBehalfOf: USER_ID,
447
+ action: "commerce.refund",
403
448
  targetType: "lead",
404
449
  targetId: "lead_xyz",
405
450
  outcome: "succeeded",
@@ -452,11 +497,11 @@ describe("AC-4 — a replay produces no duplicate row", () => {
452
497
  tool: "refund",
453
498
  idempotencyKey: "req_shared",
454
499
  };
455
- const first = await recordAgentAction(
500
+ const first = await recordAuditAction(
456
501
  { ...shared, outcome: "refused", summary: "decoy" },
457
502
  db,
458
503
  );
459
- const second = await recordAgentAction(
504
+ const second = await recordAuditAction(
460
505
  { ...shared, outcome: "succeeded", summary: "real refund" },
461
506
  db,
462
507
  );
@@ -482,8 +527,8 @@ describe("AC-4 — a replay produces no duplicate row", () => {
482
527
  .mockResolvedValueOnce({ id: "ignored" })
483
528
  .mockRejectedValueOnce({ code: "P2002" });
484
529
  const { db } = stubDb(create);
485
- const first = await recordAgentAction(BASE_INPUT, db);
486
- const second = await recordAgentAction(BASE_INPUT, db);
530
+ const first = await recordAuditAction(BASE_INPUT, db);
531
+ const second = await recordAuditAction(BASE_INPUT, db);
487
532
  expect(first).toEqual({
488
533
  ok: true,
489
534
  outcome: "recorded",
@@ -499,7 +544,7 @@ describe("AC-4 — a replay produces no duplicate row", () => {
499
544
 
500
545
  it("refuses a digit-heavy dashed uuid as an idempotencyKey — the personal-data scan reads it as a phone number, so a caller must re-spell its entropy (#6231)", async () => {
501
546
  const { db, create } = stubDb();
502
- const result = await recordAgentAction(
547
+ const result = await recordAuditAction(
503
548
  { ...BASE_INPUT, idempotencyKey: "01234567-8901-4234-8567-890123456789" },
504
549
  db,
505
550
  );
@@ -518,7 +563,7 @@ describe("AC-4 — a replay produces no duplicate row", () => {
518
563
 
519
564
  it("logs the duplicate outcome at warn, naming the colliding row — a collision is never silent regardless of caller (#6231)", async () => {
520
565
  const { db } = stubDb(jest.fn().mockRejectedValue({ code: "P2002" }));
521
- const result = await recordAgentAction(BASE_INPUT, db);
566
+ const result = await recordAuditAction(BASE_INPUT, db);
522
567
  expect(result).toEqual({
523
568
  ok: true,
524
569
  outcome: "duplicate",
@@ -545,7 +590,7 @@ describe("AC-4 — a replay produces no duplicate row", () => {
545
590
 
546
591
  it("classifies a non-P2002 rejection as write_failed, never as duplicate", async () => {
547
592
  const { db } = stubDb(jest.fn().mockRejectedValue({ code: "P2025" }));
548
- const result = await recordAgentAction(BASE_INPUT, db);
593
+ const result = await recordAuditAction(BASE_INPUT, db);
549
594
  expect(result).toEqual({
550
595
  ok: false,
551
596
  error: {
@@ -562,7 +607,7 @@ describe("AC-4 — a replay produces no duplicate row", () => {
562
607
  describe("targetType/targetId pass-through", () => {
563
608
  it("validates targetId against its named entity's own id grammar when targetType names a registered entity", async () => {
564
609
  const { db, create } = stubDb();
565
- const result = await recordAgentAction(
610
+ const result = await recordAuditAction(
566
611
  { ...BASE_INPUT, targetType: "workspace", targetId: TENANT.workspaceId },
567
612
  db,
568
613
  );
@@ -574,7 +619,7 @@ describe("targetType/targetId pass-through", () => {
574
619
 
575
620
  it("refuses a targetId that does not match its named entity's id grammar", async () => {
576
621
  const { db, create } = stubDb();
577
- const result = await recordAgentAction(
622
+ const result = await recordAuditAction(
578
623
  {
579
624
  ...BASE_INPUT,
580
625
  targetType: "workspace",
@@ -588,7 +633,7 @@ describe("targetType/targetId pass-through", () => {
588
633
 
589
634
  it("refuses a malformed tenant.workspaceId", async () => {
590
635
  const { db, create } = stubDb();
591
- const result = await recordAgentAction(
636
+ const result = await recordAuditAction(
592
637
  {
593
638
  ...BASE_INPUT,
594
639
  tenant: {
@@ -618,3 +663,275 @@ describe("redactPersonalData (exported pure helper)", () => {
618
663
  );
619
664
  });
620
665
  });
666
+
667
+ // ─── #7636 D7, #3591 D8 — a registry user or agent id is never "personal data"
668
+
669
+ describe("actor ids — a well-formed user or agent id (#7636 D7, #3591 D8)", () => {
670
+ // Real DB-minted shapes whose hex happens to contain a long digit run: the
671
+ // phone pattern reads `-` as a digit separator, so the bare scan flagged
672
+ // about a third of real ids and dropped their audit rows.
673
+ const DIGIT_HEAVY_USER = "user_01a1081d-15ec-7fcf-a280-4cb63886627f";
674
+ const DIGIT_HEAVY_SPEC_USER = "user_01923456-7890-7abc-8def-0123456789ab";
675
+ const DIGIT_HEAVY_AGENT = "agent_01923456-7890-7abc-8def-0123456789ab";
676
+
677
+ it("writes the row for a digit-heavy user_<uuidv7> actor", async () => {
678
+ const { db, create } = stubDb();
679
+ const result = await recordAuditAction({ ...BASE_INPUT, actor: userActor(DIGIT_HEAVY_USER) }, db);
680
+ expect(result.ok).toBe(true);
681
+ expect(firstWrittenRow(create).actorId).toBe(DIGIT_HEAVY_USER);
682
+ });
683
+
684
+ it("the ids really are phone-shaped to the scan — the exemption, not the id, is what admits them", () => {
685
+ for (const id of [DIGIT_HEAVY_SPEC_USER, DIGIT_HEAVY_AGENT]) {
686
+ expect(redactPersonalData(id)).toContain("[REDACTED:");
687
+ }
688
+ });
689
+
690
+ it("records a digit-heavy user id as a person actor", async () => {
691
+ const { db, create } = stubDb();
692
+ const result = await recordAuditAction({ ...BASE_INPUT, actor: userActor(DIGIT_HEAVY_SPEC_USER) }, db);
693
+ expect(result.ok).toBe(true);
694
+ expect(firstWrittenRow(create)).toMatchObject({ actorType: "user", actorId: DIGIT_HEAVY_SPEC_USER });
695
+ });
696
+
697
+ it("records a digit-heavy agent id acting for a digit-heavy user id", async () => {
698
+ const { db, create } = stubDb();
699
+ const result = await recordAuditAction(
700
+ {
701
+ ...BASE_INPUT,
702
+ actor: {
703
+ type: "agent",
704
+ agentId: DIGIT_HEAVY_AGENT as Id<"agent">,
705
+ onBehalfOfUserId: DIGIT_HEAVY_SPEC_USER as Id<"user">,
706
+ },
707
+ },
708
+ db,
709
+ );
710
+ expect(result.ok).toBe(true);
711
+ const row = firstWrittenRow(create);
712
+ expect(row).toMatchObject({ actorType: "agent", actorId: DIGIT_HEAVY_AGENT });
713
+ expect(row.metadata.onBehalfOf).toBe(DIGIT_HEAVY_SPEC_USER);
714
+ });
715
+
716
+ it("still refuses a phone-shaped actor id that is not a registry id", async () => {
717
+ const { db, create } = stubDb();
718
+ const result = await recordAuditAction({ ...BASE_INPUT, actor: agentActor("agent-555-867-5309") }, db);
719
+ expect(result.ok).toBe(false);
720
+ expect(create).not.toHaveBeenCalled();
721
+ });
722
+
723
+ it("still scans every other identifier — a registry-shaped idempotencyKey is not exempt", async () => {
724
+ const { db, create } = stubDb();
725
+ const result = await recordAuditAction({ ...BASE_INPUT, idempotencyKey: DIGIT_HEAVY_SPEC_USER }, db);
726
+ expect(result.ok).toBe(false);
727
+ expect(create).not.toHaveBeenCalled();
728
+ });
729
+ });
730
+
731
+ // ─── #3591 D8 — the route helpers ───────────────────────────────────────────
732
+
733
+ describe("freshAuditIdempotencyKey (#3591 D8)", () => {
734
+ it("is 32 hex characters in `_`-joined runs of at most six, fresh per call", () => {
735
+ const first = freshAuditIdempotencyKey();
736
+ expect(first).toMatch(/^[0-9a-f]{6}(?:_[0-9a-f]{1,6})*$/);
737
+ expect(first.replace(/_/g, "")).toHaveLength(32);
738
+ expect(freshAuditIdempotencyKey()).not.toBe(first);
739
+ });
740
+ });
741
+
742
+ describe("auditActorFor (#3591 D8)", () => {
743
+ it("passes request.actor through, and falls back to the tenant's own person with a warning", () => {
744
+ const agent = agentActor("agent_abc123");
745
+ expect(auditActorFor(agent, TENANT)).toBe(agent);
746
+ expect(mockLoggerWarn).not.toHaveBeenCalled();
747
+ expect(auditActorFor(undefined, TENANT)).toEqual({ type: "user", userId: USER_ID });
748
+ expect(mockLoggerWarn).toHaveBeenCalledTimes(1);
749
+ });
750
+ });
751
+
752
+ describe("recordAgentWrite (#3591 D8)", () => {
753
+ const WRITE = {
754
+ tenant: TENANT,
755
+ domain: "inbox",
756
+ tool: "mark_message_done",
757
+ targetType: "lead",
758
+ targetId: "lead_0190f3a2-7c1d-7e4a-9b2c-000000000004",
759
+ };
760
+
761
+ it("writes nothing for a person or an unknown actor", async () => {
762
+ const { db, create } = stubDb();
763
+ await recordAgentWrite(userActor(USER_ID), WRITE, { ok: true }, db);
764
+ await recordAgentWrite(undefined, WRITE, { ok: true }, db);
765
+ expect(create).not.toHaveBeenCalled();
766
+ });
767
+
768
+ it("writes one succeeded row for an agent's write that succeeded", async () => {
769
+ const { db, create } = stubDb();
770
+ await recordAgentWrite(agentActor("agent_abc123"), WRITE, { ok: true }, db);
771
+ expect(create).toHaveBeenCalledTimes(1);
772
+ const row = firstWrittenRow(create);
773
+ expect(row).toMatchObject({
774
+ actorType: "agent",
775
+ actorId: "agent_abc123",
776
+ action: "inbox.mark_message_done",
777
+ targetType: "lead",
778
+ });
779
+ expect(row.metadata).toMatchObject({ outcome: "succeeded", onBehalfOf: USER_ID });
780
+ expect(row.metadata).not.toHaveProperty("failureReason");
781
+ });
782
+
783
+ it("writes one failed row carrying the service's error kind for an agent's write that failed", async () => {
784
+ const { db, create } = stubDb();
785
+ await recordAgentWrite(
786
+ agentActor("agent_abc123"),
787
+ WRITE,
788
+ { ok: false, error: { kind: "not_found" } },
789
+ db,
790
+ );
791
+ const row = firstWrittenRow(create);
792
+ expect(row.metadata).toMatchObject({ outcome: "failed", failureReason: "not_found" });
793
+ });
794
+
795
+ it("logs a failed audit write once at error and resolves, so the caller's response is unchanged", async () => {
796
+ const { db } = stubDb(jest.fn().mockRejectedValue(new Error("boom")));
797
+ await expect(
798
+ recordAgentWrite(agentActor("agent_abc123"), WRITE, { ok: true }, db),
799
+ ).resolves.toBeUndefined();
800
+ const messages = mockLoggerError.mock.calls.map((call) => call[1] as string);
801
+ expect(messages).toEqual(["[audit-log] audit row write failed"]);
802
+ });
803
+
804
+ it("logs a refused audit row once at error and resolves", async () => {
805
+ const { db, create } = stubDb();
806
+ await expect(
807
+ recordAgentWrite(agentActor("agent_abc123"), { ...WRITE, domain: "In Box" }, { ok: true }, db),
808
+ ).resolves.toBeUndefined();
809
+ expect(create).not.toHaveBeenCalled();
810
+ const messages = mockLoggerError.mock.calls.map((call) => call[1] as string);
811
+ expect(messages).toEqual(["[audit-log] agent write audit refused"]);
812
+ });
813
+ });
814
+
815
+ // #3591 PR-B — a registry id is an identifier, not personal data, in free
816
+ // text too: the agent lifecycle rows name the person they were made for by
817
+ // user id in `summary`, and a digit-heavy id must survive the scan.
818
+ describe("summary and failureReason keep a registry user_ or agent_ id whole (#3591 D8)", () => {
819
+ const DIGIT_HEAVY_USER = "user_01923456-7890-7abc-8def-0123456789ab";
820
+ const DIGIT_HEAVY_AGENT = "agent_01923456-7890-7abc-8def-0123456789ab";
821
+
822
+ async function storedSummary(summary: string): Promise<unknown> {
823
+ const { db, create } = stubDb();
824
+ const result = await recordAuditAction({ ...BASE_INPUT, summary }, db);
825
+ expect(result.ok).toBe(true);
826
+ return firstWrittenRow(create).metadata.summary;
827
+ }
828
+
829
+ it("the fixture id really is phone-shaped to the bare scan", () => {
830
+ expect(redactPersonalData(DIGIT_HEAVY_USER)).toContain("[REDACTED:");
831
+ });
832
+
833
+ it("a summary naming a digit-heavy user id is stored as written", async () => {
834
+ expect(await storedSummary(`responsibleUserId=${DIGIT_HEAVY_USER}`)).toBe(
835
+ `responsibleUserId=${DIGIT_HEAVY_USER}`,
836
+ );
837
+ });
838
+
839
+ it("keeps the ids and still redacts the personal data around them", async () => {
840
+ const out = (await storedSummary(
841
+ `responsibleUserId=${DIGIT_HEAVY_USER} agent=${DIGIT_HEAVY_AGENT} call +1 415 555 0100 or jane@example.com`,
842
+ )) as string;
843
+ expect(out).toContain(`responsibleUserId=${DIGIT_HEAVY_USER}`);
844
+ expect(out).toContain(`agent=${DIGIT_HEAVY_AGENT}`);
845
+ expect(out).toContain("[REDACTED:phone]");
846
+ expect(out).toContain("[REDACTED:email]");
847
+ expect(out).not.toContain("jane@example.com");
848
+ });
849
+
850
+ it("still scans a digit run glued onto an id, and an id of another entity", async () => {
851
+ expect(await storedSummary(`${DIGIT_HEAVY_USER}5550100`)).toContain("[REDACTED:");
852
+ expect(await storedSummary("lead_01923456-7890-7abc-8def-0123456789ab")).toContain("[REDACTED:");
853
+ });
854
+
855
+ it("does not exempt a phone number dressed up as an id, nor an id inside a longer token", async () => {
856
+ for (const disguised of [
857
+ "user_+1-415-555-0100",
858
+ "user_4155550100-7abc-8def-0123456789ab",
859
+ `x${DIGIT_HEAVY_USER}`,
860
+ `${DIGIT_HEAVY_USER}.`,
861
+ ]) {
862
+ expect(await storedSummary(`responsibleUserId=${disguised}`)).toContain("[REDACTED:");
863
+ }
864
+ });
865
+
866
+ it("still catches a phone number written with spaces between exempt ids", async () => {
867
+ const out = (await storedSummary(`${DIGIT_HEAVY_USER} +1 415 555 0100 ${DIGIT_HEAVY_AGENT}`)) as string;
868
+ expect(out).toBe(`${DIGIT_HEAVY_USER} [REDACTED:phone] ${DIGIT_HEAVY_AGENT}`);
869
+ });
870
+
871
+ it("applies to failureReason the same way", async () => {
872
+ const { db, create } = stubDb();
873
+ await recordAuditAction(
874
+ { ...BASE_INPUT, outcome: "failed", failureReason: `not a member: ${DIGIT_HEAVY_USER}` },
875
+ db,
876
+ );
877
+ expect(firstWrittenRow(create).metadata.failureReason).toBe(`not a member: ${DIGIT_HEAVY_USER}`);
878
+ });
879
+ });
880
+
881
+ describe("recordAgentWrite given the request (#3591 PR-B)", () => {
882
+ const AGENT_ID = "agent_0190f3a2-7c1d-7e4a-9b2c-000000000005";
883
+ const WRITE = {
884
+ tenant: TENANT,
885
+ domain: "inbox",
886
+ tool: "set_application_featured",
887
+ targetType: "project_listing",
888
+ targetId: "listing_abc123",
889
+ };
890
+
891
+ it("reads request.actor when it is set", async () => {
892
+ const { db, create } = stubDb();
893
+ await recordAgentWrite(
894
+ { actor: agentActor(AGENT_ID), agent: { agentId: AGENT_ID as Id<"agent"> } },
895
+ WRITE,
896
+ { ok: true },
897
+ db,
898
+ );
899
+ expect(firstWrittenRow(create)).toMatchObject({ actorType: "agent", actorId: AGENT_ID });
900
+ expect(mockLoggerError).not.toHaveBeenCalled();
901
+ });
902
+
903
+ it("an agent request with no request.actor is logged at error and still recorded, from request.agent", async () => {
904
+ const { db, create } = stubDb();
905
+ await recordAgentWrite({ agent: { agentId: AGENT_ID as Id<"agent"> } }, WRITE, { ok: true }, db);
906
+
907
+ expect(create).toHaveBeenCalledTimes(1);
908
+ const row = firstWrittenRow(create);
909
+ expect(row).toMatchObject({
910
+ actorType: "agent",
911
+ actorId: AGENT_ID,
912
+ action: "inbox.set_application_featured",
913
+ });
914
+ expect(row.metadata).toMatchObject({ onBehalfOf: USER_ID, outcome: "succeeded" });
915
+ expect(mockLoggerError).toHaveBeenCalledTimes(1);
916
+ expect(mockLoggerError.mock.calls[0]![0]).toMatchObject({ actorId: AGENT_ID });
917
+ expect(mockLoggerError.mock.calls[0]![1]).toBe(
918
+ "[audit-log] agent write without request.actor; recording from request.agent",
919
+ );
920
+ });
921
+
922
+ it("a request with neither, or a person's request, records nothing and logs nothing", async () => {
923
+ const { db, create } = stubDb();
924
+ await recordAgentWrite({}, WRITE, { ok: true }, db);
925
+ await recordAgentWrite({ actor: userActor(USER_ID) }, WRITE, { ok: true }, db);
926
+ expect(create).not.toHaveBeenCalled();
927
+ expect(mockLoggerError).not.toHaveBeenCalled();
928
+ });
929
+
930
+ it("the refused-row error line names the actor id", async () => {
931
+ const { db } = stubDb();
932
+ await recordAgentWrite({ actor: agentActor(AGENT_ID) }, { ...WRITE, domain: "In Box" }, { ok: true }, db);
933
+ expect(mockLoggerError).toHaveBeenCalledTimes(1);
934
+ expect(mockLoggerError.mock.calls[0]![0]).toMatchObject({ actorId: AGENT_ID });
935
+ expect(mockLoggerError.mock.calls[0]![1]).toBe("[audit-log] agent write audit refused");
936
+ });
937
+ });