sentinelayer-cli 0.6.2 → 0.8.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 (159) hide show
  1. package/README.md +996 -996
  2. package/bin/create-sentinelayer.js +5 -5
  3. package/bin/sentinelayer-cli.js +4 -4
  4. package/bin/sl.js +5 -5
  5. package/package.json +64 -63
  6. package/src/agents/jules/config/definition.js +160 -160
  7. package/src/agents/jules/config/system-prompt.js +182 -182
  8. package/src/agents/jules/error-intake.js +51 -51
  9. package/src/agents/jules/fix-cycle.js +17 -17
  10. package/src/agents/jules/loop.js +457 -450
  11. package/src/agents/jules/pulse.js +10 -10
  12. package/src/agents/jules/stream.js +187 -186
  13. package/src/agents/jules/swarm/file-scanner.js +74 -74
  14. package/src/agents/jules/swarm/index.js +11 -11
  15. package/src/agents/jules/swarm/orchestrator.js +362 -362
  16. package/src/agents/jules/swarm/pattern-hunter.js +123 -123
  17. package/src/agents/jules/swarm/sub-agent.js +311 -309
  18. package/src/agents/jules/tools/aidenid-email.js +189 -189
  19. package/src/agents/jules/tools/auth-audit.js +1699 -1691
  20. package/src/agents/jules/tools/dispatch.js +340 -335
  21. package/src/agents/jules/tools/file-edit.js +2 -2
  22. package/src/agents/jules/tools/file-read.js +2 -2
  23. package/src/agents/jules/tools/frontend-analyze.js +570 -570
  24. package/src/agents/jules/tools/glob.js +2 -2
  25. package/src/agents/jules/tools/grep.js +2 -2
  26. package/src/agents/jules/tools/index.js +29 -29
  27. package/src/agents/jules/tools/path-guards.js +2 -2
  28. package/src/agents/jules/tools/runtime-audit.js +507 -507
  29. package/src/agents/jules/tools/shell.js +2 -2
  30. package/src/agents/jules/tools/url-policy.js +100 -100
  31. package/src/agents/persona-visuals.js +64 -61
  32. package/src/agents/shared-tools/dispatch-core.js +320 -315
  33. package/src/agents/shared-tools/file-edit.js +180 -180
  34. package/src/agents/shared-tools/file-read.js +100 -100
  35. package/src/agents/shared-tools/glob.js +168 -168
  36. package/src/agents/shared-tools/grep.js +228 -228
  37. package/src/agents/shared-tools/index.js +46 -46
  38. package/src/agents/shared-tools/path-guards.js +161 -161
  39. package/src/agents/shared-tools/shell.js +383 -383
  40. package/src/ai/aidenid.js +1021 -1009
  41. package/src/ai/client.js +553 -553
  42. package/src/ai/domain-target-store.js +268 -268
  43. package/src/ai/identity-store.js +270 -270
  44. package/src/ai/proxy.js +137 -137
  45. package/src/ai/site-store.js +145 -145
  46. package/src/audit/agents/architecture.js +180 -180
  47. package/src/audit/agents/compliance.js +179 -179
  48. package/src/audit/agents/documentation.js +165 -165
  49. package/src/audit/agents/performance.js +145 -145
  50. package/src/audit/agents/security.js +215 -215
  51. package/src/audit/agents/testing.js +172 -172
  52. package/src/audit/orchestrator.js +557 -557
  53. package/src/audit/package.js +204 -204
  54. package/src/audit/registry.js +284 -284
  55. package/src/audit/replay.js +103 -103
  56. package/src/auth/gate.js +400 -371
  57. package/src/auth/http.js +681 -611
  58. package/src/auth/service.js +1106 -1106
  59. package/src/auth/session-store.js +813 -813
  60. package/src/cli.js +257 -252
  61. package/src/commands/ai/identity-lifecycle.js +1338 -1338
  62. package/src/commands/ai/provision-governance.js +1272 -1272
  63. package/src/commands/ai/shared.js +147 -147
  64. package/src/commands/ai.js +11 -11
  65. package/src/commands/apply.js +12 -12
  66. package/src/commands/audit.js +1171 -1166
  67. package/src/commands/auth.js +419 -419
  68. package/src/commands/chat.js +191 -191
  69. package/src/commands/config.js +184 -184
  70. package/src/commands/cost.js +311 -311
  71. package/src/commands/daemon/core.js +850 -850
  72. package/src/commands/daemon/extended.js +1048 -1048
  73. package/src/commands/daemon/shared.js +213 -213
  74. package/src/commands/daemon.js +11 -11
  75. package/src/commands/guide.js +174 -174
  76. package/src/commands/ingest.js +58 -58
  77. package/src/commands/init.js +55 -55
  78. package/src/commands/legacy-args.js +10 -10
  79. package/src/commands/mcp.js +461 -461
  80. package/src/commands/omargate.js +29 -29
  81. package/src/commands/persona.js +20 -20
  82. package/src/commands/plugin.js +260 -260
  83. package/src/commands/policy.js +132 -132
  84. package/src/commands/prompt.js +238 -238
  85. package/src/commands/review.js +704 -704
  86. package/src/commands/scan.js +872 -872
  87. package/src/commands/session.js +590 -0
  88. package/src/commands/spec.js +778 -716
  89. package/src/commands/swarm.js +651 -651
  90. package/src/commands/telemetry.js +202 -202
  91. package/src/commands/watch.js +511 -511
  92. package/src/config/agent-dictionary.js +182 -182
  93. package/src/config/io.js +56 -56
  94. package/src/config/paths.js +18 -18
  95. package/src/config/schema.js +55 -55
  96. package/src/config/service.js +184 -184
  97. package/src/cost/budget.js +235 -235
  98. package/src/cost/history.js +188 -188
  99. package/src/cost/tracker.js +171 -171
  100. package/src/daemon/artifact-lineage.js +534 -534
  101. package/src/daemon/assignment-ledger.js +966 -770
  102. package/src/daemon/ast-parser-layer.js +258 -258
  103. package/src/daemon/budget-governor.js +633 -633
  104. package/src/daemon/callgraph-overlay.js +646 -646
  105. package/src/daemon/error-worker.js +1209 -626
  106. package/src/daemon/fix-cycle.js +384 -377
  107. package/src/daemon/hybrid-mapper.js +929 -929
  108. package/src/daemon/ingest-refresh.js +10 -9
  109. package/src/daemon/jira-lifecycle.js +767 -632
  110. package/src/daemon/operator-control.js +657 -657
  111. package/src/daemon/pulse.js +327 -327
  112. package/src/daemon/reliability-lane.js +471 -471
  113. package/src/daemon/scope-engine.js +1068 -0
  114. package/src/daemon/watchdog.js +971 -971
  115. package/src/events/schema.js +190 -0
  116. package/src/guide/generator.js +316 -316
  117. package/src/ingest/engine.js +918 -918
  118. package/src/interactive/index.js +97 -97
  119. package/src/legacy-cli.js +3161 -2994
  120. package/src/mcp/registry.js +695 -695
  121. package/src/memory/blackboard.js +301 -301
  122. package/src/memory/retrieval.js +581 -581
  123. package/src/plugin/manifest.js +553 -553
  124. package/src/policy/packs.js +144 -144
  125. package/src/prompt/generator.js +136 -118
  126. package/src/review/ai-review.js +679 -679
  127. package/src/review/local-review.js +1351 -1305
  128. package/src/review/omargate-interactive.js +68 -68
  129. package/src/review/omargate-orchestrator.js +404 -300
  130. package/src/review/persona-prompts.js +296 -296
  131. package/src/review/replay.js +235 -235
  132. package/src/review/report.js +664 -664
  133. package/src/review/scan-modes.js +48 -42
  134. package/src/review/spec-binding.js +487 -487
  135. package/src/scaffold/generator.js +67 -67
  136. package/src/scaffold/templates.js +150 -150
  137. package/src/scan/generator.js +418 -418
  138. package/src/scan/gh-secrets.js +107 -107
  139. package/src/session/agent-registry.js +352 -0
  140. package/src/session/daemon.js +801 -0
  141. package/src/session/paths.js +33 -0
  142. package/src/session/runtime-bridge.js +739 -0
  143. package/src/session/store.js +388 -0
  144. package/src/session/stream.js +325 -0
  145. package/src/spec/generator.js +619 -519
  146. package/src/spec/regenerate.js +237 -237
  147. package/src/spec/templates.js +91 -91
  148. package/src/swarm/dashboard.js +247 -247
  149. package/src/swarm/factory.js +363 -363
  150. package/src/swarm/pentest.js +934 -934
  151. package/src/swarm/registry.js +419 -419
  152. package/src/swarm/report.js +158 -158
  153. package/src/swarm/runtime.js +576 -576
  154. package/src/swarm/scenario-dsl.js +272 -272
  155. package/src/telemetry/ledger.js +302 -302
  156. package/src/telemetry/session-tracker.js +234 -234
  157. package/src/telemetry/sync.js +203 -203
  158. package/src/ui/command-hints.js +13 -13
  159. package/src/ui/markdown.js +220 -220
@@ -1,1338 +1,1338 @@
1
- import path from "node:path";
2
- import process from "node:process";
3
-
4
- import pc from "picocolors";
5
-
6
- import {
7
- buildChildIdentityPayload,
8
- createChildIdentity,
9
- getIdentityLineage,
10
- getLatestIdentityExtraction,
11
- listIdentityEvents,
12
- normalizeAidenIdApiUrl,
13
- revokeIdentity,
14
- revokeIdentityChildren,
15
- resolveAidenIdCredentials,
16
- } from "../../ai/aidenid.js";
17
- import {
18
- filterIdentitiesByTags,
19
- findStaleIdentities,
20
- getIdentityById,
21
- listIdentities,
22
- recordProvisionedIdentity,
23
- updateIdentityStatus,
24
- } from "../../ai/identity-store.js";
25
- import { resolveOutputRoot } from "../../config/service.js";
26
- import {
27
- delay,
28
- hasExtractionSignal,
29
- identityIsUnderLegalHold,
30
- meetsConfidenceThreshold,
31
- normalizeIdempotencyKey,
32
- normalizeLegalHoldStatus,
33
- parseConfidenceThreshold,
34
- parseCsvTokens,
35
- parsePositiveInteger,
36
- renderLineageRows,
37
- shouldEmitJson,
38
- stableTimestampForFile,
39
- writeArtifact,
40
- } from "./shared.js";
41
-
42
- export function registerAiIdentityLifecycleCommands({ identity, legalHold }) {
43
- identity
44
- .command("list")
45
- .description("List locally tracked AIdenID identities")
46
- .option("--path <path>", "Workspace path for artifact/config resolution", ".")
47
- .option("--output-dir <path>", "Optional artifact output root override")
48
- .option("--json", "Emit machine-readable output")
49
- .action(async (options, command) => {
50
- const emitJson = shouldEmitJson(options, command);
51
- const targetPath = path.resolve(process.cwd(), String(options.path || "."));
52
- const outputRoot = await resolveOutputRoot({
53
- cwd: targetPath,
54
- outputDirOverride: options.outputDir,
55
- env: process.env,
56
- });
57
- const { registryPath, identities } = await listIdentities({ outputRoot });
58
-
59
- const payload = {
60
- command: "ai identity list",
61
- registryPath,
62
- count: identities.length,
63
- identities,
64
- };
65
-
66
- if (emitJson) {
67
- console.log(JSON.stringify(payload, null, 2));
68
- return;
69
- }
70
-
71
- console.log(pc.bold("AIdenID identity registry"));
72
- console.log(pc.gray(`Registry: ${registryPath}`));
73
- if (identities.length === 0) {
74
- console.log(pc.gray("No tracked identities."));
75
- return;
76
- }
77
- for (const item of identities) {
78
- console.log(
79
- `- ${item.identityId} | ${item.emailAddress || "unknown-email"} | ${item.status} | ${
80
- item.projectId || "no-project"
81
- }`
82
- );
83
- }
84
- });
85
-
86
- identity
87
- .command("show")
88
- .description("Show a tracked identity record")
89
- .argument("<identityId>", "Identity id")
90
- .option("--path <path>", "Workspace path for artifact/config resolution", ".")
91
- .option("--output-dir <path>", "Optional artifact output root override")
92
- .option("--json", "Emit machine-readable output")
93
- .action(async (identityId, options, command) => {
94
- const emitJson = shouldEmitJson(options, command);
95
- const targetPath = path.resolve(process.cwd(), String(options.path || "."));
96
- const outputRoot = await resolveOutputRoot({
97
- cwd: targetPath,
98
- outputDirOverride: options.outputDir,
99
- env: process.env,
100
- });
101
- const { registryPath, identity: identityRecord } = await getIdentityById({
102
- outputRoot,
103
- identityId,
104
- });
105
- if (!identityRecord) {
106
- throw new Error(`Identity '${identityId}' is not present in local registry.`);
107
- }
108
-
109
- const payload = {
110
- command: "ai identity show",
111
- registryPath,
112
- identity: identityRecord,
113
- };
114
- if (emitJson) {
115
- console.log(JSON.stringify(payload, null, 2));
116
- return;
117
- }
118
-
119
- console.log(pc.bold("AIdenID identity"));
120
- console.log(pc.gray(`Registry: ${registryPath}`));
121
- console.log(`${identityRecord.identityId} | ${identityRecord.emailAddress || "unknown-email"}`);
122
- console.log(`status=${identityRecord.status} project=${identityRecord.projectId || "n/a"}`);
123
- });
124
-
125
- legalHold
126
- .command("status")
127
- .description("Show legal-hold status for a tracked identity")
128
- .argument("<identityId>", "Identity id")
129
- .option("--path <path>", "Workspace path for artifact/config resolution", ".")
130
- .option("--output-dir <path>", "Optional artifact output root override")
131
- .option("--json", "Emit machine-readable output")
132
- .action(async (identityId, options, command) => {
133
- const emitJson = shouldEmitJson(options, command);
134
- const targetPath = path.resolve(process.cwd(), String(options.path || "."));
135
- const outputRoot = await resolveOutputRoot({
136
- cwd: targetPath,
137
- outputDirOverride: options.outputDir,
138
- env: process.env,
139
- });
140
- const { registryPath, identity: identityRecord } = await getIdentityById({
141
- outputRoot,
142
- identityId,
143
- });
144
- if (!identityRecord) {
145
- throw new Error(`Identity '${identityId}' is not present in local registry.`);
146
- }
147
-
148
- const underHold = identityIsUnderLegalHold(identityRecord);
149
- const status = underHold ? "HOLD" : normalizeLegalHoldStatus(identityRecord.legalHoldStatus);
150
- const stamp = stableTimestampForFile();
151
- const artifactsDir = path.join(outputRoot, "aidenid", "legal-hold-status");
152
- const outputPath = path.join(
153
- artifactsDir,
154
- `legal-hold-${encodeURIComponent(identityId)}-${stamp}.json`
155
- );
156
- await writeArtifact(outputPath, {
157
- generatedAt: new Date().toISOString(),
158
- identityId,
159
- status,
160
- underHold,
161
- identity: identityRecord,
162
- });
163
-
164
- const payload = {
165
- command: "ai identity legal-hold status",
166
- identityId,
167
- registryPath,
168
- outputPath,
169
- status,
170
- underHold,
171
- };
172
- if (emitJson) {
173
- console.log(JSON.stringify(payload, null, 2));
174
- return;
175
- }
176
-
177
- console.log(pc.bold("AIdenID legal-hold status"));
178
- console.log(pc.gray(`Registry: ${registryPath}`));
179
- console.log(pc.gray(`Artifact: ${outputPath}`));
180
- console.log(`${identityId} | legal_hold=${status}`);
181
- });
182
-
183
- identity
184
- .command("audit")
185
- .description("Audit tracked identities for stale lifecycle records")
186
- .option("--path <path>", "Workspace path for artifact/config resolution", ".")
187
- .option("--output-dir <path>", "Optional artifact output root override")
188
- .option("--stale", "Return only stale identities", true)
189
- .option("--no-stale", "Return full identity inventory")
190
- .option("--json", "Emit machine-readable output")
191
- .action(async (options, command) => {
192
- const emitJson = shouldEmitJson(options, command);
193
- const targetPath = path.resolve(process.cwd(), String(options.path || "."));
194
- const outputRoot = await resolveOutputRoot({
195
- cwd: targetPath,
196
- outputDirOverride: options.outputDir,
197
- env: process.env,
198
- });
199
- const staleScan = await findStaleIdentities({
200
- outputRoot,
201
- });
202
- const staleOnly = Boolean(options.stale);
203
- const identities = staleOnly ? staleScan.stale : staleScan.identities;
204
- const stamp = stableTimestampForFile();
205
- const artifactsDir = path.join(outputRoot, "aidenid", "identity-audit");
206
- const outputPath = path.join(artifactsDir, `identity-audit-${stamp}.json`);
207
- await writeArtifact(outputPath, {
208
- generatedAt: new Date().toISOString(),
209
- staleOnly,
210
- staleCount: staleScan.stale.length,
211
- totalCount: staleScan.identities.length,
212
- identities,
213
- });
214
-
215
- const payload = {
216
- command: "ai identity audit",
217
- staleOnly,
218
- registryPath: staleScan.registryPath,
219
- outputPath,
220
- staleCount: staleScan.stale.length,
221
- totalCount: staleScan.identities.length,
222
- identities,
223
- };
224
- if (emitJson) {
225
- console.log(JSON.stringify(payload, null, 2));
226
- return;
227
- }
228
-
229
- console.log(pc.bold("AIdenID identity audit"));
230
- console.log(pc.gray(`Registry: ${staleScan.registryPath}`));
231
- console.log(pc.gray(`Artifact: ${outputPath}`));
232
- console.log(`stale=${staleScan.stale.length} total=${staleScan.identities.length}`);
233
- for (const identityRecord of identities) {
234
- console.log(
235
- `- ${identityRecord.identityId} | ${identityRecord.status} | expires=${identityRecord.expiresAt || "n/a"}`
236
- );
237
- }
238
- });
239
-
240
- identity
241
- .command("kill-all")
242
- .description("Emergency bulk squash by tags with legal-hold protections")
243
- .option("--path <path>", "Workspace path for artifact/config resolution", ".")
244
- .option("--output-dir <path>", "Optional artifact output root override")
245
- .option("--tags <csv>", "Comma-separated tags used for identity selection")
246
- .option("--api-url <url>", "AIdenID API base URL", "https://api.aidenid.com")
247
- .option("--api-key <key>", "AIdenID API key (or use AIDENID_API_KEY env)")
248
- .option("--org-id <id>", "AIdenID org id (or use AIDENID_ORG_ID env)")
249
- .option("--project-id <id>", "AIdenID project id (or use AIDENID_PROJECT_ID env)")
250
- .option("--execute", "Execute live revoke calls before local squash updates")
251
- .option("--json", "Emit machine-readable output")
252
- .action(async (options, command) => {
253
- const emitJson = shouldEmitJson(options, command);
254
- const tags = parseCsvTokens(options.tags, []);
255
- if (tags.length === 0) {
256
- throw new Error("At least one tag is required via --tags.");
257
- }
258
- const targetPath = path.resolve(process.cwd(), String(options.path || "."));
259
- const outputRoot = await resolveOutputRoot({
260
- cwd: targetPath,
261
- outputDirOverride: options.outputDir,
262
- env: process.env,
263
- });
264
- const { registryPath, identities } = await listIdentities({ outputRoot });
265
- const tagged = filterIdentitiesByTags(identities, tags);
266
- const candidates = tagged.filter((identityRecord) => String(identityRecord.status || "").toUpperCase() !== "SQUASHED");
267
- const blocked = candidates.filter((identityRecord) => identityIsUnderLegalHold(identityRecord));
268
- const eligible = candidates.filter((identityRecord) => !identityIsUnderLegalHold(identityRecord));
269
-
270
- const apiUrl = normalizeAidenIdApiUrl(options.apiUrl);
271
- const killCampaignId = normalizeIdempotencyKey("");
272
- const stamp = stableTimestampForFile();
273
- const artifactsDir = path.join(outputRoot, "aidenid", "kill-all");
274
- const requestPath = path.join(artifactsDir, `request-${stamp}.json`);
275
- await writeArtifact(requestPath, {
276
- generatedAt: new Date().toISOString(),
277
- killCampaignId,
278
- apiUrl,
279
- tags,
280
- candidateIdentityIds: candidates.map((item) => item.identityId),
281
- blockedIdentityIds: blocked.map((item) => item.identityId),
282
- eligibleIdentityIds: eligible.map((item) => item.identityId),
283
- });
284
-
285
- if (!options.execute) {
286
- const payload = {
287
- command: "ai identity kill-all",
288
- execute: false,
289
- killCampaignId,
290
- tags,
291
- registryPath,
292
- requestPath,
293
- candidateCount: candidates.length,
294
- blockedCount: blocked.length,
295
- eligibleCount: eligible.length,
296
- blockedIdentityIds: blocked.map((item) => item.identityId),
297
- eligibleIdentityIds: eligible.map((item) => item.identityId),
298
- };
299
- if (emitJson) {
300
- console.log(JSON.stringify(payload, null, 2));
301
- return;
302
- }
303
-
304
- console.log(pc.bold("AIdenID kill-all request generated (dry-run)"));
305
- console.log(pc.gray(`Registry: ${registryPath}`));
306
- console.log(pc.gray(`Request: ${requestPath}`));
307
- console.log(`campaign=${killCampaignId} candidates=${candidates.length} blocked=${blocked.length}`);
308
- return;
309
- }
310
-
311
- const resolvedCredentials = await resolveAidenIdCredentials({
312
- apiKey: options.apiKey,
313
- orgId: options.orgId,
314
- projectId: options.projectId,
315
- env: process.env,
316
- requireAll: false,
317
- });
318
- const canCallApi = resolvedCredentials.missing.length === 0;
319
-
320
- const executeOne = async (identityRecord) => {
321
- const revokedAt = new Date().toISOString();
322
- let revokeResponse = null;
323
- if (canCallApi) {
324
- const revokeExecution = await revokeIdentity({
325
- apiUrl,
326
- apiKey: resolvedCredentials.apiKey,
327
- orgId: resolvedCredentials.orgId,
328
- projectId: resolvedCredentials.projectId || identityRecord.projectId,
329
- idempotencyKey: normalizeIdempotencyKey(""),
330
- identityId: identityRecord.identityId,
331
- });
332
- revokeResponse = revokeExecution.response || null;
333
- }
334
- const updated = await updateIdentityStatus({
335
- outputRoot,
336
- identityId: identityRecord.identityId,
337
- status: "SQUASHED",
338
- revokedAt,
339
- squashedAt: revokedAt,
340
- metadataPatch: {
341
- killCampaignId,
342
- killSwitchTags: tags,
343
- killAllExecutedAt: revokedAt,
344
- killAllApiCalled: canCallApi,
345
- },
346
- });
347
- return {
348
- identityId: identityRecord.identityId,
349
- status: updated.identity?.status || "SQUASHED",
350
- revokeResponse,
351
- };
352
- };
353
-
354
- const updates = [];
355
- for (const identityRecord of eligible) {
356
- const updated = await executeOne(identityRecord);
357
- updates.push(updated);
358
- }
359
- const responsePath = path.join(artifactsDir, `response-${stamp}.json`);
360
- await writeArtifact(responsePath, {
361
- generatedAt: new Date().toISOString(),
362
- killCampaignId,
363
- tags,
364
- candidateCount: candidates.length,
365
- blockedIdentityIds: blocked.map((item) => item.identityId),
366
- updated: updates,
367
- apiCalled: canCallApi,
368
- credentialsMissing: resolvedCredentials.missing,
369
- });
370
-
371
- const payload = {
372
- command: "ai identity kill-all",
373
- execute: true,
374
- killCampaignId,
375
- tags,
376
- registryPath,
377
- requestPath,
378
- responsePath,
379
- candidateCount: candidates.length,
380
- blockedCount: blocked.length,
381
- updatedCount: updates.length,
382
- blockedIdentityIds: blocked.map((item) => item.identityId),
383
- updated: updates,
384
- apiCalled: canCallApi,
385
- credentialsMissing: resolvedCredentials.missing,
386
- };
387
- if (emitJson) {
388
- console.log(JSON.stringify(payload, null, 2));
389
- return;
390
- }
391
-
392
- console.log(pc.bold("AIdenID kill-all executed"));
393
- console.log(pc.gray(`Registry: ${registryPath}`));
394
- console.log(pc.gray(`Response: ${responsePath}`));
395
- console.log(
396
- `campaign=${killCampaignId} updated=${updates.length} blocked=${blocked.length} api_called=${canCallApi}`
397
- );
398
- });
399
-
400
- identity
401
- .command("revoke")
402
- .description("Revoke a tracked identity (dry-run by default)")
403
- .argument("<identityId>", "Identity id")
404
- .option("--path <path>", "Workspace path for artifact/config resolution", ".")
405
- .option("--output-dir <path>", "Optional artifact output root override")
406
- .option("--api-url <url>", "AIdenID API base URL", "https://api.aidenid.com")
407
- .option("--api-key <key>", "AIdenID API key (or use AIDENID_API_KEY env)")
408
- .option("--org-id <id>", "AIdenID org id (or use AIDENID_ORG_ID env)")
409
- .option("--project-id <id>", "AIdenID project id (or use AIDENID_PROJECT_ID env)")
410
- .option("--idempotency-key <key>", "Explicit idempotency key override")
411
- .option("--execute", "Execute live revoke API call")
412
- .option("--json", "Emit machine-readable output")
413
- .action(async (identityId, options, command) => {
414
- const emitJson = shouldEmitJson(options, command);
415
- const targetPath = path.resolve(process.cwd(), String(options.path || "."));
416
- const outputRoot = await resolveOutputRoot({
417
- cwd: targetPath,
418
- outputDirOverride: options.outputDir,
419
- env: process.env,
420
- });
421
- const apiUrl = normalizeAidenIdApiUrl(options.apiUrl);
422
- const idempotencyKey = normalizeIdempotencyKey(options.idempotencyKey);
423
- const stamp = stableTimestampForFile();
424
- const artifactsDir = path.join(outputRoot, "aidenid", "revoke-identity");
425
- const requestPath = path.join(artifactsDir, `request-${stamp}.json`);
426
- await writeArtifact(requestPath, {
427
- generatedAt: new Date().toISOString(),
428
- apiUrl,
429
- idempotencyKey,
430
- identityId,
431
- });
432
-
433
- const { registryPath, identity: trackedIdentity } = await getIdentityById({
434
- outputRoot,
435
- identityId,
436
- });
437
- if (!trackedIdentity) {
438
- throw new Error(`Identity '${identityId}' is not present in local registry.`);
439
- }
440
- if (identityIsUnderLegalHold(trackedIdentity)) {
441
- throw new Error(`Identity '${identityId}' is under legal hold and cannot be revoked.`);
442
- }
443
-
444
- const resolvedCredentials = await resolveAidenIdCredentials({
445
- apiKey: options.apiKey,
446
- orgId: options.orgId,
447
- projectId: options.projectId || trackedIdentity.projectId,
448
- env: process.env,
449
- requireAll: false,
450
- });
451
-
452
- if (!options.execute) {
453
- const payload = {
454
- command: "ai identity revoke",
455
- execute: false,
456
- identityId,
457
- registryPath,
458
- requestPath,
459
- credentialsMissing: resolvedCredentials.missing,
460
- trackedIdentity,
461
- curlPreview: [
462
- `curl -X POST ${apiUrl}/v1/identities/${encodeURIComponent(identityId)}/revoke \\`,
463
- ` -H \"Authorization: Bearer $AIDENID_API_KEY\" \\`,
464
- ` -H \"X-Org-Id: $AIDENID_ORG_ID\" \\`,
465
- ` -H \"X-Project-Id: $AIDENID_PROJECT_ID\" \\`,
466
- ` -H \"Idempotency-Key: ${idempotencyKey}\"`,
467
- ].join("\n"),
468
- };
469
- if (emitJson) {
470
- console.log(JSON.stringify(payload, null, 2));
471
- return;
472
- }
473
- console.log(pc.bold("AIdenID revoke request artifact created (dry-run)"));
474
- console.log(pc.gray(`Registry: ${registryPath}`));
475
- console.log(pc.gray(`Request: ${requestPath}`));
476
- if (resolvedCredentials.missing.length > 0) {
477
- console.log(
478
- pc.yellow(`Missing credentials for live execute: ${resolvedCredentials.missing.join(", ")}`)
479
- );
480
- }
481
- console.log(payload.curlPreview);
482
- return;
483
- }
484
-
485
- const requiredCredentials = await resolveAidenIdCredentials({
486
- apiKey: options.apiKey,
487
- orgId: options.orgId || trackedIdentity.orgId,
488
- projectId: options.projectId || trackedIdentity.projectId,
489
- env: process.env,
490
- requireAll: true,
491
- });
492
-
493
- const execution = await revokeIdentity({
494
- apiUrl,
495
- apiKey: requiredCredentials.apiKey,
496
- orgId: requiredCredentials.orgId,
497
- projectId: requiredCredentials.projectId,
498
- idempotencyKey,
499
- identityId,
500
- });
501
- const responsePath = path.join(artifactsDir, `response-${stamp}.json`);
502
- await writeArtifact(responsePath, {
503
- receivedAt: new Date().toISOString(),
504
- apiUrl,
505
- idempotencyKey,
506
- response: execution.response,
507
- });
508
-
509
- const revokedAt = String(execution.response?.revokedAt || "").trim() || new Date().toISOString();
510
- const updated = await updateIdentityStatus({
511
- outputRoot,
512
- identityId,
513
- status: String(execution.response?.status || "REVOKED"),
514
- revokedAt,
515
- metadataPatch: {
516
- revokeRequestIdempotencyKey: idempotencyKey,
517
- },
518
- });
519
-
520
- const payload = {
521
- command: "ai identity revoke",
522
- execute: true,
523
- identityId,
524
- registryPath: updated.registryPath,
525
- requestPath,
526
- responsePath,
527
- identity: updated.identity,
528
- response: execution.response,
529
- };
530
- if (emitJson) {
531
- console.log(JSON.stringify(payload, null, 2));
532
- return;
533
- }
534
-
535
- console.log(pc.bold("AIdenID identity revoked"));
536
- console.log(pc.gray(`Registry: ${updated.registryPath}`));
537
- console.log(pc.gray(`Response: ${responsePath}`));
538
- console.log(`${updated.identity.identityId} | ${updated.identity.status}`);
539
- });
540
-
541
- identity
542
- .command("create-child")
543
- .description("Create a child identity under a parent (dry-run by default)")
544
- .argument("<parentIdentityId>", "Parent identity id")
545
- .option("--path <path>", "Workspace path for artifact/config resolution", ".")
546
- .option("--output-dir <path>", "Optional artifact output root override")
547
- .option("--api-url <url>", "AIdenID API base URL", "https://api.aidenid.com")
548
- .option("--api-key <key>", "AIdenID API key (or use AIDENID_API_KEY env)")
549
- .option("--org-id <id>", "AIdenID org id (or use AIDENID_ORG_ID env)")
550
- .option("--project-id <id>", "AIdenID project id (or use AIDENID_PROJECT_ID env)")
551
- .option("--alias-template <value>", "Optional alias template")
552
- .option("--ttl-hours <hours>", "Identity TTL in hours", "24")
553
- .option("--tags <csv>", "Comma-separated tags")
554
- .option("--domain-pool-id <id>", "Optional domain pool id")
555
- .option("--receive-mode <mode>", "Identity receive mode", "EDGE_ACCEPT")
556
- .option("--extraction-types <csv>", "Comma-separated extraction types", "otp,link")
557
- .option("--allow-webhooks", "Allow webhook delivery", true)
558
- .option("--no-allow-webhooks", "Disable webhook delivery")
559
- .option("--event-budget <count>", "Optional inbound event budget envelope")
560
- .option("--idempotency-key <key>", "Explicit idempotency key override")
561
- .option("--execute", "Execute live API call")
562
- .option("--json", "Emit machine-readable output")
563
- .action(async (parentIdentityId, options, command) => {
564
- const emitJson = shouldEmitJson(options, command);
565
- const targetPath = path.resolve(process.cwd(), String(options.path || "."));
566
- const outputRoot = await resolveOutputRoot({
567
- cwd: targetPath,
568
- outputDirOverride: options.outputDir,
569
- env: process.env,
570
- });
571
- const apiUrl = normalizeAidenIdApiUrl(options.apiUrl);
572
- const idempotencyKey = normalizeIdempotencyKey(options.idempotencyKey);
573
- const ttlHours = parsePositiveInteger(options.ttlHours, "ttlHours", 24);
574
- const eventBudget =
575
- options.eventBudget === undefined || options.eventBudget === null || String(options.eventBudget).trim() === ""
576
- ? null
577
- : parsePositiveInteger(options.eventBudget, "eventBudget", 1);
578
-
579
- const payload = buildChildIdentityPayload({
580
- aliasTemplate: options.aliasTemplate,
581
- ttlHours,
582
- tags: options.tags,
583
- domainPoolId: options.domainPoolId,
584
- receiveMode: options.receiveMode,
585
- allowWebhooks: Boolean(options.allowWebhooks),
586
- extractionTypes: options.extractionTypes,
587
- eventBudget,
588
- });
589
-
590
- const { identity: parentIdentity } = await getIdentityById({
591
- outputRoot,
592
- identityId: parentIdentityId,
593
- });
594
-
595
- const artifactsDir = path.join(outputRoot, "aidenid", "create-child");
596
- const stamp = stableTimestampForFile();
597
- const requestPath = path.join(
598
- artifactsDir,
599
- `request-${encodeURIComponent(parentIdentityId)}-${stamp}.json`
600
- );
601
- await writeArtifact(requestPath, {
602
- generatedAt: new Date().toISOString(),
603
- apiUrl,
604
- idempotencyKey,
605
- parentIdentityId,
606
- payload,
607
- });
608
-
609
- const resolvedCredentials = await resolveAidenIdCredentials({
610
- apiKey: options.apiKey,
611
- orgId: options.orgId || parentIdentity?.orgId,
612
- projectId: options.projectId || parentIdentity?.projectId,
613
- env: process.env,
614
- requireAll: false,
615
- });
616
-
617
- if (!options.execute) {
618
- const result = {
619
- command: "ai identity create-child",
620
- execute: false,
621
- apiUrl,
622
- idempotencyKey,
623
- parentIdentityId,
624
- requestPath,
625
- payload,
626
- credentialsMissing: resolvedCredentials.missing,
627
- parentIdentityTracked: Boolean(parentIdentity),
628
- curlPreview: [
629
- `curl -X POST ${apiUrl}/v1/identities/${encodeURIComponent(parentIdentityId)}/children \\`,
630
- ` -H \"Authorization: Bearer $AIDENID_API_KEY\" \\`,
631
- ` -H \"X-Org-Id: $AIDENID_ORG_ID\" \\`,
632
- ` -H \"X-Project-Id: $AIDENID_PROJECT_ID\" \\`,
633
- ` -H \"Idempotency-Key: ${idempotencyKey}\" \\`,
634
- ` -H \"Content-Type: application/json\" \\`,
635
- ` --data @${String(requestPath || "").replace(/\\/g, "/")}`,
636
- ].join("\n"),
637
- };
638
- if (emitJson) {
639
- console.log(JSON.stringify(result, null, 2));
640
- return;
641
- }
642
-
643
- console.log(pc.bold("AIdenID child identity request artifact created (dry-run)"));
644
- console.log(pc.gray(`Request: ${requestPath}`));
645
- if (!parentIdentity) {
646
- console.log(pc.yellow(`Parent identity '${parentIdentityId}' is not present in local registry.`));
647
- }
648
- if (resolvedCredentials.missing.length > 0) {
649
- console.log(
650
- pc.yellow(`Missing credentials for live execute: ${resolvedCredentials.missing.join(", ")}`)
651
- );
652
- }
653
- console.log(result.curlPreview);
654
- return;
655
- }
656
-
657
- const requiredCredentials = await resolveAidenIdCredentials({
658
- apiKey: options.apiKey,
659
- orgId: options.orgId || parentIdentity?.orgId,
660
- projectId: options.projectId || parentIdentity?.projectId,
661
- env: process.env,
662
- requireAll: true,
663
- });
664
-
665
- const execution = await createChildIdentity({
666
- apiUrl,
667
- apiKey: requiredCredentials.apiKey,
668
- orgId: requiredCredentials.orgId,
669
- projectId: requiredCredentials.projectId,
670
- parentIdentityId,
671
- idempotencyKey,
672
- payload,
673
- });
674
-
675
- const responsePath = path.join(
676
- artifactsDir,
677
- `response-${encodeURIComponent(parentIdentityId)}-${stamp}.json`
678
- );
679
- await writeArtifact(responsePath, {
680
- receivedAt: new Date().toISOString(),
681
- apiUrl,
682
- idempotencyKey,
683
- parentIdentityId,
684
- response: execution.response,
685
- });
686
-
687
- const registryUpdate = await recordProvisionedIdentity({
688
- outputRoot,
689
- response: execution.response || {},
690
- context: {
691
- source: "create-child",
692
- apiUrl,
693
- orgId: requiredCredentials.orgId,
694
- projectId: requiredCredentials.projectId,
695
- idempotencyKey,
696
- parentIdentityId,
697
- eventBudget,
698
- tags: payload.tags,
699
- },
700
- });
701
- const childIdentity = execution.response || {};
702
- const result = {
703
- command: "ai identity create-child",
704
- execute: true,
705
- parentIdentityId,
706
- apiUrl,
707
- idempotencyKey,
708
- requestPath,
709
- responsePath,
710
- childIdentity: {
711
- id: String(childIdentity.id || "").trim() || null,
712
- parentIdentityId: String(childIdentity.parentIdentityId || parentIdentityId).trim() || null,
713
- emailAddress: String(childIdentity.emailAddress || "").trim() || null,
714
- status: String(childIdentity.status || "").trim() || null,
715
- expiresAt: childIdentity.expiresAt || null,
716
- projectId: childIdentity.projectId || null,
717
- },
718
- response: execution.response,
719
- identityRegistryPath: registryUpdate.registryPath,
720
- };
721
- if (emitJson) {
722
- console.log(JSON.stringify(result, null, 2));
723
- return;
724
- }
725
-
726
- console.log(pc.bold("AIdenID child identity created"));
727
- console.log(pc.gray(`Request: ${requestPath}`));
728
- console.log(pc.gray(`Response: ${responsePath}`));
729
- console.log(
730
- `${result.childIdentity.id || "unknown-id"} | parent=${result.childIdentity.parentIdentityId || "n/a"}`
731
- );
732
- });
733
-
734
- identity
735
- .command("lineage")
736
- .description("Show parent/child lineage for an identity")
737
- .argument("<identityId>", "Identity id")
738
- .option("--path <path>", "Workspace path for artifact/config resolution", ".")
739
- .option("--output-dir <path>", "Optional artifact output root override")
740
- .option("--api-url <url>", "AIdenID API base URL", "https://api.aidenid.com")
741
- .option("--api-key <key>", "AIdenID API key (or use AIDENID_API_KEY env)")
742
- .option("--org-id <id>", "AIdenID org id (or use AIDENID_ORG_ID env)")
743
- .option("--project-id <id>", "AIdenID project id (or use AIDENID_PROJECT_ID env)")
744
- .option("--json", "Emit machine-readable output")
745
- .action(async (identityId, options, command) => {
746
- const emitJson = shouldEmitJson(options, command);
747
- const targetPath = path.resolve(process.cwd(), String(options.path || "."));
748
- const outputRoot = await resolveOutputRoot({
749
- cwd: targetPath,
750
- outputDirOverride: options.outputDir,
751
- env: process.env,
752
- });
753
- const apiUrl = normalizeAidenIdApiUrl(options.apiUrl);
754
- const { registryPath, identity: trackedIdentity } = await getIdentityById({
755
- outputRoot,
756
- identityId,
757
- });
758
- if (trackedIdentity && identityIsUnderLegalHold(trackedIdentity)) {
759
- throw new Error(`Identity '${identityId}' is under legal hold and cannot run revoke-children.`);
760
- }
761
- const credentials = await resolveAidenIdCredentials({
762
- apiKey: options.apiKey,
763
- orgId: options.orgId || trackedIdentity?.orgId,
764
- projectId: options.projectId || trackedIdentity?.projectId,
765
- env: process.env,
766
- requireAll: true,
767
- });
768
-
769
- const execution = await getIdentityLineage({
770
- apiUrl,
771
- apiKey: credentials.apiKey,
772
- orgId: credentials.orgId,
773
- projectId: credentials.projectId,
774
- identityId,
775
- });
776
- const stamp = stableTimestampForFile();
777
- const artifactsDir = path.join(outputRoot, "aidenid", "lineage");
778
- const outputPath = path.join(
779
- artifactsDir,
780
- `lineage-${encodeURIComponent(identityId)}-${stamp}.json`
781
- );
782
- await writeArtifact(outputPath, {
783
- generatedAt: new Date().toISOString(),
784
- identityId,
785
- response: execution.response,
786
- });
787
-
788
- const rows = renderLineageRows({
789
- nodes: execution.nodes,
790
- });
791
- const payload = {
792
- command: "ai identity lineage",
793
- identityId,
794
- registryPath,
795
- outputPath,
796
- rootIdentityId: execution.rootIdentityId,
797
- nodeCount: execution.nodes.length,
798
- edgeCount: execution.edges.length,
799
- nodes: execution.nodes,
800
- edges: execution.edges,
801
- tree: rows.join("\n"),
802
- };
803
- if (emitJson) {
804
- console.log(JSON.stringify(payload, null, 2));
805
- return;
806
- }
807
-
808
- console.log(pc.bold("AIdenID identity lineage"));
809
- console.log(pc.gray(`Registry: ${registryPath}`));
810
- console.log(pc.gray(`Artifact: ${outputPath}`));
811
- console.log(`root=${execution.rootIdentityId} nodes=${execution.nodes.length} edges=${execution.edges.length}`);
812
- for (const row of rows) {
813
- console.log(row);
814
- }
815
- });
816
-
817
- identity
818
- .command("revoke-children")
819
- .description("Revoke all descendants under a parent identity (dry-run by default)")
820
- .argument("<identityId>", "Parent identity id")
821
- .option("--path <path>", "Workspace path for artifact/config resolution", ".")
822
- .option("--output-dir <path>", "Optional artifact output root override")
823
- .option("--api-url <url>", "AIdenID API base URL", "https://api.aidenid.com")
824
- .option("--api-key <key>", "AIdenID API key (or use AIDENID_API_KEY env)")
825
- .option("--org-id <id>", "AIdenID org id (or use AIDENID_ORG_ID env)")
826
- .option("--project-id <id>", "AIdenID project id (or use AIDENID_PROJECT_ID env)")
827
- .option("--idempotency-key <key>", "Explicit idempotency key override")
828
- .option("--execute", "Execute live revoke API call")
829
- .option("--json", "Emit machine-readable output")
830
- .action(async (identityId, options, command) => {
831
- const emitJson = shouldEmitJson(options, command);
832
- const targetPath = path.resolve(process.cwd(), String(options.path || "."));
833
- const outputRoot = await resolveOutputRoot({
834
- cwd: targetPath,
835
- outputDirOverride: options.outputDir,
836
- env: process.env,
837
- });
838
- const apiUrl = normalizeAidenIdApiUrl(options.apiUrl);
839
- const idempotencyKey = normalizeIdempotencyKey(options.idempotencyKey);
840
- const { registryPath, identity: trackedIdentity } = await getIdentityById({
841
- outputRoot,
842
- identityId,
843
- });
844
- const stamp = stableTimestampForFile();
845
- const artifactsDir = path.join(outputRoot, "aidenid", "revoke-children");
846
- const requestPath = path.join(
847
- artifactsDir,
848
- `request-${encodeURIComponent(identityId)}-${stamp}.json`
849
- );
850
- await writeArtifact(requestPath, {
851
- generatedAt: new Date().toISOString(),
852
- apiUrl,
853
- idempotencyKey,
854
- identityId,
855
- });
856
-
857
- const resolvedCredentials = await resolveAidenIdCredentials({
858
- apiKey: options.apiKey,
859
- orgId: options.orgId || trackedIdentity?.orgId,
860
- projectId: options.projectId || trackedIdentity?.projectId,
861
- env: process.env,
862
- requireAll: false,
863
- });
864
-
865
- if (!options.execute) {
866
- const payload = {
867
- command: "ai identity revoke-children",
868
- execute: false,
869
- identityId,
870
- registryPath,
871
- requestPath,
872
- credentialsMissing: resolvedCredentials.missing,
873
- parentIdentityTracked: Boolean(trackedIdentity),
874
- curlPreview: [
875
- `curl -X POST ${apiUrl}/v1/identities/${encodeURIComponent(identityId)}/revoke-children \\`,
876
- ` -H \"Authorization: Bearer $AIDENID_API_KEY\" \\`,
877
- ` -H \"X-Org-Id: $AIDENID_ORG_ID\" \\`,
878
- ` -H \"X-Project-Id: $AIDENID_PROJECT_ID\" \\`,
879
- ` -H \"Idempotency-Key: ${idempotencyKey}\"`,
880
- ].join("\n"),
881
- };
882
- if (emitJson) {
883
- console.log(JSON.stringify(payload, null, 2));
884
- return;
885
- }
886
- console.log(pc.bold("AIdenID revoke-children request artifact created (dry-run)"));
887
- console.log(pc.gray(`Registry: ${registryPath}`));
888
- console.log(pc.gray(`Request: ${requestPath}`));
889
- if (!trackedIdentity) {
890
- console.log(pc.yellow(`Parent identity '${identityId}' is not present in local registry.`));
891
- }
892
- if (resolvedCredentials.missing.length > 0) {
893
- console.log(
894
- pc.yellow(`Missing credentials for live execute: ${resolvedCredentials.missing.join(", ")}`)
895
- );
896
- }
897
- console.log(payload.curlPreview);
898
- return;
899
- }
900
-
901
- const requiredCredentials = await resolveAidenIdCredentials({
902
- apiKey: options.apiKey,
903
- orgId: options.orgId || trackedIdentity?.orgId,
904
- projectId: options.projectId || trackedIdentity?.projectId,
905
- env: process.env,
906
- requireAll: true,
907
- });
908
-
909
- const execution = await revokeIdentityChildren({
910
- apiUrl,
911
- apiKey: requiredCredentials.apiKey,
912
- orgId: requiredCredentials.orgId,
913
- projectId: requiredCredentials.projectId,
914
- identityId,
915
- idempotencyKey,
916
- });
917
- const responsePath = path.join(
918
- artifactsDir,
919
- `response-${encodeURIComponent(identityId)}-${stamp}.json`
920
- );
921
- await writeArtifact(responsePath, {
922
- receivedAt: new Date().toISOString(),
923
- apiUrl,
924
- idempotencyKey,
925
- identityId,
926
- response: execution.response,
927
- });
928
-
929
- const updateResults = await Promise.all(
930
- execution.revokedIdentityIds.map(async (revokedIdentityId) => {
931
- try {
932
- const updated = await updateIdentityStatus({
933
- outputRoot,
934
- identityId: revokedIdentityId,
935
- status: "SQUASHED",
936
- revokedAt: new Date().toISOString(),
937
- squashedAt: new Date().toISOString(),
938
- metadataPatch: {
939
- revokeChildrenRequestIdempotencyKey: idempotencyKey,
940
- parentIdentityId: execution.parentIdentityId,
941
- },
942
- });
943
- return updated.identity?.identityId || null;
944
- } catch {
945
- return null;
946
- }
947
- })
948
- );
949
- const localUpdatedIdentityIds = updateResults.filter(Boolean);
950
-
951
- const payload = {
952
- command: "ai identity revoke-children",
953
- execute: true,
954
- identityId,
955
- parentIdentityId: execution.parentIdentityId,
956
- registryPath,
957
- requestPath,
958
- responsePath,
959
- revokedCount: execution.revokedCount,
960
- revokedIdentityIds: execution.revokedIdentityIds,
961
- localUpdatedIdentityIds,
962
- response: execution.response,
963
- };
964
- if (emitJson) {
965
- console.log(JSON.stringify(payload, null, 2));
966
- return;
967
- }
968
-
969
- console.log(pc.bold("AIdenID child identities revoked"));
970
- console.log(pc.gray(`Registry: ${registryPath}`));
971
- console.log(pc.gray(`Response: ${responsePath}`));
972
- console.log(
973
- `parent=${execution.parentIdentityId} revoked=${execution.revokedCount} localUpdated=${localUpdatedIdentityIds.length}`
974
- );
975
- });
976
-
977
- identity
978
- .command("events")
979
- .description("List inbound events for a tracked identity")
980
- .argument("<identityId>", "Identity id")
981
- .option("--path <path>", "Workspace path for artifact/config resolution", ".")
982
- .option("--output-dir <path>", "Optional artifact output root override")
983
- .option("--api-url <url>", "AIdenID API base URL", "https://api.aidenid.com")
984
- .option("--api-key <key>", "AIdenID API key (or use AIDENID_API_KEY env)")
985
- .option("--org-id <id>", "AIdenID org id (or use AIDENID_ORG_ID env)")
986
- .option("--project-id <id>", "AIdenID project id (or use AIDENID_PROJECT_ID env)")
987
- .option("--cursor <cursor>", "Pagination cursor")
988
- .option("--limit <count>", "Max events to fetch per page", "50")
989
- .option("--json", "Emit machine-readable output")
990
- .action(async (identityId, options, command) => {
991
- const emitJson = shouldEmitJson(options, command);
992
- const targetPath = path.resolve(process.cwd(), String(options.path || "."));
993
- const outputRoot = await resolveOutputRoot({
994
- cwd: targetPath,
995
- outputDirOverride: options.outputDir,
996
- env: process.env,
997
- });
998
- const apiUrl = normalizeAidenIdApiUrl(options.apiUrl);
999
- const limit = parsePositiveInteger(options.limit, "limit", 50);
1000
- const { registryPath, identity: trackedIdentity } = await getIdentityById({
1001
- outputRoot,
1002
- identityId,
1003
- });
1004
- if (!trackedIdentity) {
1005
- throw new Error(`Identity '${identityId}' is not present in local registry.`);
1006
- }
1007
-
1008
- const credentials = await resolveAidenIdCredentials({
1009
- apiKey: options.apiKey,
1010
- orgId: options.orgId || trackedIdentity.orgId,
1011
- projectId: options.projectId || trackedIdentity.projectId,
1012
- env: process.env,
1013
- requireAll: true,
1014
- });
1015
-
1016
- const execution = await listIdentityEvents({
1017
- apiUrl,
1018
- apiKey: credentials.apiKey,
1019
- orgId: credentials.orgId,
1020
- projectId: credentials.projectId,
1021
- identityId,
1022
- cursor: options.cursor,
1023
- limit,
1024
- });
1025
-
1026
- const stamp = stableTimestampForFile();
1027
- const artifactsDir = path.join(outputRoot, "aidenid", "events");
1028
- const outputPath = path.join(
1029
- artifactsDir,
1030
- `events-${encodeURIComponent(identityId)}-${stamp}.json`
1031
- );
1032
- await writeArtifact(outputPath, {
1033
- generatedAt: new Date().toISOString(),
1034
- identityId,
1035
- cursor: String(options.cursor || "").trim() || null,
1036
- limit,
1037
- response: execution.response,
1038
- });
1039
-
1040
- const payload = {
1041
- command: "ai identity events",
1042
- identityId,
1043
- registryPath,
1044
- outputPath,
1045
- cursor: String(options.cursor || "").trim() || null,
1046
- nextCursor: execution.nextCursor,
1047
- previousCursor: execution.previousCursor,
1048
- count: execution.events.length,
1049
- events: execution.events,
1050
- };
1051
-
1052
- if (emitJson) {
1053
- console.log(JSON.stringify(payload, null, 2));
1054
- return;
1055
- }
1056
-
1057
- console.log(pc.bold("AIdenID identity events"));
1058
- console.log(pc.gray(`Registry: ${registryPath}`));
1059
- console.log(pc.gray(`Artifact: ${outputPath}`));
1060
- console.log(pc.gray(`Events: ${execution.events.length}`));
1061
- if (execution.nextCursor) {
1062
- console.log(pc.gray(`nextCursor=${execution.nextCursor}`));
1063
- }
1064
- for (const item of execution.events) {
1065
- const eventId = String(item.eventId || item.id || item.messageId || "event");
1066
- const eventType = String(item.eventType || item.type || item.category || "unknown");
1067
- const eventAt = String(item.receivedAt || item.createdAt || item.timestamp || "unknown-time");
1068
- console.log(`- ${eventId} | ${eventType} | ${eventAt}`);
1069
- }
1070
- });
1071
-
1072
- identity
1073
- .command("latest")
1074
- .description("Show latest extraction and most recent event for an identity")
1075
- .argument("<identityId>", "Identity id")
1076
- .option("--path <path>", "Workspace path for artifact/config resolution", ".")
1077
- .option("--output-dir <path>", "Optional artifact output root override")
1078
- .option("--api-url <url>", "AIdenID API base URL", "https://api.aidenid.com")
1079
- .option("--api-key <key>", "AIdenID API key (or use AIDENID_API_KEY env)")
1080
- .option("--org-id <id>", "AIdenID org id (or use AIDENID_ORG_ID env)")
1081
- .option("--project-id <id>", "AIdenID project id (or use AIDENID_PROJECT_ID env)")
1082
- .option("--json", "Emit machine-readable output")
1083
- .action(async (identityId, options, command) => {
1084
- const emitJson = shouldEmitJson(options, command);
1085
- const targetPath = path.resolve(process.cwd(), String(options.path || "."));
1086
- const outputRoot = await resolveOutputRoot({
1087
- cwd: targetPath,
1088
- outputDirOverride: options.outputDir,
1089
- env: process.env,
1090
- });
1091
- const apiUrl = normalizeAidenIdApiUrl(options.apiUrl);
1092
- const { registryPath, identity: trackedIdentity } = await getIdentityById({
1093
- outputRoot,
1094
- identityId,
1095
- });
1096
- if (!trackedIdentity) {
1097
- throw new Error(`Identity '${identityId}' is not present in local registry.`);
1098
- }
1099
-
1100
- const credentials = await resolveAidenIdCredentials({
1101
- apiKey: options.apiKey,
1102
- orgId: options.orgId || trackedIdentity.orgId,
1103
- projectId: options.projectId || trackedIdentity.projectId,
1104
- env: process.env,
1105
- requireAll: true,
1106
- });
1107
-
1108
- const [latestExtraction, latestEventBatch] = await Promise.all([
1109
- getLatestIdentityExtraction({
1110
- apiUrl,
1111
- apiKey: credentials.apiKey,
1112
- orgId: credentials.orgId,
1113
- projectId: credentials.projectId,
1114
- identityId,
1115
- }),
1116
- listIdentityEvents({
1117
- apiUrl,
1118
- apiKey: credentials.apiKey,
1119
- orgId: credentials.orgId,
1120
- projectId: credentials.projectId,
1121
- identityId,
1122
- limit: 1,
1123
- }),
1124
- ]);
1125
- const latestEvent = latestEventBatch.events[0] || null;
1126
-
1127
- const stamp = stableTimestampForFile();
1128
- const artifactsDir = path.join(outputRoot, "aidenid", "latest");
1129
- const outputPath = path.join(
1130
- artifactsDir,
1131
- `latest-${encodeURIComponent(identityId)}-${stamp}.json`
1132
- );
1133
- await writeArtifact(outputPath, {
1134
- generatedAt: new Date().toISOString(),
1135
- identityId,
1136
- latestEvent,
1137
- extraction: latestExtraction.extraction,
1138
- extractionResponse: latestExtraction.response,
1139
- });
1140
-
1141
- const payload = {
1142
- command: "ai identity latest",
1143
- identityId,
1144
- registryPath,
1145
- outputPath,
1146
- latestEvent,
1147
- extraction: latestExtraction.extraction,
1148
- extractionAvailable: hasExtractionSignal(latestExtraction.extraction),
1149
- };
1150
- if (emitJson) {
1151
- console.log(JSON.stringify(payload, null, 2));
1152
- return;
1153
- }
1154
-
1155
- console.log(pc.bold("AIdenID latest identity signal"));
1156
- console.log(pc.gray(`Registry: ${registryPath}`));
1157
- console.log(pc.gray(`Artifact: ${outputPath}`));
1158
- console.log(
1159
- `source=${payload.extraction.source} confidence=${
1160
- Number.isFinite(Number(payload.extraction.confidence))
1161
- ? Number(payload.extraction.confidence).toFixed(3)
1162
- : "n/a"
1163
- }`
1164
- );
1165
- if (payload.extraction.otp) {
1166
- console.log(`otp=${payload.extraction.otp}`);
1167
- }
1168
- if (payload.extraction.primaryActionUrl) {
1169
- console.log(`primaryActionUrl=${payload.extraction.primaryActionUrl}`);
1170
- }
1171
- if (latestEvent) {
1172
- console.log(
1173
- `latestEvent=${String(latestEvent.eventId || latestEvent.id || "event")} type=${String(
1174
- latestEvent.eventType || latestEvent.type || "unknown"
1175
- )}`
1176
- );
1177
- }
1178
- });
1179
-
1180
- identity
1181
- .command("wait-for-otp")
1182
- .description("Poll latest extraction until OTP/link appears and confidence passes threshold")
1183
- .argument("<identityId>", "Identity id")
1184
- .option("--path <path>", "Workspace path for artifact/config resolution", ".")
1185
- .option("--output-dir <path>", "Optional artifact output root override")
1186
- .option("--api-url <url>", "AIdenID API base URL", "https://api.aidenid.com")
1187
- .option("--api-key <key>", "AIdenID API key (or use AIDENID_API_KEY env)")
1188
- .option("--org-id <id>", "AIdenID org id (or use AIDENID_ORG_ID env)")
1189
- .option("--project-id <id>", "AIdenID project id (or use AIDENID_PROJECT_ID env)")
1190
- .option("--interval-seconds <seconds>", "Polling interval in seconds", "2")
1191
- .option("--timeout <seconds>", "Polling timeout in seconds", "60")
1192
- .option("--min-confidence <value>", "Minimum confidence threshold (0-1)", "0.8")
1193
- .option("--json", "Emit machine-readable output")
1194
- .action(async (identityId, options, command) => {
1195
- const emitJson = shouldEmitJson(options, command);
1196
- const targetPath = path.resolve(process.cwd(), String(options.path || "."));
1197
- const outputRoot = await resolveOutputRoot({
1198
- cwd: targetPath,
1199
- outputDirOverride: options.outputDir,
1200
- env: process.env,
1201
- });
1202
- const apiUrl = normalizeAidenIdApiUrl(options.apiUrl);
1203
- const intervalSeconds = parsePositiveInteger(
1204
- options.intervalSeconds,
1205
- "intervalSeconds",
1206
- 2
1207
- );
1208
- const timeoutSeconds = parsePositiveInteger(options.timeout, "timeout", 60);
1209
- const minConfidence = parseConfidenceThreshold(options.minConfidence, 0.8);
1210
- const { registryPath, identity: trackedIdentity } = await getIdentityById({
1211
- outputRoot,
1212
- identityId,
1213
- });
1214
- if (!trackedIdentity) {
1215
- throw new Error(`Identity '${identityId}' is not present in local registry.`);
1216
- }
1217
-
1218
- const credentials = await resolveAidenIdCredentials({
1219
- apiKey: options.apiKey,
1220
- orgId: options.orgId || trackedIdentity.orgId,
1221
- projectId: options.projectId || trackedIdentity.projectId,
1222
- env: process.env,
1223
- requireAll: true,
1224
- });
1225
-
1226
- const stamp = stableTimestampForFile();
1227
- const artifactsDir = path.join(outputRoot, "aidenid", "wait-for-otp");
1228
- const outputPath = path.join(
1229
- artifactsDir,
1230
- `wait-for-otp-${encodeURIComponent(identityId)}-${stamp}.json`
1231
- );
1232
- const startedAt = Date.now();
1233
- const deadlineAt = startedAt + timeoutSeconds * 1000;
1234
- const attempts = [];
1235
- let lastExtraction = null;
1236
- let success = null;
1237
-
1238
- while (Date.now() <= deadlineAt) {
1239
- const execution = await getLatestIdentityExtraction({
1240
- apiUrl,
1241
- apiKey: credentials.apiKey,
1242
- orgId: credentials.orgId,
1243
- projectId: credentials.projectId,
1244
- identityId,
1245
- });
1246
- lastExtraction = execution.extraction;
1247
-
1248
- const hasSignal = hasExtractionSignal(execution.extraction);
1249
- const confidenceSatisfied = meetsConfidenceThreshold(execution.extraction, minConfidence);
1250
- const pollAt = new Date().toISOString();
1251
-
1252
- attempts.push({
1253
- attempt: attempts.length + 1,
1254
- polledAt: pollAt,
1255
- source: execution.extraction.source,
1256
- confidence: execution.extraction.confidence,
1257
- hasSignal,
1258
- confidenceSatisfied,
1259
- notFound: Boolean(execution.notFound),
1260
- });
1261
-
1262
- if (hasSignal && confidenceSatisfied) {
1263
- success = {
1264
- foundAt: pollAt,
1265
- extraction: execution.extraction,
1266
- source: execution.extraction.source,
1267
- confidence: execution.extraction.confidence,
1268
- };
1269
- break;
1270
- }
1271
-
1272
- if (Date.now() >= deadlineAt) {
1273
- break;
1274
- }
1275
- await delay(intervalSeconds * 1000);
1276
- }
1277
-
1278
- const finishedAtIso = new Date().toISOString();
1279
- const elapsedSeconds = Math.max(0, Math.round((Date.now() - startedAt) / 1000));
1280
- const artifactPayload = {
1281
- generatedAt: finishedAtIso,
1282
- identityId,
1283
- registryPath,
1284
- timeoutSeconds,
1285
- intervalSeconds,
1286
- minConfidence,
1287
- elapsedSeconds,
1288
- attempts,
1289
- result: success
1290
- ? {
1291
- status: "FOUND",
1292
- ...success,
1293
- }
1294
- : {
1295
- status: "TIMEOUT",
1296
- extraction: lastExtraction,
1297
- },
1298
- };
1299
- await writeArtifact(outputPath, artifactPayload);
1300
-
1301
- if (!success) {
1302
- throw new Error(
1303
- `Timed out waiting for OTP/link for identity '${identityId}' within ${timeoutSeconds}s (artifact: ${outputPath}).`
1304
- );
1305
- }
1306
-
1307
- const payload = {
1308
- command: "ai identity wait-for-otp",
1309
- identityId,
1310
- registryPath,
1311
- outputPath,
1312
- timeoutSeconds,
1313
- intervalSeconds,
1314
- minConfidence,
1315
- attempts: attempts.length,
1316
- extraction: success.extraction,
1317
- source: success.source,
1318
- confidence: success.confidence,
1319
- foundAt: success.foundAt,
1320
- };
1321
- if (emitJson) {
1322
- console.log(JSON.stringify(payload, null, 2));
1323
- return;
1324
- }
1325
-
1326
- console.log(pc.bold("AIdenID OTP/link extracted"));
1327
- console.log(pc.gray(`Registry: ${registryPath}`));
1328
- console.log(pc.gray(`Artifact: ${outputPath}`));
1329
- console.log(`source=${success.source} confidence=${String(success.confidence ?? "n/a")}`);
1330
- if (success.extraction.otp) {
1331
- console.log(`otp=${success.extraction.otp}`);
1332
- }
1333
- if (success.extraction.primaryActionUrl) {
1334
- console.log(`primaryActionUrl=${success.extraction.primaryActionUrl}`);
1335
- }
1336
- });
1337
- }
1338
-
1
+ import path from "node:path";
2
+ import process from "node:process";
3
+
4
+ import pc from "picocolors";
5
+
6
+ import {
7
+ buildChildIdentityPayload,
8
+ createChildIdentity,
9
+ getIdentityLineage,
10
+ getLatestIdentityExtraction,
11
+ listIdentityEvents,
12
+ normalizeAidenIdApiUrl,
13
+ revokeIdentity,
14
+ revokeIdentityChildren,
15
+ resolveAidenIdCredentials,
16
+ } from "../../ai/aidenid.js";
17
+ import {
18
+ filterIdentitiesByTags,
19
+ findStaleIdentities,
20
+ getIdentityById,
21
+ listIdentities,
22
+ recordProvisionedIdentity,
23
+ updateIdentityStatus,
24
+ } from "../../ai/identity-store.js";
25
+ import { resolveOutputRoot } from "../../config/service.js";
26
+ import {
27
+ delay,
28
+ hasExtractionSignal,
29
+ identityIsUnderLegalHold,
30
+ meetsConfidenceThreshold,
31
+ normalizeIdempotencyKey,
32
+ normalizeLegalHoldStatus,
33
+ parseConfidenceThreshold,
34
+ parseCsvTokens,
35
+ parsePositiveInteger,
36
+ renderLineageRows,
37
+ shouldEmitJson,
38
+ stableTimestampForFile,
39
+ writeArtifact,
40
+ } from "./shared.js";
41
+
42
+ export function registerAiIdentityLifecycleCommands({ identity, legalHold }) {
43
+ identity
44
+ .command("list")
45
+ .description("List locally tracked AIdenID identities")
46
+ .option("--path <path>", "Workspace path for artifact/config resolution", ".")
47
+ .option("--output-dir <path>", "Optional artifact output root override")
48
+ .option("--json", "Emit machine-readable output")
49
+ .action(async (options, command) => {
50
+ const emitJson = shouldEmitJson(options, command);
51
+ const targetPath = path.resolve(process.cwd(), String(options.path || "."));
52
+ const outputRoot = await resolveOutputRoot({
53
+ cwd: targetPath,
54
+ outputDirOverride: options.outputDir,
55
+ env: process.env,
56
+ });
57
+ const { registryPath, identities } = await listIdentities({ outputRoot });
58
+
59
+ const payload = {
60
+ command: "ai identity list",
61
+ registryPath,
62
+ count: identities.length,
63
+ identities,
64
+ };
65
+
66
+ if (emitJson) {
67
+ console.log(JSON.stringify(payload, null, 2));
68
+ return;
69
+ }
70
+
71
+ console.log(pc.bold("AIdenID identity registry"));
72
+ console.log(pc.gray(`Registry: ${registryPath}`));
73
+ if (identities.length === 0) {
74
+ console.log(pc.gray("No tracked identities."));
75
+ return;
76
+ }
77
+ for (const item of identities) {
78
+ console.log(
79
+ `- ${item.identityId} | ${item.emailAddress || "unknown-email"} | ${item.status} | ${
80
+ item.projectId || "no-project"
81
+ }`
82
+ );
83
+ }
84
+ });
85
+
86
+ identity
87
+ .command("show")
88
+ .description("Show a tracked identity record")
89
+ .argument("<identityId>", "Identity id")
90
+ .option("--path <path>", "Workspace path for artifact/config resolution", ".")
91
+ .option("--output-dir <path>", "Optional artifact output root override")
92
+ .option("--json", "Emit machine-readable output")
93
+ .action(async (identityId, options, command) => {
94
+ const emitJson = shouldEmitJson(options, command);
95
+ const targetPath = path.resolve(process.cwd(), String(options.path || "."));
96
+ const outputRoot = await resolveOutputRoot({
97
+ cwd: targetPath,
98
+ outputDirOverride: options.outputDir,
99
+ env: process.env,
100
+ });
101
+ const { registryPath, identity: identityRecord } = await getIdentityById({
102
+ outputRoot,
103
+ identityId,
104
+ });
105
+ if (!identityRecord) {
106
+ throw new Error(`Identity '${identityId}' is not present in local registry.`);
107
+ }
108
+
109
+ const payload = {
110
+ command: "ai identity show",
111
+ registryPath,
112
+ identity: identityRecord,
113
+ };
114
+ if (emitJson) {
115
+ console.log(JSON.stringify(payload, null, 2));
116
+ return;
117
+ }
118
+
119
+ console.log(pc.bold("AIdenID identity"));
120
+ console.log(pc.gray(`Registry: ${registryPath}`));
121
+ console.log(`${identityRecord.identityId} | ${identityRecord.emailAddress || "unknown-email"}`);
122
+ console.log(`status=${identityRecord.status} project=${identityRecord.projectId || "n/a"}`);
123
+ });
124
+
125
+ legalHold
126
+ .command("status")
127
+ .description("Show legal-hold status for a tracked identity")
128
+ .argument("<identityId>", "Identity id")
129
+ .option("--path <path>", "Workspace path for artifact/config resolution", ".")
130
+ .option("--output-dir <path>", "Optional artifact output root override")
131
+ .option("--json", "Emit machine-readable output")
132
+ .action(async (identityId, options, command) => {
133
+ const emitJson = shouldEmitJson(options, command);
134
+ const targetPath = path.resolve(process.cwd(), String(options.path || "."));
135
+ const outputRoot = await resolveOutputRoot({
136
+ cwd: targetPath,
137
+ outputDirOverride: options.outputDir,
138
+ env: process.env,
139
+ });
140
+ const { registryPath, identity: identityRecord } = await getIdentityById({
141
+ outputRoot,
142
+ identityId,
143
+ });
144
+ if (!identityRecord) {
145
+ throw new Error(`Identity '${identityId}' is not present in local registry.`);
146
+ }
147
+
148
+ const underHold = identityIsUnderLegalHold(identityRecord);
149
+ const status = underHold ? "HOLD" : normalizeLegalHoldStatus(identityRecord.legalHoldStatus);
150
+ const stamp = stableTimestampForFile();
151
+ const artifactsDir = path.join(outputRoot, "aidenid", "legal-hold-status");
152
+ const outputPath = path.join(
153
+ artifactsDir,
154
+ `legal-hold-${encodeURIComponent(identityId)}-${stamp}.json`
155
+ );
156
+ await writeArtifact(outputPath, {
157
+ generatedAt: new Date().toISOString(),
158
+ identityId,
159
+ status,
160
+ underHold,
161
+ identity: identityRecord,
162
+ });
163
+
164
+ const payload = {
165
+ command: "ai identity legal-hold status",
166
+ identityId,
167
+ registryPath,
168
+ outputPath,
169
+ status,
170
+ underHold,
171
+ };
172
+ if (emitJson) {
173
+ console.log(JSON.stringify(payload, null, 2));
174
+ return;
175
+ }
176
+
177
+ console.log(pc.bold("AIdenID legal-hold status"));
178
+ console.log(pc.gray(`Registry: ${registryPath}`));
179
+ console.log(pc.gray(`Artifact: ${outputPath}`));
180
+ console.log(`${identityId} | legal_hold=${status}`);
181
+ });
182
+
183
+ identity
184
+ .command("audit")
185
+ .description("Audit tracked identities for stale lifecycle records")
186
+ .option("--path <path>", "Workspace path for artifact/config resolution", ".")
187
+ .option("--output-dir <path>", "Optional artifact output root override")
188
+ .option("--stale", "Return only stale identities", true)
189
+ .option("--no-stale", "Return full identity inventory")
190
+ .option("--json", "Emit machine-readable output")
191
+ .action(async (options, command) => {
192
+ const emitJson = shouldEmitJson(options, command);
193
+ const targetPath = path.resolve(process.cwd(), String(options.path || "."));
194
+ const outputRoot = await resolveOutputRoot({
195
+ cwd: targetPath,
196
+ outputDirOverride: options.outputDir,
197
+ env: process.env,
198
+ });
199
+ const staleScan = await findStaleIdentities({
200
+ outputRoot,
201
+ });
202
+ const staleOnly = Boolean(options.stale);
203
+ const identities = staleOnly ? staleScan.stale : staleScan.identities;
204
+ const stamp = stableTimestampForFile();
205
+ const artifactsDir = path.join(outputRoot, "aidenid", "identity-audit");
206
+ const outputPath = path.join(artifactsDir, `identity-audit-${stamp}.json`);
207
+ await writeArtifact(outputPath, {
208
+ generatedAt: new Date().toISOString(),
209
+ staleOnly,
210
+ staleCount: staleScan.stale.length,
211
+ totalCount: staleScan.identities.length,
212
+ identities,
213
+ });
214
+
215
+ const payload = {
216
+ command: "ai identity audit",
217
+ staleOnly,
218
+ registryPath: staleScan.registryPath,
219
+ outputPath,
220
+ staleCount: staleScan.stale.length,
221
+ totalCount: staleScan.identities.length,
222
+ identities,
223
+ };
224
+ if (emitJson) {
225
+ console.log(JSON.stringify(payload, null, 2));
226
+ return;
227
+ }
228
+
229
+ console.log(pc.bold("AIdenID identity audit"));
230
+ console.log(pc.gray(`Registry: ${staleScan.registryPath}`));
231
+ console.log(pc.gray(`Artifact: ${outputPath}`));
232
+ console.log(`stale=${staleScan.stale.length} total=${staleScan.identities.length}`);
233
+ for (const identityRecord of identities) {
234
+ console.log(
235
+ `- ${identityRecord.identityId} | ${identityRecord.status} | expires=${identityRecord.expiresAt || "n/a"}`
236
+ );
237
+ }
238
+ });
239
+
240
+ identity
241
+ .command("kill-all")
242
+ .description("Emergency bulk squash by tags with legal-hold protections")
243
+ .option("--path <path>", "Workspace path for artifact/config resolution", ".")
244
+ .option("--output-dir <path>", "Optional artifact output root override")
245
+ .option("--tags <csv>", "Comma-separated tags used for identity selection")
246
+ .option("--api-url <url>", "AIdenID API base URL", "https://api.aidenid.com")
247
+ .option("--api-key <key>", "AIdenID API key (or use AIDENID_API_KEY env)")
248
+ .option("--org-id <id>", "AIdenID org id (or use AIDENID_ORG_ID env)")
249
+ .option("--project-id <id>", "AIdenID project id (or use AIDENID_PROJECT_ID env)")
250
+ .option("--execute", "Execute live revoke calls before local squash updates")
251
+ .option("--json", "Emit machine-readable output")
252
+ .action(async (options, command) => {
253
+ const emitJson = shouldEmitJson(options, command);
254
+ const tags = parseCsvTokens(options.tags, []);
255
+ if (tags.length === 0) {
256
+ throw new Error("At least one tag is required via --tags.");
257
+ }
258
+ const targetPath = path.resolve(process.cwd(), String(options.path || "."));
259
+ const outputRoot = await resolveOutputRoot({
260
+ cwd: targetPath,
261
+ outputDirOverride: options.outputDir,
262
+ env: process.env,
263
+ });
264
+ const { registryPath, identities } = await listIdentities({ outputRoot });
265
+ const tagged = filterIdentitiesByTags(identities, tags);
266
+ const candidates = tagged.filter((identityRecord) => String(identityRecord.status || "").toUpperCase() !== "SQUASHED");
267
+ const blocked = candidates.filter((identityRecord) => identityIsUnderLegalHold(identityRecord));
268
+ const eligible = candidates.filter((identityRecord) => !identityIsUnderLegalHold(identityRecord));
269
+
270
+ const apiUrl = normalizeAidenIdApiUrl(options.apiUrl);
271
+ const killCampaignId = normalizeIdempotencyKey("");
272
+ const stamp = stableTimestampForFile();
273
+ const artifactsDir = path.join(outputRoot, "aidenid", "kill-all");
274
+ const requestPath = path.join(artifactsDir, `request-${stamp}.json`);
275
+ await writeArtifact(requestPath, {
276
+ generatedAt: new Date().toISOString(),
277
+ killCampaignId,
278
+ apiUrl,
279
+ tags,
280
+ candidateIdentityIds: candidates.map((item) => item.identityId),
281
+ blockedIdentityIds: blocked.map((item) => item.identityId),
282
+ eligibleIdentityIds: eligible.map((item) => item.identityId),
283
+ });
284
+
285
+ if (!options.execute) {
286
+ const payload = {
287
+ command: "ai identity kill-all",
288
+ execute: false,
289
+ killCampaignId,
290
+ tags,
291
+ registryPath,
292
+ requestPath,
293
+ candidateCount: candidates.length,
294
+ blockedCount: blocked.length,
295
+ eligibleCount: eligible.length,
296
+ blockedIdentityIds: blocked.map((item) => item.identityId),
297
+ eligibleIdentityIds: eligible.map((item) => item.identityId),
298
+ };
299
+ if (emitJson) {
300
+ console.log(JSON.stringify(payload, null, 2));
301
+ return;
302
+ }
303
+
304
+ console.log(pc.bold("AIdenID kill-all request generated (dry-run)"));
305
+ console.log(pc.gray(`Registry: ${registryPath}`));
306
+ console.log(pc.gray(`Request: ${requestPath}`));
307
+ console.log(`campaign=${killCampaignId} candidates=${candidates.length} blocked=${blocked.length}`);
308
+ return;
309
+ }
310
+
311
+ const resolvedCredentials = await resolveAidenIdCredentials({
312
+ apiKey: options.apiKey,
313
+ orgId: options.orgId,
314
+ projectId: options.projectId,
315
+ env: process.env,
316
+ requireAll: false,
317
+ });
318
+ const canCallApi = resolvedCredentials.missing.length === 0;
319
+
320
+ const executeOne = async (identityRecord) => {
321
+ const revokedAt = new Date().toISOString();
322
+ let revokeResponse = null;
323
+ if (canCallApi) {
324
+ const revokeExecution = await revokeIdentity({
325
+ apiUrl,
326
+ apiKey: resolvedCredentials.apiKey,
327
+ orgId: resolvedCredentials.orgId,
328
+ projectId: resolvedCredentials.projectId || identityRecord.projectId,
329
+ idempotencyKey: normalizeIdempotencyKey(""),
330
+ identityId: identityRecord.identityId,
331
+ });
332
+ revokeResponse = revokeExecution.response || null;
333
+ }
334
+ const updated = await updateIdentityStatus({
335
+ outputRoot,
336
+ identityId: identityRecord.identityId,
337
+ status: "SQUASHED",
338
+ revokedAt,
339
+ squashedAt: revokedAt,
340
+ metadataPatch: {
341
+ killCampaignId,
342
+ killSwitchTags: tags,
343
+ killAllExecutedAt: revokedAt,
344
+ killAllApiCalled: canCallApi,
345
+ },
346
+ });
347
+ return {
348
+ identityId: identityRecord.identityId,
349
+ status: updated.identity?.status || "SQUASHED",
350
+ revokeResponse,
351
+ };
352
+ };
353
+
354
+ const updates = [];
355
+ for (const identityRecord of eligible) {
356
+ const updated = await executeOne(identityRecord);
357
+ updates.push(updated);
358
+ }
359
+ const responsePath = path.join(artifactsDir, `response-${stamp}.json`);
360
+ await writeArtifact(responsePath, {
361
+ generatedAt: new Date().toISOString(),
362
+ killCampaignId,
363
+ tags,
364
+ candidateCount: candidates.length,
365
+ blockedIdentityIds: blocked.map((item) => item.identityId),
366
+ updated: updates,
367
+ apiCalled: canCallApi,
368
+ credentialsMissing: resolvedCredentials.missing,
369
+ });
370
+
371
+ const payload = {
372
+ command: "ai identity kill-all",
373
+ execute: true,
374
+ killCampaignId,
375
+ tags,
376
+ registryPath,
377
+ requestPath,
378
+ responsePath,
379
+ candidateCount: candidates.length,
380
+ blockedCount: blocked.length,
381
+ updatedCount: updates.length,
382
+ blockedIdentityIds: blocked.map((item) => item.identityId),
383
+ updated: updates,
384
+ apiCalled: canCallApi,
385
+ credentialsMissing: resolvedCredentials.missing,
386
+ };
387
+ if (emitJson) {
388
+ console.log(JSON.stringify(payload, null, 2));
389
+ return;
390
+ }
391
+
392
+ console.log(pc.bold("AIdenID kill-all executed"));
393
+ console.log(pc.gray(`Registry: ${registryPath}`));
394
+ console.log(pc.gray(`Response: ${responsePath}`));
395
+ console.log(
396
+ `campaign=${killCampaignId} updated=${updates.length} blocked=${blocked.length} api_called=${canCallApi}`
397
+ );
398
+ });
399
+
400
+ identity
401
+ .command("revoke")
402
+ .description("Revoke a tracked identity (dry-run by default)")
403
+ .argument("<identityId>", "Identity id")
404
+ .option("--path <path>", "Workspace path for artifact/config resolution", ".")
405
+ .option("--output-dir <path>", "Optional artifact output root override")
406
+ .option("--api-url <url>", "AIdenID API base URL", "https://api.aidenid.com")
407
+ .option("--api-key <key>", "AIdenID API key (or use AIDENID_API_KEY env)")
408
+ .option("--org-id <id>", "AIdenID org id (or use AIDENID_ORG_ID env)")
409
+ .option("--project-id <id>", "AIdenID project id (or use AIDENID_PROJECT_ID env)")
410
+ .option("--idempotency-key <key>", "Explicit idempotency key override")
411
+ .option("--execute", "Execute live revoke API call")
412
+ .option("--json", "Emit machine-readable output")
413
+ .action(async (identityId, options, command) => {
414
+ const emitJson = shouldEmitJson(options, command);
415
+ const targetPath = path.resolve(process.cwd(), String(options.path || "."));
416
+ const outputRoot = await resolveOutputRoot({
417
+ cwd: targetPath,
418
+ outputDirOverride: options.outputDir,
419
+ env: process.env,
420
+ });
421
+ const apiUrl = normalizeAidenIdApiUrl(options.apiUrl);
422
+ const idempotencyKey = normalizeIdempotencyKey(options.idempotencyKey);
423
+ const stamp = stableTimestampForFile();
424
+ const artifactsDir = path.join(outputRoot, "aidenid", "revoke-identity");
425
+ const requestPath = path.join(artifactsDir, `request-${stamp}.json`);
426
+ await writeArtifact(requestPath, {
427
+ generatedAt: new Date().toISOString(),
428
+ apiUrl,
429
+ idempotencyKey,
430
+ identityId,
431
+ });
432
+
433
+ const { registryPath, identity: trackedIdentity } = await getIdentityById({
434
+ outputRoot,
435
+ identityId,
436
+ });
437
+ if (!trackedIdentity) {
438
+ throw new Error(`Identity '${identityId}' is not present in local registry.`);
439
+ }
440
+ if (identityIsUnderLegalHold(trackedIdentity)) {
441
+ throw new Error(`Identity '${identityId}' is under legal hold and cannot be revoked.`);
442
+ }
443
+
444
+ const resolvedCredentials = await resolveAidenIdCredentials({
445
+ apiKey: options.apiKey,
446
+ orgId: options.orgId,
447
+ projectId: options.projectId || trackedIdentity.projectId,
448
+ env: process.env,
449
+ requireAll: false,
450
+ });
451
+
452
+ if (!options.execute) {
453
+ const payload = {
454
+ command: "ai identity revoke",
455
+ execute: false,
456
+ identityId,
457
+ registryPath,
458
+ requestPath,
459
+ credentialsMissing: resolvedCredentials.missing,
460
+ trackedIdentity,
461
+ curlPreview: [
462
+ `curl -X POST ${apiUrl}/v1/identities/${encodeURIComponent(identityId)}/revoke \\`,
463
+ ` -H \"Authorization: Bearer $AIDENID_API_KEY\" \\`,
464
+ ` -H \"X-Org-Id: $AIDENID_ORG_ID\" \\`,
465
+ ` -H \"X-Project-Id: $AIDENID_PROJECT_ID\" \\`,
466
+ ` -H \"Idempotency-Key: ${idempotencyKey}\"`,
467
+ ].join("\n"),
468
+ };
469
+ if (emitJson) {
470
+ console.log(JSON.stringify(payload, null, 2));
471
+ return;
472
+ }
473
+ console.log(pc.bold("AIdenID revoke request artifact created (dry-run)"));
474
+ console.log(pc.gray(`Registry: ${registryPath}`));
475
+ console.log(pc.gray(`Request: ${requestPath}`));
476
+ if (resolvedCredentials.missing.length > 0) {
477
+ console.log(
478
+ pc.yellow(`Missing credentials for live execute: ${resolvedCredentials.missing.join(", ")}`)
479
+ );
480
+ }
481
+ console.log(payload.curlPreview);
482
+ return;
483
+ }
484
+
485
+ const requiredCredentials = await resolveAidenIdCredentials({
486
+ apiKey: options.apiKey,
487
+ orgId: options.orgId || trackedIdentity.orgId,
488
+ projectId: options.projectId || trackedIdentity.projectId,
489
+ env: process.env,
490
+ requireAll: true,
491
+ });
492
+
493
+ const execution = await revokeIdentity({
494
+ apiUrl,
495
+ apiKey: requiredCredentials.apiKey,
496
+ orgId: requiredCredentials.orgId,
497
+ projectId: requiredCredentials.projectId,
498
+ idempotencyKey,
499
+ identityId,
500
+ });
501
+ const responsePath = path.join(artifactsDir, `response-${stamp}.json`);
502
+ await writeArtifact(responsePath, {
503
+ receivedAt: new Date().toISOString(),
504
+ apiUrl,
505
+ idempotencyKey,
506
+ response: execution.response,
507
+ });
508
+
509
+ const revokedAt = String(execution.response?.revokedAt || "").trim() || new Date().toISOString();
510
+ const updated = await updateIdentityStatus({
511
+ outputRoot,
512
+ identityId,
513
+ status: String(execution.response?.status || "REVOKED"),
514
+ revokedAt,
515
+ metadataPatch: {
516
+ revokeRequestIdempotencyKey: idempotencyKey,
517
+ },
518
+ });
519
+
520
+ const payload = {
521
+ command: "ai identity revoke",
522
+ execute: true,
523
+ identityId,
524
+ registryPath: updated.registryPath,
525
+ requestPath,
526
+ responsePath,
527
+ identity: updated.identity,
528
+ response: execution.response,
529
+ };
530
+ if (emitJson) {
531
+ console.log(JSON.stringify(payload, null, 2));
532
+ return;
533
+ }
534
+
535
+ console.log(pc.bold("AIdenID identity revoked"));
536
+ console.log(pc.gray(`Registry: ${updated.registryPath}`));
537
+ console.log(pc.gray(`Response: ${responsePath}`));
538
+ console.log(`${updated.identity.identityId} | ${updated.identity.status}`);
539
+ });
540
+
541
+ identity
542
+ .command("create-child")
543
+ .description("Create a child identity under a parent (dry-run by default)")
544
+ .argument("<parentIdentityId>", "Parent identity id")
545
+ .option("--path <path>", "Workspace path for artifact/config resolution", ".")
546
+ .option("--output-dir <path>", "Optional artifact output root override")
547
+ .option("--api-url <url>", "AIdenID API base URL", "https://api.aidenid.com")
548
+ .option("--api-key <key>", "AIdenID API key (or use AIDENID_API_KEY env)")
549
+ .option("--org-id <id>", "AIdenID org id (or use AIDENID_ORG_ID env)")
550
+ .option("--project-id <id>", "AIdenID project id (or use AIDENID_PROJECT_ID env)")
551
+ .option("--alias-template <value>", "Optional alias template")
552
+ .option("--ttl-hours <hours>", "Identity TTL in hours", "24")
553
+ .option("--tags <csv>", "Comma-separated tags")
554
+ .option("--domain-pool-id <id>", "Optional domain pool id")
555
+ .option("--receive-mode <mode>", "Identity receive mode", "EDGE_ACCEPT")
556
+ .option("--extraction-types <csv>", "Comma-separated extraction types", "otp,link")
557
+ .option("--allow-webhooks", "Allow webhook delivery", true)
558
+ .option("--no-allow-webhooks", "Disable webhook delivery")
559
+ .option("--event-budget <count>", "Optional inbound event budget envelope")
560
+ .option("--idempotency-key <key>", "Explicit idempotency key override")
561
+ .option("--execute", "Execute live API call")
562
+ .option("--json", "Emit machine-readable output")
563
+ .action(async (parentIdentityId, options, command) => {
564
+ const emitJson = shouldEmitJson(options, command);
565
+ const targetPath = path.resolve(process.cwd(), String(options.path || "."));
566
+ const outputRoot = await resolveOutputRoot({
567
+ cwd: targetPath,
568
+ outputDirOverride: options.outputDir,
569
+ env: process.env,
570
+ });
571
+ const apiUrl = normalizeAidenIdApiUrl(options.apiUrl);
572
+ const idempotencyKey = normalizeIdempotencyKey(options.idempotencyKey);
573
+ const ttlHours = parsePositiveInteger(options.ttlHours, "ttlHours", 24);
574
+ const eventBudget =
575
+ options.eventBudget === undefined || options.eventBudget === null || String(options.eventBudget).trim() === ""
576
+ ? null
577
+ : parsePositiveInteger(options.eventBudget, "eventBudget", 1);
578
+
579
+ const payload = buildChildIdentityPayload({
580
+ aliasTemplate: options.aliasTemplate,
581
+ ttlHours,
582
+ tags: options.tags,
583
+ domainPoolId: options.domainPoolId,
584
+ receiveMode: options.receiveMode,
585
+ allowWebhooks: Boolean(options.allowWebhooks),
586
+ extractionTypes: options.extractionTypes,
587
+ eventBudget,
588
+ });
589
+
590
+ const { identity: parentIdentity } = await getIdentityById({
591
+ outputRoot,
592
+ identityId: parentIdentityId,
593
+ });
594
+
595
+ const artifactsDir = path.join(outputRoot, "aidenid", "create-child");
596
+ const stamp = stableTimestampForFile();
597
+ const requestPath = path.join(
598
+ artifactsDir,
599
+ `request-${encodeURIComponent(parentIdentityId)}-${stamp}.json`
600
+ );
601
+ await writeArtifact(requestPath, {
602
+ generatedAt: new Date().toISOString(),
603
+ apiUrl,
604
+ idempotencyKey,
605
+ parentIdentityId,
606
+ payload,
607
+ });
608
+
609
+ const resolvedCredentials = await resolveAidenIdCredentials({
610
+ apiKey: options.apiKey,
611
+ orgId: options.orgId || parentIdentity?.orgId,
612
+ projectId: options.projectId || parentIdentity?.projectId,
613
+ env: process.env,
614
+ requireAll: false,
615
+ });
616
+
617
+ if (!options.execute) {
618
+ const result = {
619
+ command: "ai identity create-child",
620
+ execute: false,
621
+ apiUrl,
622
+ idempotencyKey,
623
+ parentIdentityId,
624
+ requestPath,
625
+ payload,
626
+ credentialsMissing: resolvedCredentials.missing,
627
+ parentIdentityTracked: Boolean(parentIdentity),
628
+ curlPreview: [
629
+ `curl -X POST ${apiUrl}/v1/identities/${encodeURIComponent(parentIdentityId)}/children \\`,
630
+ ` -H \"Authorization: Bearer $AIDENID_API_KEY\" \\`,
631
+ ` -H \"X-Org-Id: $AIDENID_ORG_ID\" \\`,
632
+ ` -H \"X-Project-Id: $AIDENID_PROJECT_ID\" \\`,
633
+ ` -H \"Idempotency-Key: ${idempotencyKey}\" \\`,
634
+ ` -H \"Content-Type: application/json\" \\`,
635
+ ` --data @${String(requestPath || "").replace(/\\/g, "/")}`,
636
+ ].join("\n"),
637
+ };
638
+ if (emitJson) {
639
+ console.log(JSON.stringify(result, null, 2));
640
+ return;
641
+ }
642
+
643
+ console.log(pc.bold("AIdenID child identity request artifact created (dry-run)"));
644
+ console.log(pc.gray(`Request: ${requestPath}`));
645
+ if (!parentIdentity) {
646
+ console.log(pc.yellow(`Parent identity '${parentIdentityId}' is not present in local registry.`));
647
+ }
648
+ if (resolvedCredentials.missing.length > 0) {
649
+ console.log(
650
+ pc.yellow(`Missing credentials for live execute: ${resolvedCredentials.missing.join(", ")}`)
651
+ );
652
+ }
653
+ console.log(result.curlPreview);
654
+ return;
655
+ }
656
+
657
+ const requiredCredentials = await resolveAidenIdCredentials({
658
+ apiKey: options.apiKey,
659
+ orgId: options.orgId || parentIdentity?.orgId,
660
+ projectId: options.projectId || parentIdentity?.projectId,
661
+ env: process.env,
662
+ requireAll: true,
663
+ });
664
+
665
+ const execution = await createChildIdentity({
666
+ apiUrl,
667
+ apiKey: requiredCredentials.apiKey,
668
+ orgId: requiredCredentials.orgId,
669
+ projectId: requiredCredentials.projectId,
670
+ parentIdentityId,
671
+ idempotencyKey,
672
+ payload,
673
+ });
674
+
675
+ const responsePath = path.join(
676
+ artifactsDir,
677
+ `response-${encodeURIComponent(parentIdentityId)}-${stamp}.json`
678
+ );
679
+ await writeArtifact(responsePath, {
680
+ receivedAt: new Date().toISOString(),
681
+ apiUrl,
682
+ idempotencyKey,
683
+ parentIdentityId,
684
+ response: execution.response,
685
+ });
686
+
687
+ const registryUpdate = await recordProvisionedIdentity({
688
+ outputRoot,
689
+ response: execution.response || {},
690
+ context: {
691
+ source: "create-child",
692
+ apiUrl,
693
+ orgId: requiredCredentials.orgId,
694
+ projectId: requiredCredentials.projectId,
695
+ idempotencyKey,
696
+ parentIdentityId,
697
+ eventBudget,
698
+ tags: payload.tags,
699
+ },
700
+ });
701
+ const childIdentity = execution.response || {};
702
+ const result = {
703
+ command: "ai identity create-child",
704
+ execute: true,
705
+ parentIdentityId,
706
+ apiUrl,
707
+ idempotencyKey,
708
+ requestPath,
709
+ responsePath,
710
+ childIdentity: {
711
+ id: String(childIdentity.id || "").trim() || null,
712
+ parentIdentityId: String(childIdentity.parentIdentityId || parentIdentityId).trim() || null,
713
+ emailAddress: String(childIdentity.emailAddress || "").trim() || null,
714
+ status: String(childIdentity.status || "").trim() || null,
715
+ expiresAt: childIdentity.expiresAt || null,
716
+ projectId: childIdentity.projectId || null,
717
+ },
718
+ response: execution.response,
719
+ identityRegistryPath: registryUpdate.registryPath,
720
+ };
721
+ if (emitJson) {
722
+ console.log(JSON.stringify(result, null, 2));
723
+ return;
724
+ }
725
+
726
+ console.log(pc.bold("AIdenID child identity created"));
727
+ console.log(pc.gray(`Request: ${requestPath}`));
728
+ console.log(pc.gray(`Response: ${responsePath}`));
729
+ console.log(
730
+ `${result.childIdentity.id || "unknown-id"} | parent=${result.childIdentity.parentIdentityId || "n/a"}`
731
+ );
732
+ });
733
+
734
+ identity
735
+ .command("lineage")
736
+ .description("Show parent/child lineage for an identity")
737
+ .argument("<identityId>", "Identity id")
738
+ .option("--path <path>", "Workspace path for artifact/config resolution", ".")
739
+ .option("--output-dir <path>", "Optional artifact output root override")
740
+ .option("--api-url <url>", "AIdenID API base URL", "https://api.aidenid.com")
741
+ .option("--api-key <key>", "AIdenID API key (or use AIDENID_API_KEY env)")
742
+ .option("--org-id <id>", "AIdenID org id (or use AIDENID_ORG_ID env)")
743
+ .option("--project-id <id>", "AIdenID project id (or use AIDENID_PROJECT_ID env)")
744
+ .option("--json", "Emit machine-readable output")
745
+ .action(async (identityId, options, command) => {
746
+ const emitJson = shouldEmitJson(options, command);
747
+ const targetPath = path.resolve(process.cwd(), String(options.path || "."));
748
+ const outputRoot = await resolveOutputRoot({
749
+ cwd: targetPath,
750
+ outputDirOverride: options.outputDir,
751
+ env: process.env,
752
+ });
753
+ const apiUrl = normalizeAidenIdApiUrl(options.apiUrl);
754
+ const { registryPath, identity: trackedIdentity } = await getIdentityById({
755
+ outputRoot,
756
+ identityId,
757
+ });
758
+ if (trackedIdentity && identityIsUnderLegalHold(trackedIdentity)) {
759
+ throw new Error(`Identity '${identityId}' is under legal hold and cannot run revoke-children.`);
760
+ }
761
+ const credentials = await resolveAidenIdCredentials({
762
+ apiKey: options.apiKey,
763
+ orgId: options.orgId || trackedIdentity?.orgId,
764
+ projectId: options.projectId || trackedIdentity?.projectId,
765
+ env: process.env,
766
+ requireAll: true,
767
+ });
768
+
769
+ const execution = await getIdentityLineage({
770
+ apiUrl,
771
+ apiKey: credentials.apiKey,
772
+ orgId: credentials.orgId,
773
+ projectId: credentials.projectId,
774
+ identityId,
775
+ });
776
+ const stamp = stableTimestampForFile();
777
+ const artifactsDir = path.join(outputRoot, "aidenid", "lineage");
778
+ const outputPath = path.join(
779
+ artifactsDir,
780
+ `lineage-${encodeURIComponent(identityId)}-${stamp}.json`
781
+ );
782
+ await writeArtifact(outputPath, {
783
+ generatedAt: new Date().toISOString(),
784
+ identityId,
785
+ response: execution.response,
786
+ });
787
+
788
+ const rows = renderLineageRows({
789
+ nodes: execution.nodes,
790
+ });
791
+ const payload = {
792
+ command: "ai identity lineage",
793
+ identityId,
794
+ registryPath,
795
+ outputPath,
796
+ rootIdentityId: execution.rootIdentityId,
797
+ nodeCount: execution.nodes.length,
798
+ edgeCount: execution.edges.length,
799
+ nodes: execution.nodes,
800
+ edges: execution.edges,
801
+ tree: rows.join("\n"),
802
+ };
803
+ if (emitJson) {
804
+ console.log(JSON.stringify(payload, null, 2));
805
+ return;
806
+ }
807
+
808
+ console.log(pc.bold("AIdenID identity lineage"));
809
+ console.log(pc.gray(`Registry: ${registryPath}`));
810
+ console.log(pc.gray(`Artifact: ${outputPath}`));
811
+ console.log(`root=${execution.rootIdentityId} nodes=${execution.nodes.length} edges=${execution.edges.length}`);
812
+ for (const row of rows) {
813
+ console.log(row);
814
+ }
815
+ });
816
+
817
+ identity
818
+ .command("revoke-children")
819
+ .description("Revoke all descendants under a parent identity (dry-run by default)")
820
+ .argument("<identityId>", "Parent identity id")
821
+ .option("--path <path>", "Workspace path for artifact/config resolution", ".")
822
+ .option("--output-dir <path>", "Optional artifact output root override")
823
+ .option("--api-url <url>", "AIdenID API base URL", "https://api.aidenid.com")
824
+ .option("--api-key <key>", "AIdenID API key (or use AIDENID_API_KEY env)")
825
+ .option("--org-id <id>", "AIdenID org id (or use AIDENID_ORG_ID env)")
826
+ .option("--project-id <id>", "AIdenID project id (or use AIDENID_PROJECT_ID env)")
827
+ .option("--idempotency-key <key>", "Explicit idempotency key override")
828
+ .option("--execute", "Execute live revoke API call")
829
+ .option("--json", "Emit machine-readable output")
830
+ .action(async (identityId, options, command) => {
831
+ const emitJson = shouldEmitJson(options, command);
832
+ const targetPath = path.resolve(process.cwd(), String(options.path || "."));
833
+ const outputRoot = await resolveOutputRoot({
834
+ cwd: targetPath,
835
+ outputDirOverride: options.outputDir,
836
+ env: process.env,
837
+ });
838
+ const apiUrl = normalizeAidenIdApiUrl(options.apiUrl);
839
+ const idempotencyKey = normalizeIdempotencyKey(options.idempotencyKey);
840
+ const { registryPath, identity: trackedIdentity } = await getIdentityById({
841
+ outputRoot,
842
+ identityId,
843
+ });
844
+ const stamp = stableTimestampForFile();
845
+ const artifactsDir = path.join(outputRoot, "aidenid", "revoke-children");
846
+ const requestPath = path.join(
847
+ artifactsDir,
848
+ `request-${encodeURIComponent(identityId)}-${stamp}.json`
849
+ );
850
+ await writeArtifact(requestPath, {
851
+ generatedAt: new Date().toISOString(),
852
+ apiUrl,
853
+ idempotencyKey,
854
+ identityId,
855
+ });
856
+
857
+ const resolvedCredentials = await resolveAidenIdCredentials({
858
+ apiKey: options.apiKey,
859
+ orgId: options.orgId || trackedIdentity?.orgId,
860
+ projectId: options.projectId || trackedIdentity?.projectId,
861
+ env: process.env,
862
+ requireAll: false,
863
+ });
864
+
865
+ if (!options.execute) {
866
+ const payload = {
867
+ command: "ai identity revoke-children",
868
+ execute: false,
869
+ identityId,
870
+ registryPath,
871
+ requestPath,
872
+ credentialsMissing: resolvedCredentials.missing,
873
+ parentIdentityTracked: Boolean(trackedIdentity),
874
+ curlPreview: [
875
+ `curl -X POST ${apiUrl}/v1/identities/${encodeURIComponent(identityId)}/revoke-children \\`,
876
+ ` -H \"Authorization: Bearer $AIDENID_API_KEY\" \\`,
877
+ ` -H \"X-Org-Id: $AIDENID_ORG_ID\" \\`,
878
+ ` -H \"X-Project-Id: $AIDENID_PROJECT_ID\" \\`,
879
+ ` -H \"Idempotency-Key: ${idempotencyKey}\"`,
880
+ ].join("\n"),
881
+ };
882
+ if (emitJson) {
883
+ console.log(JSON.stringify(payload, null, 2));
884
+ return;
885
+ }
886
+ console.log(pc.bold("AIdenID revoke-children request artifact created (dry-run)"));
887
+ console.log(pc.gray(`Registry: ${registryPath}`));
888
+ console.log(pc.gray(`Request: ${requestPath}`));
889
+ if (!trackedIdentity) {
890
+ console.log(pc.yellow(`Parent identity '${identityId}' is not present in local registry.`));
891
+ }
892
+ if (resolvedCredentials.missing.length > 0) {
893
+ console.log(
894
+ pc.yellow(`Missing credentials for live execute: ${resolvedCredentials.missing.join(", ")}`)
895
+ );
896
+ }
897
+ console.log(payload.curlPreview);
898
+ return;
899
+ }
900
+
901
+ const requiredCredentials = await resolveAidenIdCredentials({
902
+ apiKey: options.apiKey,
903
+ orgId: options.orgId || trackedIdentity?.orgId,
904
+ projectId: options.projectId || trackedIdentity?.projectId,
905
+ env: process.env,
906
+ requireAll: true,
907
+ });
908
+
909
+ const execution = await revokeIdentityChildren({
910
+ apiUrl,
911
+ apiKey: requiredCredentials.apiKey,
912
+ orgId: requiredCredentials.orgId,
913
+ projectId: requiredCredentials.projectId,
914
+ identityId,
915
+ idempotencyKey,
916
+ });
917
+ const responsePath = path.join(
918
+ artifactsDir,
919
+ `response-${encodeURIComponent(identityId)}-${stamp}.json`
920
+ );
921
+ await writeArtifact(responsePath, {
922
+ receivedAt: new Date().toISOString(),
923
+ apiUrl,
924
+ idempotencyKey,
925
+ identityId,
926
+ response: execution.response,
927
+ });
928
+
929
+ const updateResults = await Promise.all(
930
+ execution.revokedIdentityIds.map(async (revokedIdentityId) => {
931
+ try {
932
+ const updated = await updateIdentityStatus({
933
+ outputRoot,
934
+ identityId: revokedIdentityId,
935
+ status: "SQUASHED",
936
+ revokedAt: new Date().toISOString(),
937
+ squashedAt: new Date().toISOString(),
938
+ metadataPatch: {
939
+ revokeChildrenRequestIdempotencyKey: idempotencyKey,
940
+ parentIdentityId: execution.parentIdentityId,
941
+ },
942
+ });
943
+ return updated.identity?.identityId || null;
944
+ } catch {
945
+ return null;
946
+ }
947
+ })
948
+ );
949
+ const localUpdatedIdentityIds = updateResults.filter(Boolean);
950
+
951
+ const payload = {
952
+ command: "ai identity revoke-children",
953
+ execute: true,
954
+ identityId,
955
+ parentIdentityId: execution.parentIdentityId,
956
+ registryPath,
957
+ requestPath,
958
+ responsePath,
959
+ revokedCount: execution.revokedCount,
960
+ revokedIdentityIds: execution.revokedIdentityIds,
961
+ localUpdatedIdentityIds,
962
+ response: execution.response,
963
+ };
964
+ if (emitJson) {
965
+ console.log(JSON.stringify(payload, null, 2));
966
+ return;
967
+ }
968
+
969
+ console.log(pc.bold("AIdenID child identities revoked"));
970
+ console.log(pc.gray(`Registry: ${registryPath}`));
971
+ console.log(pc.gray(`Response: ${responsePath}`));
972
+ console.log(
973
+ `parent=${execution.parentIdentityId} revoked=${execution.revokedCount} localUpdated=${localUpdatedIdentityIds.length}`
974
+ );
975
+ });
976
+
977
+ identity
978
+ .command("events")
979
+ .description("List inbound events for a tracked identity")
980
+ .argument("<identityId>", "Identity id")
981
+ .option("--path <path>", "Workspace path for artifact/config resolution", ".")
982
+ .option("--output-dir <path>", "Optional artifact output root override")
983
+ .option("--api-url <url>", "AIdenID API base URL", "https://api.aidenid.com")
984
+ .option("--api-key <key>", "AIdenID API key (or use AIDENID_API_KEY env)")
985
+ .option("--org-id <id>", "AIdenID org id (or use AIDENID_ORG_ID env)")
986
+ .option("--project-id <id>", "AIdenID project id (or use AIDENID_PROJECT_ID env)")
987
+ .option("--cursor <cursor>", "Pagination cursor")
988
+ .option("--limit <count>", "Max events to fetch per page", "50")
989
+ .option("--json", "Emit machine-readable output")
990
+ .action(async (identityId, options, command) => {
991
+ const emitJson = shouldEmitJson(options, command);
992
+ const targetPath = path.resolve(process.cwd(), String(options.path || "."));
993
+ const outputRoot = await resolveOutputRoot({
994
+ cwd: targetPath,
995
+ outputDirOverride: options.outputDir,
996
+ env: process.env,
997
+ });
998
+ const apiUrl = normalizeAidenIdApiUrl(options.apiUrl);
999
+ const limit = parsePositiveInteger(options.limit, "limit", 50);
1000
+ const { registryPath, identity: trackedIdentity } = await getIdentityById({
1001
+ outputRoot,
1002
+ identityId,
1003
+ });
1004
+ if (!trackedIdentity) {
1005
+ throw new Error(`Identity '${identityId}' is not present in local registry.`);
1006
+ }
1007
+
1008
+ const credentials = await resolveAidenIdCredentials({
1009
+ apiKey: options.apiKey,
1010
+ orgId: options.orgId || trackedIdentity.orgId,
1011
+ projectId: options.projectId || trackedIdentity.projectId,
1012
+ env: process.env,
1013
+ requireAll: true,
1014
+ });
1015
+
1016
+ const execution = await listIdentityEvents({
1017
+ apiUrl,
1018
+ apiKey: credentials.apiKey,
1019
+ orgId: credentials.orgId,
1020
+ projectId: credentials.projectId,
1021
+ identityId,
1022
+ cursor: options.cursor,
1023
+ limit,
1024
+ });
1025
+
1026
+ const stamp = stableTimestampForFile();
1027
+ const artifactsDir = path.join(outputRoot, "aidenid", "events");
1028
+ const outputPath = path.join(
1029
+ artifactsDir,
1030
+ `events-${encodeURIComponent(identityId)}-${stamp}.json`
1031
+ );
1032
+ await writeArtifact(outputPath, {
1033
+ generatedAt: new Date().toISOString(),
1034
+ identityId,
1035
+ cursor: String(options.cursor || "").trim() || null,
1036
+ limit,
1037
+ response: execution.response,
1038
+ });
1039
+
1040
+ const payload = {
1041
+ command: "ai identity events",
1042
+ identityId,
1043
+ registryPath,
1044
+ outputPath,
1045
+ cursor: String(options.cursor || "").trim() || null,
1046
+ nextCursor: execution.nextCursor,
1047
+ previousCursor: execution.previousCursor,
1048
+ count: execution.events.length,
1049
+ events: execution.events,
1050
+ };
1051
+
1052
+ if (emitJson) {
1053
+ console.log(JSON.stringify(payload, null, 2));
1054
+ return;
1055
+ }
1056
+
1057
+ console.log(pc.bold("AIdenID identity events"));
1058
+ console.log(pc.gray(`Registry: ${registryPath}`));
1059
+ console.log(pc.gray(`Artifact: ${outputPath}`));
1060
+ console.log(pc.gray(`Events: ${execution.events.length}`));
1061
+ if (execution.nextCursor) {
1062
+ console.log(pc.gray(`nextCursor=${execution.nextCursor}`));
1063
+ }
1064
+ for (const item of execution.events) {
1065
+ const eventId = String(item.eventId || item.id || item.messageId || "event");
1066
+ const eventType = String(item.eventType || item.type || item.category || "unknown");
1067
+ const eventAt = String(item.receivedAt || item.createdAt || item.timestamp || "unknown-time");
1068
+ console.log(`- ${eventId} | ${eventType} | ${eventAt}`);
1069
+ }
1070
+ });
1071
+
1072
+ identity
1073
+ .command("latest")
1074
+ .description("Show latest extraction and most recent event for an identity")
1075
+ .argument("<identityId>", "Identity id")
1076
+ .option("--path <path>", "Workspace path for artifact/config resolution", ".")
1077
+ .option("--output-dir <path>", "Optional artifact output root override")
1078
+ .option("--api-url <url>", "AIdenID API base URL", "https://api.aidenid.com")
1079
+ .option("--api-key <key>", "AIdenID API key (or use AIDENID_API_KEY env)")
1080
+ .option("--org-id <id>", "AIdenID org id (or use AIDENID_ORG_ID env)")
1081
+ .option("--project-id <id>", "AIdenID project id (or use AIDENID_PROJECT_ID env)")
1082
+ .option("--json", "Emit machine-readable output")
1083
+ .action(async (identityId, options, command) => {
1084
+ const emitJson = shouldEmitJson(options, command);
1085
+ const targetPath = path.resolve(process.cwd(), String(options.path || "."));
1086
+ const outputRoot = await resolveOutputRoot({
1087
+ cwd: targetPath,
1088
+ outputDirOverride: options.outputDir,
1089
+ env: process.env,
1090
+ });
1091
+ const apiUrl = normalizeAidenIdApiUrl(options.apiUrl);
1092
+ const { registryPath, identity: trackedIdentity } = await getIdentityById({
1093
+ outputRoot,
1094
+ identityId,
1095
+ });
1096
+ if (!trackedIdentity) {
1097
+ throw new Error(`Identity '${identityId}' is not present in local registry.`);
1098
+ }
1099
+
1100
+ const credentials = await resolveAidenIdCredentials({
1101
+ apiKey: options.apiKey,
1102
+ orgId: options.orgId || trackedIdentity.orgId,
1103
+ projectId: options.projectId || trackedIdentity.projectId,
1104
+ env: process.env,
1105
+ requireAll: true,
1106
+ });
1107
+
1108
+ const [latestExtraction, latestEventBatch] = await Promise.all([
1109
+ getLatestIdentityExtraction({
1110
+ apiUrl,
1111
+ apiKey: credentials.apiKey,
1112
+ orgId: credentials.orgId,
1113
+ projectId: credentials.projectId,
1114
+ identityId,
1115
+ }),
1116
+ listIdentityEvents({
1117
+ apiUrl,
1118
+ apiKey: credentials.apiKey,
1119
+ orgId: credentials.orgId,
1120
+ projectId: credentials.projectId,
1121
+ identityId,
1122
+ limit: 1,
1123
+ }),
1124
+ ]);
1125
+ const latestEvent = latestEventBatch.events[0] || null;
1126
+
1127
+ const stamp = stableTimestampForFile();
1128
+ const artifactsDir = path.join(outputRoot, "aidenid", "latest");
1129
+ const outputPath = path.join(
1130
+ artifactsDir,
1131
+ `latest-${encodeURIComponent(identityId)}-${stamp}.json`
1132
+ );
1133
+ await writeArtifact(outputPath, {
1134
+ generatedAt: new Date().toISOString(),
1135
+ identityId,
1136
+ latestEvent,
1137
+ extraction: latestExtraction.extraction,
1138
+ extractionResponse: latestExtraction.response,
1139
+ });
1140
+
1141
+ const payload = {
1142
+ command: "ai identity latest",
1143
+ identityId,
1144
+ registryPath,
1145
+ outputPath,
1146
+ latestEvent,
1147
+ extraction: latestExtraction.extraction,
1148
+ extractionAvailable: hasExtractionSignal(latestExtraction.extraction),
1149
+ };
1150
+ if (emitJson) {
1151
+ console.log(JSON.stringify(payload, null, 2));
1152
+ return;
1153
+ }
1154
+
1155
+ console.log(pc.bold("AIdenID latest identity signal"));
1156
+ console.log(pc.gray(`Registry: ${registryPath}`));
1157
+ console.log(pc.gray(`Artifact: ${outputPath}`));
1158
+ console.log(
1159
+ `source=${payload.extraction.source} confidence=${
1160
+ Number.isFinite(Number(payload.extraction.confidence))
1161
+ ? Number(payload.extraction.confidence).toFixed(3)
1162
+ : "n/a"
1163
+ }`
1164
+ );
1165
+ if (payload.extraction.otp) {
1166
+ console.log(`otp=${payload.extraction.otp}`);
1167
+ }
1168
+ if (payload.extraction.primaryActionUrl) {
1169
+ console.log(`primaryActionUrl=${payload.extraction.primaryActionUrl}`);
1170
+ }
1171
+ if (latestEvent) {
1172
+ console.log(
1173
+ `latestEvent=${String(latestEvent.eventId || latestEvent.id || "event")} type=${String(
1174
+ latestEvent.eventType || latestEvent.type || "unknown"
1175
+ )}`
1176
+ );
1177
+ }
1178
+ });
1179
+
1180
+ identity
1181
+ .command("wait-for-otp")
1182
+ .description("Poll latest extraction until OTP/link appears and confidence passes threshold")
1183
+ .argument("<identityId>", "Identity id")
1184
+ .option("--path <path>", "Workspace path for artifact/config resolution", ".")
1185
+ .option("--output-dir <path>", "Optional artifact output root override")
1186
+ .option("--api-url <url>", "AIdenID API base URL", "https://api.aidenid.com")
1187
+ .option("--api-key <key>", "AIdenID API key (or use AIDENID_API_KEY env)")
1188
+ .option("--org-id <id>", "AIdenID org id (or use AIDENID_ORG_ID env)")
1189
+ .option("--project-id <id>", "AIdenID project id (or use AIDENID_PROJECT_ID env)")
1190
+ .option("--interval-seconds <seconds>", "Polling interval in seconds", "2")
1191
+ .option("--timeout <seconds>", "Polling timeout in seconds", "60")
1192
+ .option("--min-confidence <value>", "Minimum confidence threshold (0-1)", "0.8")
1193
+ .option("--json", "Emit machine-readable output")
1194
+ .action(async (identityId, options, command) => {
1195
+ const emitJson = shouldEmitJson(options, command);
1196
+ const targetPath = path.resolve(process.cwd(), String(options.path || "."));
1197
+ const outputRoot = await resolveOutputRoot({
1198
+ cwd: targetPath,
1199
+ outputDirOverride: options.outputDir,
1200
+ env: process.env,
1201
+ });
1202
+ const apiUrl = normalizeAidenIdApiUrl(options.apiUrl);
1203
+ const intervalSeconds = parsePositiveInteger(
1204
+ options.intervalSeconds,
1205
+ "intervalSeconds",
1206
+ 2
1207
+ );
1208
+ const timeoutSeconds = parsePositiveInteger(options.timeout, "timeout", 60);
1209
+ const minConfidence = parseConfidenceThreshold(options.minConfidence, 0.8);
1210
+ const { registryPath, identity: trackedIdentity } = await getIdentityById({
1211
+ outputRoot,
1212
+ identityId,
1213
+ });
1214
+ if (!trackedIdentity) {
1215
+ throw new Error(`Identity '${identityId}' is not present in local registry.`);
1216
+ }
1217
+
1218
+ const credentials = await resolveAidenIdCredentials({
1219
+ apiKey: options.apiKey,
1220
+ orgId: options.orgId || trackedIdentity.orgId,
1221
+ projectId: options.projectId || trackedIdentity.projectId,
1222
+ env: process.env,
1223
+ requireAll: true,
1224
+ });
1225
+
1226
+ const stamp = stableTimestampForFile();
1227
+ const artifactsDir = path.join(outputRoot, "aidenid", "wait-for-otp");
1228
+ const outputPath = path.join(
1229
+ artifactsDir,
1230
+ `wait-for-otp-${encodeURIComponent(identityId)}-${stamp}.json`
1231
+ );
1232
+ const startedAt = Date.now();
1233
+ const deadlineAt = startedAt + timeoutSeconds * 1000;
1234
+ const attempts = [];
1235
+ let lastExtraction = null;
1236
+ let success = null;
1237
+
1238
+ while (Date.now() <= deadlineAt) {
1239
+ const execution = await getLatestIdentityExtraction({
1240
+ apiUrl,
1241
+ apiKey: credentials.apiKey,
1242
+ orgId: credentials.orgId,
1243
+ projectId: credentials.projectId,
1244
+ identityId,
1245
+ });
1246
+ lastExtraction = execution.extraction;
1247
+
1248
+ const hasSignal = hasExtractionSignal(execution.extraction);
1249
+ const confidenceSatisfied = meetsConfidenceThreshold(execution.extraction, minConfidence);
1250
+ const pollAt = new Date().toISOString();
1251
+
1252
+ attempts.push({
1253
+ attempt: attempts.length + 1,
1254
+ polledAt: pollAt,
1255
+ source: execution.extraction.source,
1256
+ confidence: execution.extraction.confidence,
1257
+ hasSignal,
1258
+ confidenceSatisfied,
1259
+ notFound: Boolean(execution.notFound),
1260
+ });
1261
+
1262
+ if (hasSignal && confidenceSatisfied) {
1263
+ success = {
1264
+ foundAt: pollAt,
1265
+ extraction: execution.extraction,
1266
+ source: execution.extraction.source,
1267
+ confidence: execution.extraction.confidence,
1268
+ };
1269
+ break;
1270
+ }
1271
+
1272
+ if (Date.now() >= deadlineAt) {
1273
+ break;
1274
+ }
1275
+ await delay(intervalSeconds * 1000);
1276
+ }
1277
+
1278
+ const finishedAtIso = new Date().toISOString();
1279
+ const elapsedSeconds = Math.max(0, Math.round((Date.now() - startedAt) / 1000));
1280
+ const artifactPayload = {
1281
+ generatedAt: finishedAtIso,
1282
+ identityId,
1283
+ registryPath,
1284
+ timeoutSeconds,
1285
+ intervalSeconds,
1286
+ minConfidence,
1287
+ elapsedSeconds,
1288
+ attempts,
1289
+ result: success
1290
+ ? {
1291
+ status: "FOUND",
1292
+ ...success,
1293
+ }
1294
+ : {
1295
+ status: "TIMEOUT",
1296
+ extraction: lastExtraction,
1297
+ },
1298
+ };
1299
+ await writeArtifact(outputPath, artifactPayload);
1300
+
1301
+ if (!success) {
1302
+ throw new Error(
1303
+ `Timed out waiting for OTP/link for identity '${identityId}' within ${timeoutSeconds}s (artifact: ${outputPath}).`
1304
+ );
1305
+ }
1306
+
1307
+ const payload = {
1308
+ command: "ai identity wait-for-otp",
1309
+ identityId,
1310
+ registryPath,
1311
+ outputPath,
1312
+ timeoutSeconds,
1313
+ intervalSeconds,
1314
+ minConfidence,
1315
+ attempts: attempts.length,
1316
+ extraction: success.extraction,
1317
+ source: success.source,
1318
+ confidence: success.confidence,
1319
+ foundAt: success.foundAt,
1320
+ };
1321
+ if (emitJson) {
1322
+ console.log(JSON.stringify(payload, null, 2));
1323
+ return;
1324
+ }
1325
+
1326
+ console.log(pc.bold("AIdenID OTP/link extracted"));
1327
+ console.log(pc.gray(`Registry: ${registryPath}`));
1328
+ console.log(pc.gray(`Artifact: ${outputPath}`));
1329
+ console.log(`source=${success.source} confidence=${String(success.confidence ?? "n/a")}`);
1330
+ if (success.extraction.otp) {
1331
+ console.log(`otp=${success.extraction.otp}`);
1332
+ }
1333
+ if (success.extraction.primaryActionUrl) {
1334
+ console.log(`primaryActionUrl=${success.extraction.primaryActionUrl}`);
1335
+ }
1336
+ });
1337
+ }
1338
+