@a5c-ai/krate 5.0.1-staging.660d2b90f → 5.0.1-staging.69cb593ea

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 (118) hide show
  1. package/Dockerfile +31 -29
  2. package/bin/krate-demo.mjs +0 -0
  3. package/bin/krate-server.mjs +0 -0
  4. package/dist/krate-controller-ui.json +808 -10
  5. package/dist/krate-lifecycle.json +1 -1
  6. package/dist/krate-runtime-snapshot.json +223 -53
  7. package/dist/krate-summary.json +40 -3
  8. package/docs/agents/gaps-agent-mux-to-krate-crds.md +298 -0
  9. package/docs/architecture-v2.md +431 -0
  10. package/docs/openapi.yaml +1275 -0
  11. package/docs/requirements-v2.md +238 -0
  12. package/docs/sdk-api-reference.md +782 -0
  13. package/docs/system-spec-v2.md +352 -0
  14. package/docs/todos.md +4 -0
  15. package/docs/web-console-spec.md +433 -0
  16. package/package.json +1 -1
  17. package/scripts/validate-ui.mjs +305 -207
  18. package/src/agent-adapter-controller.js +169 -0
  19. package/src/agent-approval-controller.js +47 -0
  20. package/src/agent-dispatch-controller.js +130 -7
  21. package/src/agent-gateway-config-controller.js +147 -0
  22. package/src/agent-memory-controller.js +357 -0
  23. package/src/agent-memory-import.js +327 -0
  24. package/src/agent-memory-query.js +292 -0
  25. package/src/agent-memory-repository-source-controller.js +255 -0
  26. package/src/agent-mux-client.js +1 -1
  27. package/src/agent-permission-review.js +102 -14
  28. package/src/agent-project-controller.js +117 -0
  29. package/src/agent-provider-config-controller.js +150 -0
  30. package/src/agent-secret-config-grant-controller.js +282 -0
  31. package/src/agent-session-transcript-controller.js +189 -0
  32. package/src/agent-stack-controller.js +52 -1
  33. package/src/agent-subagent-controller.js +160 -0
  34. package/src/agent-transport-binding-controller.js +121 -0
  35. package/src/agent-trigger-controller.js +273 -0
  36. package/src/agent-workspace-controller.js +702 -0
  37. package/src/agent-writeback-controller.js +302 -0
  38. package/src/api-controller.js +338 -3
  39. package/src/async-controller.js +207 -0
  40. package/src/audit-controller.js +191 -0
  41. package/src/auth.js +48 -6
  42. package/src/controller-client.js +112 -38
  43. package/src/controller-ui.js +96 -16
  44. package/src/data-plane.js +3 -2
  45. package/src/event-bus.js +61 -0
  46. package/src/external/conflict-controller.js +225 -0
  47. package/src/external/github/auth.js +96 -0
  48. package/src/external/github/cicd.js +180 -0
  49. package/src/external/github/git-forge.js +240 -0
  50. package/src/external/github/index.js +144 -0
  51. package/src/external/github/issue-tracking.js +163 -0
  52. package/src/external/provider-adapter.js +161 -0
  53. package/src/external/provider-resource-factory.js +161 -0
  54. package/src/external/sync-controller.js +235 -0
  55. package/src/external/webhook-controller.js +144 -0
  56. package/src/external/write-controller.js +283 -0
  57. package/src/gitea-backend.js +36 -0
  58. package/src/gitea-service.js +173 -0
  59. package/src/http-server.js +226 -0
  60. package/src/index.js +27 -0
  61. package/src/kubernetes-controller-async.js +531 -0
  62. package/src/kubernetes-controller.js +156 -84
  63. package/src/notification-controller.js +178 -0
  64. package/src/org-scoping.js +5 -0
  65. package/src/resource-model.js +26 -8
  66. package/src/runner-controller.js +272 -0
  67. package/src/snapshot-cache.js +157 -0
  68. package/tests/agent-adapter-controller.test.js +361 -0
  69. package/tests/agent-dispatch-controller.test.js +139 -0
  70. package/tests/agent-gateway-config-controller.test.js +386 -0
  71. package/tests/agent-memory-controller.test.js +308 -0
  72. package/tests/agent-memory-import-snapshot.test.js +477 -0
  73. package/tests/agent-memory-query.test.js +404 -0
  74. package/tests/agent-memory-repository-source.test.js +514 -0
  75. package/tests/agent-permission-review-v2.test.js +317 -0
  76. package/tests/agent-project-controller.test.js +302 -0
  77. package/tests/agent-provider-config-controller.test.js +376 -0
  78. package/tests/agent-resources.test.js +35 -19
  79. package/tests/agent-secret-config-grant.test.js +231 -0
  80. package/tests/agent-session-transcript-controller.test.js +499 -0
  81. package/tests/agent-subagent-controller.test.js +201 -0
  82. package/tests/agent-transport-binding-controller.test.js +294 -0
  83. package/tests/agent-trigger-routes.test.js +190 -0
  84. package/tests/agent-trigger-sources.test.js +245 -0
  85. package/tests/agent-workspace-controller.test.js +181 -0
  86. package/tests/agent-writeback.test.js +292 -0
  87. package/tests/approval-persistence.test.js +171 -0
  88. package/tests/async-controller.test.js +252 -0
  89. package/tests/audit-controller.test.js +227 -0
  90. package/tests/codespace-controller.test.js +318 -0
  91. package/tests/controller-client.test.js +133 -0
  92. package/tests/deployment.test.js +43 -29
  93. package/tests/e2e/lifecycle.test.js +5 -2
  94. package/tests/event-bus-integration.test.js +190 -0
  95. package/tests/external-github-forge.test.js +560 -0
  96. package/tests/external-github-issues-cicd.test.js +520 -0
  97. package/tests/external-integration.test.js +470 -0
  98. package/tests/external-persistence.test.js +340 -0
  99. package/tests/external-provider-adapter.test.js +365 -0
  100. package/tests/external-resource-model.test.js +215 -0
  101. package/tests/external-webhook-sync.test.js +287 -0
  102. package/tests/external-write-conflict.test.js +353 -0
  103. package/tests/gitea-service.test.js +253 -0
  104. package/tests/health-check-real.test.js +165 -0
  105. package/tests/integration/full-flow.test.js +266 -0
  106. package/tests/krate.test.js +58 -6
  107. package/tests/memory-search-wiring.test.js +270 -0
  108. package/tests/notification-controller.test.js +196 -0
  109. package/tests/notification-integration.test.js +179 -0
  110. package/tests/org-scoping.test.js +687 -0
  111. package/tests/runner-controller.test.js +327 -0
  112. package/tests/runner-integration.test.js +231 -0
  113. package/tests/session-cookie-hmac.test.js +151 -0
  114. package/tests/snapshot-performance.test.js +315 -0
  115. package/tests/sse-events.test.js +107 -0
  116. package/tests/webhook-trigger.test.js +198 -0
  117. package/tests/workspace-volumes.test.js +312 -0
  118. package/tests/writeback-persistence.test.js +207 -0
@@ -65,7 +65,49 @@ export const KRATE_RESOURCES = [
65
65
  { kind: 'KubeVelaWorkflow', plural: 'workflows', group: KUBEVELA_API_GROUP, namespaced: true, storage: 'kubevela' },
66
66
  { kind: 'KubeVelaResourceTracker', plural: 'resourcetrackers', group: KUBEVELA_API_GROUP, namespaced: false, storage: 'kubevela' },
67
67
  { kind: 'View', plural: 'views', namespaced: true, storage: 'etcd' },
68
- { kind: 'Selector', plural: 'selectors', namespaced: true, storage: 'etcd' }
68
+ { kind: 'Selector', plural: 'selectors', namespaced: true, storage: 'etcd' },
69
+ // Agent orchestration CRDs (etcd-stored, krate.a5c.ai group)
70
+ { kind: 'AgentStack', plural: 'agentstacks', namespaced: true, storage: 'etcd' },
71
+ { kind: 'AgentSubagent', plural: 'agentsubagents', namespaced: true, storage: 'etcd' },
72
+ { kind: 'AgentToolProfile', plural: 'agenttoolprofiles', namespaced: true, storage: 'etcd' },
73
+ { kind: 'AgentMcpServer', plural: 'agentmcpservers', namespaced: true, storage: 'etcd' },
74
+ { kind: 'AgentSkill', plural: 'agentskills', namespaced: true, storage: 'etcd' },
75
+ { kind: 'AgentTriggerRule', plural: 'agenttriggerrules', namespaced: true, storage: 'etcd' },
76
+ { kind: 'AgentContextLabel', plural: 'agentcontextlabels', namespaced: true, storage: 'etcd' },
77
+ { kind: 'KrateWorkspacePolicy', plural: 'krateworkspacepolicies', namespaced: true, storage: 'etcd' },
78
+ { kind: 'AgentServiceAccount', plural: 'agentserviceaccounts', namespaced: true, storage: 'etcd' },
79
+ { kind: 'AgentRoleBinding', plural: 'agentrolebindings', namespaced: true, storage: 'etcd' },
80
+ { kind: 'AgentSecretGrant', plural: 'agentsecretgrants', namespaced: true, storage: 'etcd' },
81
+ { kind: 'AgentConfigGrant', plural: 'agentconfiggrants', namespaced: true, storage: 'etcd' },
82
+ { kind: 'AgentAdapter', plural: 'agentadapters', namespaced: true, storage: 'etcd' },
83
+ { kind: 'AgentTransportBinding', plural: 'agenttransportbindings', namespaced: true, storage: 'etcd' },
84
+ { kind: 'AgentProviderConfig', plural: 'agentproviderconfigs', namespaced: true, storage: 'etcd' },
85
+ { kind: 'KrateProject', plural: 'krateprojects', namespaced: true, storage: 'etcd' },
86
+ { kind: 'AgentGatewayConfig', plural: 'agentgatewayconfigs', namespaced: true, storage: 'etcd' },
87
+ { kind: 'AgentMemoryRepository', plural: 'agentmemoryrepositories', namespaced: true, storage: 'etcd' },
88
+ { kind: 'AgentMemorySource', plural: 'agentmemorysources', namespaced: true, storage: 'etcd' },
89
+ { kind: 'AgentMemoryOntology', plural: 'agentmemoryontologies', namespaced: true, storage: 'etcd' },
90
+ { kind: 'AgentMemoryAssociation', plural: 'agentmemoryassociations', namespaced: true, storage: 'etcd' },
91
+ // Aggregated agent resources (postgres-stored, accessed via snapshot but need discovery)
92
+ { kind: 'AgentDispatchRun', plural: 'agentdispatchruns', namespaced: true, storage: 'postgres' },
93
+ { kind: 'AgentDispatchAttempt', plural: 'agentdispatchattempts', namespaced: true, storage: 'postgres' },
94
+ { kind: 'AgentSession', plural: 'agentsessions', namespaced: true, storage: 'postgres' },
95
+ { kind: 'AgentContextBundle', plural: 'agentcontextbundles', namespaced: true, storage: 'postgres' },
96
+ { kind: 'KrateArtifact', plural: 'krateartifacts', namespaced: true, storage: 'postgres' },
97
+ { kind: 'AgentApproval', plural: 'agentapprovals', namespaced: true, storage: 'postgres' },
98
+ { kind: 'KrateWorkspace', plural: 'krateworkspaces', namespaced: true, storage: 'postgres' },
99
+ { kind: 'AgentTriggerExecution', plural: 'agenttriggerexecutions', namespaced: true, storage: 'postgres' },
100
+ { kind: 'KrateWorkspaceRuntime', plural: 'krateworkspaceruntimes', namespaced: true, storage: 'postgres' },
101
+ { kind: 'AgentSessionTranscript', plural: 'agentsessiontranscripts', namespaced: true, storage: 'postgres' },
102
+ // External backend resources (etcd-stored)
103
+ { kind: 'ExternalBackendProvider', plural: 'externalbackendproviders', namespaced: true, storage: 'etcd' },
104
+ { kind: 'ExternalBackendBinding', plural: 'externalbackendbindings', namespaced: true, storage: 'etcd' },
105
+ { kind: 'ExternalBackendSyncPolicy', plural: 'externalbackendsyncpolicies', namespaced: true, storage: 'etcd' },
106
+ // Core Kubernetes resources (group: '' — no API group prefix for kubectl).
107
+ // These are excluded from snapshot discovery (storage: 'core') but are
108
+ // available for list/get/delete via findResourceDefinition.
109
+ { kind: 'Secret', plural: 'secrets', group: '', namespaced: true, storage: 'core' },
110
+ { kind: 'ConfigMap', plural: 'configmaps', group: '', namespaced: true, storage: 'core' }
69
111
  ];
70
112
 
71
113
  export const KYVERNO_RESOURCES = [
@@ -332,8 +374,8 @@ export async function getControllerSnapshot(options = {}) {
332
374
  },
333
375
  apiService: null,
334
376
  crds: [],
335
- resources: Object.fromEntries(KRATE_RESOURCES.map((definition) => [definition.kind, []])),
336
- kyverno: emptyKyvernoDiscovery(namespace, env),
377
+ resources: Object.fromEntries(KRATE_RESOURCES.filter((d) => d.storage !== 'core').map((definition) => [definition.kind, []])),
378
+ kyverno: emptyKyvernoDiscovery(namespace, env),
337
379
  events: [],
338
380
  permissions: [],
339
381
  storage: storageBoundaries(),
@@ -359,8 +401,8 @@ export async function getControllerSnapshot(options = {}) {
359
401
  },
360
402
  apiService: null,
361
403
  crds: [],
362
- resources: Object.fromEntries(KRATE_RESOURCES.map((definition) => [definition.kind, []])),
363
- kyverno: emptyKyvernoDiscovery(namespace, env),
404
+ resources: Object.fromEntries(KRATE_RESOURCES.filter((d) => d.storage !== 'core').map((definition) => [definition.kind, []])),
405
+ kyverno: emptyKyvernoDiscovery(namespace, env),
364
406
  events: [],
365
407
  permissions: [],
366
408
  storage: storageBoundaries(),
@@ -385,22 +427,25 @@ export async function getControllerSnapshot(options = {}) {
385
427
  },
386
428
  apiService: null,
387
429
  crds: [],
388
- resources: Object.fromEntries(KRATE_RESOURCES.map((definition) => [definition.kind, []])),
389
- kyverno: emptyKyvernoDiscovery(namespace, env),
430
+ resources: Object.fromEntries(KRATE_RESOURCES.filter((d) => d.storage !== 'core').map((definition) => [definition.kind, []])),
431
+ kyverno: emptyKyvernoDiscovery(namespace, env),
390
432
  events: [],
391
433
  permissions: [],
392
434
  storage: storageBoundaries(),
393
435
  commands: controllerCommands(namespace)
394
436
  };
395
437
  }
396
- const kyverno = discoverKyverno({ kubectl, namespace, timeoutMs, env, discoveredPluralSet });
397
- const resources = Object.fromEntries(KRATE_RESOURCES.map((definition) => [definition.kind, []]));
438
+ const kyverno = discoverKyverno({ kubectl, namespace, timeoutMs, env, discoveredPluralSet });
439
+ // Exclude core K8s resources (Secret, ConfigMap) from snapshot — they are
440
+ // accessed on-demand via listResource, not loaded into the full snapshot.
441
+ const snapshotResources = KRATE_RESOURCES.filter((d) => d.storage !== 'core');
442
+ const resources = Object.fromEntries(snapshotResources.map((definition) => [definition.kind, []]));
398
443
  const listResults = [];
399
- const platformScopedDefinitions = KRATE_RESOURCES.filter((definition) => definition.platformScoped);
400
- const orgScopedDefinitions = KRATE_RESOURCES.filter((definition) => !definition.platformScoped);
444
+ const platformScopedDefinitions = snapshotResources.filter((definition) => definition.platformScoped);
445
+ const orgScopedDefinitions = snapshotResources.filter((definition) => !definition.platformScoped);
401
446
 
402
447
  for (const definition of platformScopedDefinitions) {
403
- if (!discoveredPluralSet.has(`${definition.group || KRATE_API_GROUP}/${definition.plural}`)) continue;
448
+ if (!shouldListSnapshotDefinition(definition, discoveredPluralSet)) continue;
404
449
  const resourceNamespace = definition.namespace || namespace;
405
450
  const result = runKubectl(['get', apiResourceName(definition), ...namespaceArgs(definition, resourceNamespace), '-o', 'json', '--ignore-not-found'], { kubectl, timeoutMs, env, allowFailure: true });
406
451
  listResults.push({ definition, result });
@@ -409,7 +454,7 @@ export async function getControllerSnapshot(options = {}) {
409
454
 
410
455
  const orgNamespaces = organizationNamespaces(resources.Organization, resources.OrgNamespaceBinding, namespace);
411
456
  for (const definition of orgScopedDefinitions) {
412
- if (!discoveredPluralSet.has(`${definition.group || KRATE_API_GROUP}/${definition.plural}`)) continue;
457
+ if (!shouldListSnapshotDefinition(definition, discoveredPluralSet)) continue;
413
458
  const namespaces = definition.namespaced === false ? [null] : [definition.namespace || null].filter(Boolean).concat(definition.namespace ? [] : orgNamespaces);
414
459
  resources[definition.kind] = namespaces.flatMap((resourceNamespace) => {
415
460
  const effectiveNamespace = resourceNamespace || namespace;
@@ -420,7 +465,7 @@ export async function getControllerSnapshot(options = {}) {
420
465
  }
421
466
 
422
467
  const eventsResult = runKubectl(['get', 'events', '-n', namespace, '-o', 'json', '--ignore-not-found'], { kubectl, timeoutMs, env, allowFailure: true });
423
- const permissions = await Promise.all(KRATE_RESOURCES.filter((definition) => discoveredPluralSet.has(`${definition.group || KRATE_API_GROUP}/${definition.plural}`)).map(async (definition) => ({
468
+ const permissions = await Promise.all(snapshotResources.filter((definition) => discoveredPluralSet.has(`${definition.group || KRATE_API_GROUP}/${definition.plural}`)).map(async (definition) => ({
424
469
  kind: definition.kind,
425
470
  plural: definition.plural,
426
471
  verbs: Object.fromEntries(['get', 'list', 'watch', 'create', 'update', 'patch', 'delete'].map((verb) => [verb, canI(verb, definition, { kubectl, namespace: definition.namespace || namespace, timeoutMs, env })]))
@@ -443,7 +488,7 @@ export async function getControllerSnapshot(options = {}) {
443
488
  apiService: apiServiceResult.ok ? safeJson(apiServiceResult.stdout) : null,
444
489
  crds: discoveredCrds,
445
490
  resources,
446
- kyverno,
491
+ kyverno,
447
492
  events: eventsResult.ok ? parseKubernetesList(eventsResult.stdout).items : [],
448
493
  permissions,
449
494
  storage: storageBoundaries(),
@@ -484,16 +529,29 @@ export async function applyResource(resource, options = {}) {
484
529
  if (!resource.kind) throw new Error('resource.kind is required');
485
530
  const namespace = options.namespace || process.env.KRATE_NAMESPACE || 'krate-system';
486
531
  const manifest = withOrgScope(resource, { namespace });
532
+ const kubectlBin = options.kubectl || process.env.KRATE_KUBECTL || 'kubectl';
533
+ const timeoutMs = Number(options.timeoutMs || process.env.KRATE_KUBECTL_TIMEOUT_MS || 3_000);
534
+ const env = { ...process.env, ...(options.env || {}) };
535
+ const targetNs = manifest.metadata?.namespace;
536
+ if (targetNs) {
537
+ ensureNamespace(targetNs, { kubectl: kubectlBin, timeoutMs, env });
538
+ }
487
539
  const result = runKubectl(['apply', '-f', '-', '-o', 'json'], {
488
- kubectl: options.kubectl || process.env.KRATE_KUBECTL || 'kubectl',
489
- timeoutMs: Number(options.timeoutMs || process.env.KRATE_KUBECTL_TIMEOUT_MS || 3_000),
490
- env: { ...process.env, ...(options.env || {}) },
540
+ kubectl: kubectlBin,
541
+ timeoutMs,
542
+ env,
491
543
  input: JSON.stringify(manifest),
492
544
  allowFailure: false
493
545
  });
494
546
  return { operation: 'apply', command: 'kubectl apply -f -', resource: safeJson(result.stdout) || manifest, stderr: result.stderr.trim() };
495
547
  }
496
548
 
549
+ function ensureNamespace(name, options) {
550
+ const check = runKubectl(['get', 'namespace', name], { ...options, allowFailure: true });
551
+ if (check.ok) return;
552
+ runKubectl(['create', 'namespace', name], { ...options, allowFailure: true });
553
+ }
554
+
497
555
  export async function deleteResource(kindOrPlural, name, options = {}) {
498
556
  if (!name) throw new Error('resource name is required');
499
557
  const namespace = options.namespace || process.env.KRATE_NAMESPACE || 'krate-system';
@@ -594,7 +652,9 @@ export function findResourceDefinition(kindOrPlural) {
594
652
  }
595
653
 
596
654
  export function apiResourceName(definition) {
597
- return `${definition.plural}.${definition.group || KRATE_API_GROUP}`;
655
+ // Core K8s resources (Secret, ConfigMap) have group: '' — use bare plural name
656
+ const group = definition.group === '' ? '' : (definition.group || KRATE_API_GROUP);
657
+ return group ? `${definition.plural}.${group}` : definition.plural;
598
658
  }
599
659
 
600
660
  export function withKrateDefaults(resource, namespace) {
@@ -683,76 +743,88 @@ function inClusterKubectlConfig(env = process.env) {
683
743
  }
684
744
 
685
745
 
686
- function kyvernoMode(env = process.env) {
687
- const configured = env.KRATE_KYVERNO_MODE || env.KRATE_EXTERNAL_KYVERNO_MODE;
688
- if (configured) return configured;
689
- if (String(env.KRATE_KYVERNO_ENABLED || '').toLowerCase() === 'true') return 'byo';
690
- if (String(env.KRATE_KYVERNO_DISCOVER_EXISTING || '').toLowerCase() !== 'false') return 'auto';
691
- return 'disabled';
692
- }
693
-
694
- function emptyKyvernoDiscovery(namespace = KRATE_PLATFORM_NAMESPACE, env = process.env) {
695
- return {
696
- mode: kyvernoMode(env),
697
- namespace: env.KRATE_KYVERNO_NAMESPACE || env.KRATE_EXTERNAL_KYVERNO_NAMESPACE || 'kyverno',
698
- policyNamespace: env.KRATE_KYVERNO_POLICY_NAMESPACE || namespace,
699
- requireForEnforceMode: String(env.KRATE_KYVERNO_REQUIRE_FOR_ENFORCE_MODE || 'true') !== 'false',
700
- detected: false,
701
- controllers: [],
702
- resources: Object.fromEntries(KYVERNO_RESOURCES.map((definition) => [definition.kind, []])),
703
- reports: { policyReports: [], clusterPolicyReports: [], results: [], violations: [] },
704
- permissions: [],
705
- degraded: []
706
- };
707
- }
708
-
709
- function discoverKyverno({ kubectl, namespace, timeoutMs, env, discoveredPluralSet }) {
710
- const discovery = emptyKyvernoDiscovery(namespace, env);
711
- const availableDefinitions = KYVERNO_RESOURCES.filter((definition) => discoveredPluralSet.has(`${definition.group || KRATE_API_GROUP}/${definition.plural}`));
712
- discovery.detected = availableDefinitions.length > 0;
713
- if (discovery.detected && discovery.mode === 'auto') discovery.mode = 'byo';
714
- if (!discovery.detected) {
715
- if (discovery.mode !== 'disabled') discovery.degraded.push('Kyverno CRDs are not installed or are not readable by the Krate service account.');
716
- return discovery;
717
- }
718
-
719
- const listResults = [];
720
- for (const definition of availableDefinitions) {
721
- const resourceNamespace = definition.namespaced === false ? null : definition.namespace || (definition.kind === 'PolicyReport' ? namespace : discovery.policyNamespace);
722
- const result = runKubectl(['get', apiResourceName(definition), ...namespaceArgs(definition, resourceNamespace), '-o', 'json', '--ignore-not-found'], { kubectl, timeoutMs, env, allowFailure: true });
723
- listResults.push({ definition, result });
724
- discovery.resources[definition.kind] = result.ok ? parseKubernetesList(result.stdout).items : [];
725
- }
726
-
727
- const deploymentsResult = runKubectl(['get', 'deploy', '-n', discovery.namespace, '-o', 'json', '--ignore-not-found'], { kubectl, timeoutMs, env, allowFailure: true });
728
- discovery.controllers = deploymentsResult.ok ? parseKubernetesList(deploymentsResult.stdout).items.filter((deployment) => String(deployment.metadata?.name || '').includes('kyverno') || deployment.metadata?.labels?.['app.kubernetes.io/part-of'] === 'kyverno').map((deployment) => ({ name: deployment.metadata?.name, namespace: deployment.metadata?.namespace || discovery.namespace, ready: Number(deployment.status?.readyReplicas || 0) >= Number(deployment.spec?.replicas || 1), readyReplicas: deployment.status?.readyReplicas || 0, replicas: deployment.spec?.replicas || 0 })) : [];
729
-
730
- discovery.permissions = availableDefinitions.map((definition) => {
731
- const resourceNamespace = definition.namespaced === false ? null : definition.namespace || (definition.kind === 'PolicyReport' ? namespace : discovery.policyNamespace);
732
- return {
733
- kind: definition.kind,
734
- plural: definition.plural,
735
- apiResource: apiResourceName(definition),
736
- verbs: Object.fromEntries(['get', 'list', 'watch', 'create', 'patch'].map((verb) => [verb, canI(verb, definition, { kubectl, namespace: resourceNamespace || namespace, timeoutMs, env })]))
737
- };
738
- });
739
-
740
- const policyReports = discovery.resources.PolicyReport || [];
741
- const clusterPolicyReports = discovery.resources.ClusterPolicyReport || [];
742
- const results = [...policyReports, ...clusterPolicyReports].flatMap((report) => (report.results || []).map((result) => ({ report: report.metadata?.name, namespace: report.metadata?.namespace || '', policy: result.policy, rule: result.rule, result: result.result, severity: result.severity || result.properties?.severity || 'medium', message: result.message || '', resource: result.resources?.[0] || report.scope || null })));
743
- discovery.reports = { policyReports, clusterPolicyReports, results, violations: results.filter((result) => ['fail', 'error', 'warn'].includes(String(result.result || '').toLowerCase())) };
744
- discovery.degraded.push(...listResults.filter(({ result }) => !result.ok).map(({ definition, result }) => `${definition.kind}: ${commandFailure(result)}`));
745
- if (discovery.mode !== 'disabled' && discovery.controllers.length === 0) discovery.degraded.push(`No Kyverno controller deployments were found in namespace ${discovery.namespace}.`);
746
- return discovery;
747
- }
746
+ function kyvernoMode(env = process.env) {
747
+ const configured = env.KRATE_KYVERNO_MODE || env.KRATE_EXTERNAL_KYVERNO_MODE;
748
+ if (configured) return configured;
749
+ if (String(env.KRATE_KYVERNO_ENABLED || '').toLowerCase() === 'true') return 'byo';
750
+ if (String(env.KRATE_KYVERNO_DISCOVER_EXISTING || '').toLowerCase() !== 'false') return 'auto';
751
+ return 'disabled';
752
+ }
753
+
754
+ function emptyKyvernoDiscovery(namespace = KRATE_PLATFORM_NAMESPACE, env = process.env) {
755
+ return {
756
+ mode: kyvernoMode(env),
757
+ namespace: env.KRATE_KYVERNO_NAMESPACE || env.KRATE_EXTERNAL_KYVERNO_NAMESPACE || 'kyverno',
758
+ policyNamespace: env.KRATE_KYVERNO_POLICY_NAMESPACE || namespace,
759
+ requireForEnforceMode: String(env.KRATE_KYVERNO_REQUIRE_FOR_ENFORCE_MODE || 'true') !== 'false',
760
+ detected: false,
761
+ controllers: [],
762
+ resources: Object.fromEntries(KYVERNO_RESOURCES.map((definition) => [definition.kind, []])),
763
+ reports: { policyReports: [], clusterPolicyReports: [], results: [], violations: [] },
764
+ permissions: [],
765
+ degraded: []
766
+ };
767
+ }
768
+
769
+ function discoverKyverno({ kubectl, namespace, timeoutMs, env, discoveredPluralSet }) {
770
+ const discovery = emptyKyvernoDiscovery(namespace, env);
771
+ const availableDefinitions = KYVERNO_RESOURCES.filter((definition) => discoveredPluralSet.has(`${definition.group || KRATE_API_GROUP}/${definition.plural}`));
772
+ discovery.detected = availableDefinitions.length > 0;
773
+ if (discovery.detected && discovery.mode === 'auto') discovery.mode = 'byo';
774
+ if (!discovery.detected) {
775
+ if (discovery.mode !== 'disabled') discovery.degraded.push('Kyverno CRDs are not installed or are not readable by the Krate service account.');
776
+ return discovery;
777
+ }
778
+
779
+ const listResults = [];
780
+ for (const definition of availableDefinitions) {
781
+ const resourceNamespace = definition.namespaced === false ? null : definition.namespace || (definition.kind === 'PolicyReport' ? namespace : discovery.policyNamespace);
782
+ const result = runKubectl(['get', apiResourceName(definition), ...namespaceArgs(definition, resourceNamespace), '-o', 'json', '--ignore-not-found'], { kubectl, timeoutMs, env, allowFailure: true });
783
+ listResults.push({ definition, result });
784
+ discovery.resources[definition.kind] = result.ok ? parseKubernetesList(result.stdout).items : [];
785
+ }
786
+
787
+ const deploymentsResult = runKubectl(['get', 'deploy', '-n', discovery.namespace, '-o', 'json', '--ignore-not-found'], { kubectl, timeoutMs, env, allowFailure: true });
788
+ discovery.controllers = deploymentsResult.ok ? parseKubernetesList(deploymentsResult.stdout).items.filter((deployment) => String(deployment.metadata?.name || '').includes('kyverno') || deployment.metadata?.labels?.['app.kubernetes.io/part-of'] === 'kyverno').map((deployment) => ({ name: deployment.metadata?.name, namespace: deployment.metadata?.namespace || discovery.namespace, ready: Number(deployment.status?.readyReplicas || 0) >= Number(deployment.spec?.replicas || 1), readyReplicas: deployment.status?.readyReplicas || 0, replicas: deployment.spec?.replicas || 0 })) : [];
789
+
790
+ discovery.permissions = availableDefinitions.map((definition) => {
791
+ const resourceNamespace = definition.namespaced === false ? null : definition.namespace || (definition.kind === 'PolicyReport' ? namespace : discovery.policyNamespace);
792
+ return {
793
+ kind: definition.kind,
794
+ plural: definition.plural,
795
+ apiResource: apiResourceName(definition),
796
+ verbs: Object.fromEntries(['get', 'list', 'watch', 'create', 'patch'].map((verb) => [verb, canI(verb, definition, { kubectl, namespace: resourceNamespace || namespace, timeoutMs, env })]))
797
+ };
798
+ });
799
+
800
+ const policyReports = discovery.resources.PolicyReport || [];
801
+ const clusterPolicyReports = discovery.resources.ClusterPolicyReport || [];
802
+ const results = [...policyReports, ...clusterPolicyReports].flatMap((report) => (report.results || []).map((result) => ({ report: report.metadata?.name, namespace: report.metadata?.namespace || '', policy: result.policy, rule: result.rule, result: result.result, severity: result.severity || result.properties?.severity || 'medium', message: result.message || '', resource: result.resources?.[0] || report.scope || null })));
803
+ discovery.reports = { policyReports, clusterPolicyReports, results, violations: results.filter((result) => ['fail', 'error', 'warn'].includes(String(result.result || '').toLowerCase())) };
804
+ discovery.degraded.push(...listResults.filter(({ result }) => !result.ok).map(({ definition, result }) => `${definition.kind}: ${commandFailure(result)}`));
805
+ if (discovery.mode !== 'disabled' && discovery.controllers.length === 0) discovery.degraded.push(`No Kyverno controller deployments were found in namespace ${discovery.namespace}.`);
806
+ return discovery;
807
+ }
748
808
  function organizationNamespaces(organizations = [], bindings = [], fallbackNamespace = KRATE_PLATFORM_NAMESPACE) {
749
809
  const namespaces = [...new Set([
750
810
  ...organizations.map((org) => org.spec?.namespaceName || org.metadata?.labels?.[KRATE_ORG_NAMESPACE_LABEL]).filter(Boolean),
751
811
  ...bindings.map((binding) => binding.spec?.namespace || binding.metadata?.labels?.[KRATE_ORG_NAMESPACE_LABEL]).filter(Boolean)
752
812
  ])];
753
- return namespaces.length ? namespaces : [fallbackNamespace];
754
- }
755
-
813
+ if (namespaces.length) return namespaces;
814
+ const fallbackOrgs = new Set();
815
+ const adminOrg = process.env.KRATE_ADMIN_ORG;
816
+ const defaultOrg = process.env.KRATE_ORG || 'default';
817
+ if (adminOrg) fallbackOrgs.add(orgNamespaceName(adminOrg));
818
+ fallbackOrgs.add(orgNamespaceName(defaultOrg));
819
+ return fallbackOrgs.size ? [...fallbackOrgs] : [fallbackNamespace];
820
+ }
821
+
822
+ function shouldListSnapshotDefinition(definition, discoveredPluralSet) {
823
+ const group = definition.group || KRATE_API_GROUP;
824
+ if (discoveredPluralSet.has(`${group}/${definition.plural}`)) return true;
825
+ return group === KRATE_API_GROUP;
826
+ }
827
+
756
828
  function parseKubernetesList(stdout) {
757
829
  const parsed = safeJson(stdout);
758
830
  if (!parsed) return { items: [] };
@@ -0,0 +1,178 @@
1
+ import { randomUUID } from 'node:crypto';
2
+
3
+ export const NOTIFICATION_CONTROLLER_BOUNDARY = {
4
+ role: 'notification-controller',
5
+ scope: 'User notification lifecycle: creation from events, querying, read state, and preferences',
6
+ owns: ['notification creation', 'notification listing', 'read state', 'user preferences'],
7
+ delegatesTo: [],
8
+ mustNotOwn: ['event dispatch', 'UI rendering', 'push delivery']
9
+ };
10
+
11
+ const NOTIFICATION_TYPES = {
12
+ 'run-complete': { severity: 'info' },
13
+ 'approval-needed': { severity: 'warning' },
14
+ 'conflict-detected': { severity: 'warning' },
15
+ 'workspace-ready': { severity: 'info' },
16
+ 'system': { severity: 'info' },
17
+ };
18
+
19
+ const DEFAULT_PREFERENCES = {
20
+ runs: true,
21
+ approvals: true,
22
+ conflicts: true,
23
+ workspaces: true,
24
+ sound: false,
25
+ desktop: false,
26
+ };
27
+
28
+ export function createNotificationController() {
29
+ // Map of org -> notifications[]
30
+ const store = new Map();
31
+ // Map of userId -> preferences
32
+ const prefsStore = new Map();
33
+
34
+ function getOrgNotifications(org) {
35
+ if (!store.has(org)) store.set(org, []);
36
+ return store.get(org);
37
+ }
38
+
39
+ function mapEventToNotification(event) {
40
+ const { type, status, name, action, resourceRef, org = 'default' } = event || {};
41
+
42
+ let notifType = 'system';
43
+ let title = 'System event';
44
+ let message = '';
45
+ let severity = 'info';
46
+
47
+ if (type === 'AgentDispatchRun') {
48
+ notifType = 'run-complete';
49
+ const runName = name || event?.metadata?.name || 'Unknown';
50
+ if (status === 'completed') {
51
+ title = `Run ${runName} completed`;
52
+ message = `Agent dispatch run "${runName}" completed successfully.`;
53
+ severity = 'info';
54
+ } else if (status === 'failed') {
55
+ title = `Run ${runName} failed`;
56
+ message = `Agent dispatch run "${runName}" failed.`;
57
+ severity = 'error';
58
+ } else {
59
+ title = `Run ${runName} updated`;
60
+ message = `Agent dispatch run "${runName}" status: ${status || 'unknown'}.`;
61
+ severity = 'info';
62
+ }
63
+ } else if (type === 'AgentApproval' && status === 'pending') {
64
+ notifType = 'approval-needed';
65
+ const actionLabel = action || event?.spec?.action || 'unknown action';
66
+ title = `Approval needed for ${actionLabel}`;
67
+ message = `An agent is requesting approval for: ${actionLabel}.`;
68
+ severity = 'warning';
69
+ } else if (type === 'ExternalSyncConflict') {
70
+ notifType = 'conflict-detected';
71
+ const resource = resourceRef || event?.spec?.resourceRef || name || 'unknown resource';
72
+ title = `Conflict in ${resource}`;
73
+ message = `A sync conflict was detected in resource: ${resource}.`;
74
+ severity = 'warning';
75
+ } else if (type === 'KrateWorkspace' && event?.claimed) {
76
+ notifType = 'workspace-ready';
77
+ const wsName = name || event?.metadata?.name || 'Unknown';
78
+ const runRef = event?.claimedBy || event?.spec?.claimedBy || 'a run';
79
+ title = `Workspace ${wsName} claimed by ${runRef}`;
80
+ message = `Workspace "${wsName}" has been claimed by "${runRef}".`;
81
+ severity = 'info';
82
+ }
83
+
84
+ return { notifType, title, message, severity, org };
85
+ }
86
+
87
+ return {
88
+ role: 'notification-controller',
89
+
90
+ createNotification(event) {
91
+ const { notifType, title, message, severity, org } = mapEventToNotification(event);
92
+
93
+ const notification = {
94
+ id: randomUUID(),
95
+ type: notifType,
96
+ title,
97
+ message,
98
+ severity,
99
+ resourceRef: event?.resourceRef || null,
100
+ createdAt: new Date().toISOString(),
101
+ read: false,
102
+ org,
103
+ };
104
+
105
+ const notifications = getOrgNotifications(org);
106
+ notifications.push(notification);
107
+
108
+ return notification;
109
+ },
110
+
111
+ listNotifications(org, opts = {}) {
112
+ const { unreadOnly = false, limit = 20, since = null } = opts;
113
+ let notifications = [...getOrgNotifications(org)];
114
+
115
+ // Filter by read state
116
+ if (unreadOnly) {
117
+ notifications = notifications.filter((n) => !n.read);
118
+ }
119
+
120
+ // Filter by since timestamp
121
+ if (since) {
122
+ const sinceDate = new Date(since).getTime();
123
+ notifications = notifications.filter((n) => new Date(n.createdAt).getTime() > sinceDate);
124
+ }
125
+
126
+ // Newest first
127
+ notifications.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
128
+
129
+ // Cap to limit
130
+ if (limit > 0) {
131
+ notifications = notifications.slice(0, limit);
132
+ }
133
+
134
+ return notifications;
135
+ },
136
+
137
+ markAsRead(notificationId) {
138
+ for (const notifications of store.values()) {
139
+ const notification = notifications.find((n) => n.id === notificationId);
140
+ if (notification) {
141
+ notification.read = true;
142
+ return true;
143
+ }
144
+ }
145
+ return false;
146
+ },
147
+
148
+ markAllAsRead(org) {
149
+ const notifications = getOrgNotifications(org);
150
+ let count = 0;
151
+ for (const notification of notifications) {
152
+ if (!notification.read) {
153
+ notification.read = true;
154
+ count++;
155
+ }
156
+ }
157
+ return count;
158
+ },
159
+
160
+ getUnreadCount(org) {
161
+ return getOrgNotifications(org).filter((n) => !n.read).length;
162
+ },
163
+
164
+ getPreferences(userId) {
165
+ if (!prefsStore.has(userId)) {
166
+ return { ...DEFAULT_PREFERENCES };
167
+ }
168
+ return { ...DEFAULT_PREFERENCES, ...prefsStore.get(userId) };
169
+ },
170
+
171
+ updatePreferences(userId, prefs) {
172
+ const existing = prefsStore.get(userId) || {};
173
+ const merged = { ...DEFAULT_PREFERENCES, ...existing, ...prefs };
174
+ prefsStore.set(userId, merged);
175
+ return merged;
176
+ },
177
+ };
178
+ }
@@ -0,0 +1,5 @@
1
+ // Dedicated org-scoping module — re-exports the org namespace derivation
2
+ // function so callers can depend on it without pulling in the full
3
+ // kubernetes-controller surface.
4
+
5
+ export { orgNamespaceName, normalizeOrgSlug, resolveResourceOrg, withOrgScope } from './kubernetes-controller.js';
@@ -1,5 +1,5 @@
1
- export const CONFIG_KINDS = new Set(['Organization', 'OrgNamespaceBinding', 'User', 'Team', 'Invite', 'IdentityMapping', 'AuthProvider', 'Repository', 'SSHKey', 'RepositoryPermission', 'WebhookSubscription', 'RefPolicy', 'BranchProtection', 'PolicyProfile', 'PolicyTemplate', 'PolicyBinding', 'PolicyExceptionRequest', 'RunnerPool', 'View', 'Selector', 'AgentStack', 'AgentSubagent', 'AgentToolProfile', 'AgentMcpServer', 'AgentSkill', 'AgentTriggerRule', 'AgentContextLabel', 'AgentWorkspacePolicy', 'AgentServiceAccount', 'AgentRoleBinding', 'AgentSecretGrant', 'AgentConfigGrant', 'AgentAdapter', 'AgentTransportBinding', 'AgentProviderConfig', 'AgentProject', 'AgentGatewayConfig']);
2
- export const AGGREGATED_KINDS = new Set(['PullRequest', 'Issue', 'Review', 'Pipeline', 'Job', 'WebhookDelivery', 'AgentDispatchRun', 'AgentDispatchAttempt', 'AgentSession', 'AgentContextBundle', 'AgentArtifact', 'AgentApproval', 'AgentWorkspace', 'AgentTriggerExecution', 'AgentCapabilityRequirement', 'WorkItemSessionLink', 'WorkItemWorkspaceLink', 'AgentSessionTranscript', 'AgentSessionAttachment', 'AgentWorkspaceRuntime']);
1
+ export const CONFIG_KINDS = new Set(['Organization', 'OrgNamespaceBinding', 'User', 'Team', 'Invite', 'IdentityMapping', 'AuthProvider', 'Repository', 'SSHKey', 'RepositoryPermission', 'WebhookSubscription', 'RefPolicy', 'BranchProtection', 'PolicyProfile', 'PolicyTemplate', 'PolicyBinding', 'PolicyExceptionRequest', 'RunnerPool', 'View', 'Selector', 'AgentStack', 'AgentSubagent', 'AgentToolProfile', 'AgentMcpServer', 'AgentSkill', 'AgentTriggerRule', 'AgentContextLabel', 'KrateWorkspacePolicy', 'AgentServiceAccount', 'AgentRoleBinding', 'AgentSecretGrant', 'AgentConfigGrant', 'AgentAdapter', 'AgentTransportBinding', 'AgentProviderConfig', 'KrateProject', 'AgentGatewayConfig', 'AgentMemoryRepository', 'AgentMemorySource', 'AgentMemoryOntology', 'AgentMemoryAssociation', 'KrateWorkspace', 'ExternalBackendProvider', 'ExternalBackendBinding', 'ExternalBackendSyncPolicy', 'ExternalProviderCapabilityManifest']);
2
+ export const AGGREGATED_KINDS = new Set(['PullRequest', 'Issue', 'Review', 'Pipeline', 'Job', 'WebhookDelivery', 'AgentDispatchRun', 'AgentDispatchAttempt', 'AgentSession', 'AgentContextBundle', 'KrateArtifact', 'AgentApproval', 'AgentTriggerExecution', 'AgentCapabilityRequirement', 'WorkItemSessionLink', 'WorkItemWorkspaceLink', 'AgentSessionTranscript', 'AgentSessionAttachment', 'KrateWorkspaceRuntime', 'AgentMemorySnapshot', 'AgentMemoryQuery', 'AgentMemoryUpdate', 'AgentRunMemoryImport', 'ExternalWebhookDelivery', 'ExternalSyncEvent', 'ExternalSyncState', 'ExternalWriteIntent', 'ExternalSyncConflict', 'ExternalObjectLink']);
3
3
  export const ALL_KINDS = new Set([...CONFIG_KINDS, ...AGGREGATED_KINDS]);
4
4
 
5
5
  export const RESOURCE_DEFINITIONS = Object.freeze({
@@ -23,7 +23,7 @@ export const RESOURCE_DEFINITIONS = Object.freeze({
23
23
  View: { storage: 'etcd', context: 'web-ui', plural: 'views', purpose: 'Saved triage and dashboard view backed by resource selectors', requiredSpec: ['organizationRef', 'selector'] },
24
24
  Selector: { storage: 'etcd', context: 'web-ui', plural: 'selectors', purpose: 'Reusable label/query selector for workflows and views', requiredSpec: ['organizationRef'] },
25
25
  PullRequest: { storage: 'postgres', context: 'control-plane', plural: 'pullrequests', purpose: 'Review unit with source/target refs, title, checks, and merge lifecycle', requiredSpec: ['organizationRef', 'repository', 'title'] },
26
- Issue: { storage: 'postgres', context: 'control-plane', plural: 'issues', purpose: 'Work item with labels, assignment, and lifecycle state', requiredSpec: ['organizationRef', 'title'] },
26
+ Issue: { storage: 'postgres', context: 'control-plane', plural: 'issues', purpose: 'Project-scoped work item with labels, comments, backend sync metadata, and zero-or-more repository associations', requiredSpec: ['organizationRef', 'title'] },
27
27
  Review: { storage: 'postgres', context: 'control-plane', plural: 'reviews', purpose: 'Approval, comment, or change-request record for a pull request', requiredSpec: ['organizationRef', 'pullRequest'] },
28
28
  Pipeline: { storage: 'postgres', context: 'runners-ci', plural: 'pipelines', purpose: 'CI pipeline run state, trust tier, steps, and resume point', requiredSpec: ['organizationRef', 'repository', 'ref'] },
29
29
  Job: { storage: 'postgres', context: 'runners-ci', plural: 'jobs', purpose: 'Executable CI step with service-account scope and isolation metadata', requiredSpec: ['organizationRef', 'pipeline', 'step'] },
@@ -36,7 +36,7 @@ export const RESOURCE_DEFINITIONS = Object.freeze({
36
36
  AgentSkill: { storage: 'etcd', context: 'agents', plural: 'agentskills', purpose: 'Reusable runbook/procedure bundle with prompt fragments, tool deps, and output contracts', requiredSpec: ['organizationRef', 'format', 'sourceRef'] },
37
37
  AgentTriggerRule: { storage: 'etcd', context: 'agents', plural: 'agenttriggerrules', purpose: 'Event-to-stack routing for CI failures, webhooks, comments, labels, schedules, and manual dispatch', requiredSpec: ['organizationRef', 'sources', 'agentStack', 'taskKind'] },
38
38
  AgentContextLabel: { storage: 'etcd', context: 'agents', plural: 'agentcontextlabels', purpose: 'Reviewed prompt fragment with provenance and allowlisted sources', requiredSpec: ['organizationRef', 'promptFragment', 'allowedSources'] },
39
- AgentWorkspacePolicy: { storage: 'etcd', context: 'agents', plural: 'agentworkspacepolicies', purpose: 'Git worktree provisioning, cleanup, retention, and trust tier policies', requiredSpec: ['organizationRef', 'mode', 'retentionPolicy'] },
39
+ KrateWorkspacePolicy: { storage: 'etcd', context: 'agents', plural: 'krateworkspacepolicies', purpose: 'Git worktree provisioning, cleanup, retention, and trust tier policies', requiredSpec: ['organizationRef', 'mode', 'retentionPolicy'] },
40
40
  AgentServiceAccount: { storage: 'etcd', context: 'identity', plural: 'agentserviceaccounts', purpose: 'Kubernetes ServiceAccount wrapper for agent/runner identity binding', requiredSpec: ['organizationRef', 'namespace', 'serviceAccountName'] },
41
41
  AgentRoleBinding: { storage: 'etcd', context: 'identity', plural: 'agentrolebindings', purpose: 'Managed projection to native Kubernetes RBAC for agent identity', requiredSpec: ['organizationRef', 'subject', 'roleRef', 'scope'] },
42
42
  AgentSecretGrant: { storage: 'etcd', context: 'identity', plural: 'agentsecretgrants', purpose: 'Explicit permission for subject to access Secret keys with purpose scope', requiredSpec: ['organizationRef', 'subject', 'secretRef', 'purpose'] },
@@ -45,9 +45,9 @@ export const RESOURCE_DEFINITIONS = Object.freeze({
45
45
  AgentDispatchAttempt: { storage: 'postgres', context: 'agents', plural: 'agentdispatchattempts', purpose: 'Concrete execution attempt with reason, stack snapshot, and runtime state', requiredSpec: ['organizationRef', 'agentDispatchRun', 'attemptReason', 'agentStackSnapshot'] },
46
46
  AgentSession: { storage: 'postgres', context: 'agents', plural: 'agentsessions', purpose: 'Krate projection of Agent Mux chat/session with lifecycle state', requiredSpec: ['organizationRef', 'agentMuxSessionId', 'dispatchRun'] },
47
47
  AgentContextBundle: { storage: 'postgres', context: 'agents', plural: 'agentcontextbundles', purpose: 'Immutable prompt/context snapshot with digest, provenance, and redaction manifest', requiredSpec: ['organizationRef', 'dispatchRun', 'digest', 'sources'] },
48
- AgentArtifact: { storage: 'postgres', context: 'agents', plural: 'agentartifacts', purpose: 'Durable agent output with kind, digest, and retention policy', requiredSpec: ['organizationRef', 'dispatchRun', 'kind', 'digest'] },
48
+ KrateArtifact: { storage: 'postgres', context: 'agents', plural: 'krateartifacts', purpose: 'Durable agent output with kind, digest, and retention policy', requiredSpec: ['organizationRef', 'dispatchRun', 'kind', 'digest'] },
49
49
  AgentApproval: { storage: 'postgres', context: 'agents', plural: 'agentapprovals', purpose: 'Human gate for tools, secrets, write-back, and release actions', requiredSpec: ['organizationRef', 'dispatchRun', 'action', 'requestedBy'] },
50
- AgentWorkspace: { storage: 'postgres', context: 'agents', plural: 'agentworkspaces', purpose: 'Git worktree/runtime inventory with lifecycle state and ownership', requiredSpec: ['organizationRef', 'repository', 'workspacePath', 'ownership'] },
50
+ KrateWorkspace: { storage: 'etcd', context: 'workspaces', plural: 'krateworkspaces', purpose: 'Volume-backed git workspace with PVC lifecycle, repo binding, and runner mount spec', requiredSpec: ['organizationRef', 'repository', 'volumeSpec'] },
51
51
  AgentTriggerExecution: { storage: 'postgres', context: 'agents', plural: 'agenttriggerexecutions', purpose: 'Durable trigger evaluation record with dedupe, coalescing, and rejection reason', requiredSpec: ['organizationRef', 'triggerRule', 'sourceEvent', 'decision'] },
52
52
  AgentCapabilityRequirement: { storage: 'postgres', context: 'agents', plural: 'agentcapabilityrequirements', purpose: 'Computed dependency record from tools, MCP, skills, models, and subagents', requiredSpec: ['organizationRef', 'ownerRef', 'requiredRoles'] },
53
53
  WorkItemSessionLink: { storage: 'postgres', context: 'agents', plural: 'workitemsessionlinks', purpose: 'Association between issues/PRs and agent sessions', requiredSpec: ['organizationRef', 'workItemRef', 'agentSession'] },
@@ -55,11 +55,29 @@ export const RESOURCE_DEFINITIONS = Object.freeze({
55
55
  AgentAdapter: { storage: 'etcd', context: 'agents', plural: 'agentadapters', purpose: 'Agent adapter definition with transport type, capabilities matrix, auth requirements, and installation method', requiredSpec: ['organizationRef', 'adapterType', 'transport'] },
56
56
  AgentTransportBinding: { storage: 'etcd', context: 'agents', plural: 'agenttransportbindings', purpose: 'Connection configuration for an adapter instance with endpoint, protocol, auth, health check, and reconnect policy', requiredSpec: ['organizationRef', 'adapterRef', 'endpoint', 'protocol'] },
57
57
  AgentProviderConfig: { storage: 'etcd', context: 'agents', plural: 'agentproviderconfigs', purpose: 'Model provider configuration with API base, auth type, default model, model translations, and rate limits', requiredSpec: ['organizationRef', 'provider', 'authType'] },
58
- AgentProject: { storage: 'etcd', context: 'agents', plural: 'agentprojects', purpose: 'Project grouping issues with kanban board config, default workflow, and team refs', requiredSpec: ['organizationRef', 'displayName'] },
58
+ KrateProject: { storage: 'etcd', context: 'agents', plural: 'krateprojects', purpose: 'Org project grouping issues, linked repositories, kanban board config, default workflow, and backend sync refs', requiredSpec: ['organizationRef', 'displayName'] },
59
59
  AgentGatewayConfig: { storage: 'etcd', context: 'agents', plural: 'agentgatewayconfigs', purpose: 'Runtime Agent Mux gateway connection settings with URL, auth, reconnect policy, and feature flags', requiredSpec: ['organizationRef', 'gatewayUrl'] },
60
60
  AgentSessionTranscript: { storage: 'postgres', context: 'agents', plural: 'agentsessiontranscripts', purpose: 'Durable chat transcript with message nodes, pagination support, and cost per turn', requiredSpec: ['organizationRef', 'sessionRef', 'messages'] },
61
61
  AgentSessionAttachment: { storage: 'postgres', context: 'agents', plural: 'agentsessionattachments', purpose: 'File attached to a session message with source type, MIME type, digest, and redaction status', requiredSpec: ['organizationRef', 'sessionRef', 'sourceType', 'digest'] },
62
- AgentWorkspaceRuntime: { storage: 'postgres', context: 'agents', plural: 'agentworkspaceruntimes', purpose: 'Workspace runtime surface state with cwd, environment variables, process status, and preview URL', requiredSpec: ['organizationRef', 'workspaceRef', 'status'] }
62
+ KrateWorkspaceRuntime: { storage: 'postgres', context: 'agents', plural: 'krateworkspaceruntimes', purpose: 'Workspace runtime surface state with cwd, environment variables, process status, and preview URL', requiredSpec: ['organizationRef', 'workspaceRef', 'status'] },
63
+ AgentMemoryRepository: { storage: 'etcd', context: 'agents', plural: 'agentmemoryrepositories', purpose: 'Org-level Git repository pointer for shared agent memory with layout profile and index policy', requiredSpec: ['organizationRef', 'repositoryRef', 'defaultBranch', 'layoutProfile'] },
64
+ AgentMemorySource: { storage: 'etcd', context: 'agents', plural: 'agentmemorysources', purpose: 'Read policy for memory paths and kinds per repository, team, stack, or trigger', requiredSpec: ['organizationRef', 'repositoryRef', 'appliesTo', 'include'] },
65
+ AgentMemoryOntology: { storage: 'etcd', context: 'agents', plural: 'agentmemoryontologies', purpose: 'Ontology policy pointer with required fields, edge kinds, and controlled vocabulary', requiredSpec: ['organizationRef', 'memoryRepository', 'ontologyPath'] },
66
+ AgentMemoryAssociation: { storage: 'etcd', context: 'agents', plural: 'agentmemoryassociations', purpose: 'Bridge record linking memory content to Krate resources by relationship type', requiredSpec: ['organizationRef', 'memoryRef', 'targetRef', 'relationship'] },
67
+ AgentMemorySnapshot: { storage: 'postgres', context: 'agents', plural: 'agentmemorysnapshots', purpose: 'Immutable dispatch-time memory pin with resolved commit, query manifest digest, and selected records digest', requiredSpec: ['organizationRef', 'memoryRepository', 'requestedRef', 'resolvedCommit'] },
68
+ AgentMemoryQuery: { storage: 'postgres', context: 'agents', plural: 'agentmemoryqueries', purpose: 'Graph and grep retrieval record with query parameters, result digests, and ranking metadata', requiredSpec: ['organizationRef', 'snapshotRef', 'requester', 'query'] },
69
+ AgentMemoryUpdate: { storage: 'postgres', context: 'agents', plural: 'agentmemoryupdates', purpose: 'Reviewable proposed memory mutation with branch, changes, and validation status', requiredSpec: ['organizationRef', 'memoryRepository', 'sourceRun', 'changes'] },
70
+ AgentRunMemoryImport: { storage: 'postgres', context: 'agents', plural: 'agentrunmemoryimports', purpose: 'Import curated babysitter run metadata into org company brain with redaction and review', requiredSpec: ['organizationRef', 'memoryRepository', 'source', 'include'] },
71
+ ExternalBackendProvider: { storage: 'etcd', context: 'external-backends', plural: 'externalbackendproviders', purpose: 'External backend provider registration with type, endpoint, auth configuration, and capability discovery settings', requiredSpec: ['organizationRef', 'providerType', 'endpoint'] },
72
+ ExternalBackendBinding: { storage: 'etcd', context: 'external-backends', plural: 'externalbackendbindings', purpose: 'Binding of an external backend provider to an organization with credential reference and sync scope', requiredSpec: ['organizationRef', 'providerRef', 'credentialRef'] },
73
+ ExternalBackendSyncPolicy: { storage: 'etcd', context: 'external-backends', plural: 'externalbackendsyncpolicies', purpose: 'Sync interval, conflict resolution mode, field mapping overrides, and retry policy for an external backend provider', requiredSpec: ['organizationRef', 'providerRef', 'syncInterval'] },
74
+ ExternalProviderCapabilityManifest: { storage: 'etcd', context: 'external-backends', plural: 'externalprovidercapabilitymanifests', purpose: 'Discovered capability surface of an external backend provider including supported resource kinds and API features', requiredSpec: ['organizationRef', 'providerRef', 'capabilities'] },
75
+ ExternalWebhookDelivery: { storage: 'postgres', context: 'external-backends', plural: 'externalwebhookdeliveries', purpose: 'Inbound webhook delivery from an external backend provider with event type, payload, and processing state', requiredSpec: ['organizationRef', 'providerRef', 'eventType', 'payload'] },
76
+ ExternalSyncEvent: { storage: 'postgres', context: 'external-backends', plural: 'externalsyncevents', purpose: 'Discrete sync event record from an external backend for a specific resource kind with dedupe and ordering metadata', requiredSpec: ['organizationRef', 'providerRef', 'eventKind', 'resourceRef'] },
77
+ ExternalSyncState: { storage: 'postgres', context: 'external-backends', plural: 'externalsyncstates', purpose: 'Current sync phase, last successful sync timestamp, and error details for an external resource binding', requiredSpec: ['organizationRef', 'providerRef', 'resourceRef', 'phase'] },
78
+ ExternalWriteIntent: { storage: 'postgres', context: 'external-backends', plural: 'externalwriteintents', purpose: 'Queued write-back intent to an external backend with operation, payload snapshot, and approval state', requiredSpec: ['organizationRef', 'providerRef', 'resourceRef', 'operation'] },
79
+ ExternalSyncConflict: { storage: 'postgres', context: 'external-backends', plural: 'externalsyncconflicts', purpose: 'Detected conflict between local and external state with conflict kind, diff, and resolution outcome', requiredSpec: ['organizationRef', 'providerRef', 'resourceRef', 'conflictKind'] },
80
+ ExternalObjectLink: { storage: 'postgres', context: 'external-backends', plural: 'externalobjectlinks', purpose: 'Stable mapping between a Krate local resource and its external backend counterpart by external ID', requiredSpec: ['organizationRef', 'providerRef', 'externalId', 'localRef'] }
63
81
  });
64
82
 
65
83
  export function listResourceDefinitions() {