@a5c-ai/kradle 5.0.1-staging.3abdf9534c25
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.
- package/Dockerfile +31 -0
- package/README.md +187 -0
- package/bin/kradle-demo.mjs +23 -0
- package/bin/kradle-server.mjs +14 -0
- package/dist/kradle-controller-ui.json +3482 -0
- package/dist/kradle-lifecycle.json +201 -0
- package/dist/kradle-runtime-snapshot.json +3125 -0
- package/dist/kradle-summary.json +724 -0
- package/docs/README.md +61 -0
- package/docs/agents/README.md +83 -0
- package/docs/agents/acceptance-test-matrix.md +193 -0
- package/docs/agents/agent-mux-adapter-contract.md +167 -0
- package/docs/agents/agent-mux-source-map.md +310 -0
- package/docs/agents/agent-run-memory-import-spec.md +256 -0
- package/docs/agents/agent-stack-management-spec.md +421 -0
- package/docs/agents/api-contract-spec.md +309 -0
- package/docs/agents/artifacts-writeback-spec.md +145 -0
- package/docs/agents/chart-packaging-spec.md +128 -0
- package/docs/agents/ci-orchestration-spec.md +140 -0
- package/docs/agents/context-assembly-spec.md +219 -0
- package/docs/agents/controller-reconciliation-spec.md +255 -0
- package/docs/agents/crd-schema-spec.md +315 -0
- package/docs/agents/decision-log-open-questions.md +169 -0
- package/docs/agents/developer-implementation-checklist.md +329 -0
- package/docs/agents/dispatching-design.md +262 -0
- package/docs/agents/gaps-agent-mux-to-kradle-crds.md +298 -0
- package/docs/agents/glossary.md +66 -0
- package/docs/agents/implementation-blueprint.md +324 -0
- package/docs/agents/implementation-rollout-slices.md +251 -0
- package/docs/agents/memory-context-integration-spec.md +194 -0
- package/docs/agents/memory-ontology-schema-spec.md +253 -0
- package/docs/agents/memory-operations-runbook.md +121 -0
- package/docs/agents/mvp-vertical-slice-spec.md +146 -0
- package/docs/agents/observability-audit-spec.md +265 -0
- package/docs/agents/operator-runbook.md +174 -0
- package/docs/agents/org-memory-api-payload-examples.md +333 -0
- package/docs/agents/org-memory-controller-sequence-spec.md +181 -0
- package/docs/agents/org-memory-e2e-fixture-plan.md +161 -0
- package/docs/agents/org-memory-ui-implementation-map.md +114 -0
- package/docs/agents/org-memory-vertical-slice-spec.md +168 -0
- package/docs/agents/org-resource-model-delta-spec.md +111 -0
- package/docs/agents/org-route-resource-model-spec.md +183 -0
- package/docs/agents/org-scoping-namespace-spec.md +114 -0
- package/docs/agents/rbac-secrets-management-spec.md +406 -0
- package/docs/agents/repository-page-integration-spec.md +255 -0
- package/docs/agents/resource-contract-examples.md +808 -0
- package/docs/agents/resource-relationship-map.md +190 -0
- package/docs/agents/security-threat-model.md +188 -0
- package/docs/agents/shared-memory-company-brain-spec.md +358 -0
- package/docs/agents/storage-migration-spec.md +168 -0
- package/docs/agents/subagent-orchestration-spec.md +152 -0
- package/docs/agents/system-overview.md +88 -0
- package/docs/agents/tools-mcp-skills-spec.md +189 -0
- package/docs/agents/traceability-matrix.md +79 -0
- package/docs/agents/ui-flow-spec.md +211 -0
- package/docs/agents/ui-ux-system-spec.md +426 -0
- package/docs/agents/workspace-lifecycle-spec.md +166 -0
- package/docs/architecture-spec.md +78 -0
- package/docs/architecture-v2.md +2759 -0
- package/docs/components/control-plane.md +78 -0
- package/docs/components/data-plane.md +69 -0
- package/docs/components/hooks-events.md +67 -0
- package/docs/components/identity-rbac-policy.md +73 -0
- package/docs/components/kubevela-oam.md +70 -0
- package/docs/components/operations-publishing.md +81 -0
- package/docs/components/runners-ci.md +66 -0
- package/docs/components/web-ui.md +94 -0
- package/docs/crd-behaviors-and-relationships.md +3926 -0
- package/docs/external/README.md +47 -0
- package/docs/external/bidirectional-sync-design.md +134 -0
- package/docs/external/cicd-interface.md +64 -0
- package/docs/external/external-backend-controllers.md +170 -0
- package/docs/external/external-backend-crds.md +234 -0
- package/docs/external/external-backend-ui-spec.md +151 -0
- package/docs/external/external-backend-ux-flows.md +115 -0
- package/docs/external/external-object-mapping.md +125 -0
- package/docs/external/git-forge-interface.md +68 -0
- package/docs/external/github-integration-design.md +151 -0
- package/docs/external/issue-tracking-interface.md +66 -0
- package/docs/external/provider-capability-manifests.md +204 -0
- package/docs/external/provider-catalog.md +139 -0
- package/docs/external/provider-rollout-testing.md +78 -0
- package/docs/external/research-results.md +48 -0
- package/docs/external/security-auth-permissions.md +81 -0
- package/docs/external/sync-state-machines.md +108 -0
- package/docs/external/unified-external-backend-model.md +107 -0
- package/docs/external/user-facing-changes.md +67 -0
- package/docs/gaps.md +161 -0
- package/docs/install.md +94 -0
- package/docs/integration-and-design-decisions.md +1530 -0
- package/docs/kradle-design.md +334 -0
- package/docs/local-minikube.md +55 -0
- package/docs/ontology/README.md +32 -0
- package/docs/ontology/bounded-contexts.md +29 -0
- package/docs/ontology/events-and-hooks.md +32 -0
- package/docs/ontology/oam-kubevela.md +32 -0
- package/docs/ontology/operations-and-release.md +25 -0
- package/docs/ontology/personas-and-actors.md +32 -0
- package/docs/ontology/policies-and-invariants.md +33 -0
- package/docs/ontology/problem-space.md +30 -0
- package/docs/ontology/resource-contracts.md +40 -0
- package/docs/ontology/resource-taxonomy.md +42 -0
- package/docs/ontology/runners-and-ci.md +29 -0
- package/docs/ontology/solution-space.md +24 -0
- package/docs/ontology/storage-and-data-boundaries.md +29 -0
- package/docs/ontology/validation-matrix.md +24 -0
- package/docs/ontology/web-ui-excellent-flows.md +32 -0
- package/docs/ontology/workflows.md +39 -0
- package/docs/ontology/world.md +35 -0
- package/docs/openapi.yaml +1291 -0
- package/docs/product-requirements.md +62 -0
- package/docs/requirements-v2.md +235 -0
- package/docs/roadmap-mvp.md +87 -0
- package/docs/sdk-api-reference.md +1108 -0
- package/docs/system-requirements.md +90 -0
- package/docs/system-spec-v2.md +1230 -0
- package/docs/tests/README.md +53 -0
- package/docs/tests/agent-qa-plan.md +63 -0
- package/docs/tests/browser-ui-tests.md +62 -0
- package/docs/tests/ci-quality-gates.md +48 -0
- package/docs/tests/coverage-model.md +64 -0
- package/docs/tests/e2e-scenario-tests.md +53 -0
- package/docs/tests/fixtures-test-data.md +63 -0
- package/docs/tests/observability-reliability-tests.md +54 -0
- package/docs/tests/product-test-matrix.md +145 -0
- package/docs/tests/qa-adoption-roadmap.md +130 -0
- package/docs/tests/qa-automation-plan.md +101 -0
- package/docs/tests/security-compliance-tests.md +57 -0
- package/docs/tests/test-framework-tools.md +88 -0
- package/docs/tests/test-suite-layout.md +121 -0
- package/docs/tests/unit-integration-tests.md +48 -0
- package/docs/todo-kyverno +714 -0
- package/docs/todos.md +4 -0
- package/docs/user-stories.md +78 -0
- package/docs/web-console-spec.md +533 -0
- package/examples/minikube-demo.yaml +190 -0
- package/examples/oam-application.yaml +23 -0
- package/examples/policy-kyverno-pr-title.yaml +18 -0
- package/package.json +66 -0
- package/scripts/build.mjs +29 -0
- package/scripts/setup-minikube.mjs +65 -0
- package/scripts/smoke.mjs +37 -0
- package/scripts/validate-doc-coverage.mjs +152 -0
- package/scripts/validate-package.mjs +95 -0
- package/scripts/validate-ui.mjs +305 -0
- package/src/agent-adapter-controller.js +169 -0
- package/src/agent-approval-controller.js +170 -0
- package/src/agent-context-bundles.js +242 -0
- package/src/agent-dispatch-controller.js +549 -0
- package/src/agent-gateway-config-controller.js +147 -0
- package/src/agent-identity-migration.js +115 -0
- package/src/agent-memory-controller.js +357 -0
- package/src/agent-memory-import.js +327 -0
- package/src/agent-memory-query.js +292 -0
- package/src/agent-memory-repository-source-controller.js +255 -0
- package/src/agent-mux-client.js +589 -0
- package/src/agent-permission-review.js +250 -0
- package/src/agent-persona-controller.js +135 -0
- package/src/agent-project-controller.js +117 -0
- package/src/agent-prompt-composition.js +55 -0
- package/src/agent-provider-config-controller.js +151 -0
- package/src/agent-secret-config-grant-controller.js +282 -0
- package/src/agent-session-transcript-controller.js +189 -0
- package/src/agent-stack-controller.js +421 -0
- package/src/agent-subagent-controller.js +160 -0
- package/src/agent-transport-binding-controller.js +121 -0
- package/src/agent-trigger-controller.js +387 -0
- package/src/agent-workspace-controller.js +702 -0
- package/src/agent-writeback-controller.js +302 -0
- package/src/api-controller.js +621 -0
- package/src/argocd-gitops.js +43 -0
- package/src/artifact-registry-controller.js +542 -0
- package/src/assistant-runtime.js +284 -0
- package/src/async-controller.js +207 -0
- package/src/audit-controller.js +191 -0
- package/src/auth.js +310 -0
- package/src/component-catalog.js +41 -0
- package/src/control-plane.js +136 -0
- package/src/controller-client.js +112 -0
- package/src/controller-ui.js +620 -0
- package/src/data-plane.js +179 -0
- package/src/event-bus.js +397 -0
- package/src/external/conflict-controller.js +225 -0
- package/src/external/github/auth.js +96 -0
- package/src/external/github/cicd.js +180 -0
- package/src/external/github/git-forge.js +240 -0
- package/src/external/github/index.js +144 -0
- package/src/external/github/issue-tracking.js +163 -0
- package/src/external/provider-adapter.js +161 -0
- package/src/external/provider-resource-factory.js +221 -0
- package/src/external/sync-controller.js +235 -0
- package/src/external/webhook-controller.js +144 -0
- package/src/external/write-controller.js +283 -0
- package/src/gitea-backend.js +131 -0
- package/src/gitea-service.js +173 -0
- package/src/handoff.js +98 -0
- package/src/health-probes.js +134 -0
- package/src/hooks-events.js +63 -0
- package/src/hooks-lifecycle.js +117 -0
- package/src/http-server.js +409 -0
- package/src/identity-policy.js +86 -0
- package/src/index.js +71 -0
- package/src/jitsi-agent-bridge.js +141 -0
- package/src/jitsi-meeting-controller.js +291 -0
- package/src/jitsi-sync-controller.js +198 -0
- package/src/kradle-inference-service-controller.js +246 -0
- package/src/kubernetes-controller-async.js +531 -0
- package/src/kubernetes-controller.js +904 -0
- package/src/kubernetes-resource-gateway.js +48 -0
- package/src/model-route-controller.js +364 -0
- package/src/notification-controller.js +178 -0
- package/src/operations.js +112 -0
- package/src/org-scoping.js +5 -0
- package/src/resource-model.js +282 -0
- package/src/runner-controller.js +272 -0
- package/src/runners-ci.js +48 -0
- package/src/runtime.js +196 -0
- package/src/snapshot-cache.js +157 -0
- package/src/virtual-model-controller.js +538 -0
- package/src/virtual-model-hook-bridge.js +200 -0
- package/src/web-ui.js +40 -0
- package/tests/agent-adapter-controller.test.js +361 -0
- package/tests/agent-approval-controller.test.js +173 -0
- package/tests/agent-context-bundles.test.js +278 -0
- package/tests/agent-dispatch-controller.test.js +679 -0
- package/tests/agent-gateway-config-controller.test.js +386 -0
- package/tests/agent-identity-migration.test.js +87 -0
- package/tests/agent-memory-controller.test.js +461 -0
- package/tests/agent-memory-import-snapshot.test.js +477 -0
- package/tests/agent-memory-query.test.js +404 -0
- package/tests/agent-memory-repository-source.test.js +514 -0
- package/tests/agent-mux-client.test.js +389 -0
- package/tests/agent-mux-integration.test.js +971 -0
- package/tests/agent-permission-review-v2.test.js +317 -0
- package/tests/agent-permission-review.test.js +209 -0
- package/tests/agent-persona-controller.test.js +127 -0
- package/tests/agent-project-controller.test.js +302 -0
- package/tests/agent-prompt-composition.test.js +76 -0
- package/tests/agent-provider-config-controller.test.js +376 -0
- package/tests/agent-resources.test.js +303 -0
- package/tests/agent-secret-config-grant.test.js +231 -0
- package/tests/agent-session-transcript-controller.test.js +499 -0
- package/tests/agent-stack-controller.test.js +283 -0
- package/tests/agent-subagent-controller.test.js +201 -0
- package/tests/agent-transport-binding-controller.test.js +294 -0
- package/tests/agent-trigger-controller.test.js +271 -0
- package/tests/agent-trigger-routes.test.js +190 -0
- package/tests/agent-trigger-sources.test.js +245 -0
- package/tests/agent-workspace-controller.test.js +181 -0
- package/tests/agent-writeback.test.js +292 -0
- package/tests/approval-persistence.test.js +171 -0
- package/tests/artifact-registry.test.js +511 -0
- package/tests/assistant-runtime.test.js +506 -0
- package/tests/async-controller.test.js +252 -0
- package/tests/audit-controller.test.js +227 -0
- package/tests/codespace-controller.test.js +318 -0
- package/tests/controller-client.test.js +133 -0
- package/tests/deployment.test.js +527 -0
- package/tests/e2e/lifecycle.test.js +120 -0
- package/tests/event-bus-integration.test.js +355 -0
- package/tests/external-github-forge.test.js +560 -0
- package/tests/external-github-issues-cicd.test.js +520 -0
- package/tests/external-integration.test.js +470 -0
- package/tests/external-persistence.test.js +415 -0
- package/tests/external-provider-adapter.test.js +365 -0
- package/tests/external-resource-model.test.js +223 -0
- package/tests/external-webhook-sync.test.js +287 -0
- package/tests/external-write-conflict.test.js +353 -0
- package/tests/gitea-service.test.js +253 -0
- package/tests/health-check-real.test.js +165 -0
- package/tests/health-probes.test.js +90 -0
- package/tests/hooks-lifecycle.test.js +364 -0
- package/tests/integration/full-flow.test.js +266 -0
- package/tests/jitsi-agent-bridge.test.js +119 -0
- package/tests/jitsi-helm-integration.test.js +77 -0
- package/tests/jitsi-meeting-controller.test.js +170 -0
- package/tests/jitsi-resource-model.test.js +73 -0
- package/tests/jitsi-sync-controller.test.js +112 -0
- package/tests/kradle-inference-service.test.js +689 -0
- package/tests/kradle.test.js +779 -0
- package/tests/memory-search-wiring.test.js +270 -0
- package/tests/model-route-controller.test.js +733 -0
- package/tests/notification-controller.test.js +196 -0
- package/tests/notification-integration.test.js +179 -0
- package/tests/org-scoping.test.js +687 -0
- package/tests/runner-controller.test.js +327 -0
- package/tests/runner-integration.test.js +231 -0
- package/tests/session-cookie-hmac.test.js +151 -0
- package/tests/snapshot-performance.test.js +315 -0
- package/tests/sse-events.test.js +107 -0
- package/tests/virtual-model-controller.test.js +877 -0
- package/tests/virtual-model-hook-bridge.test.js +384 -0
- package/tests/webhook-trigger.test.js +198 -0
- package/tests/workspace-volumes.test.js +312 -0
- package/tests/writeback-persistence.test.js +207 -0
|
@@ -0,0 +1,904 @@
|
|
|
1
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
2
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
3
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
4
|
+
|
|
5
|
+
export const KRADLE_API_GROUP = 'kradle.a5c.ai';
|
|
6
|
+
export const KRADLE_API_VERSION = 'v1alpha1';
|
|
7
|
+
export const KRADLE_API_VERSIONED_GROUP = `${KRADLE_API_VERSION}.${KRADLE_API_GROUP}`;
|
|
8
|
+
export const KUBEVELA_API_GROUP = 'core.oam.dev';
|
|
9
|
+
export const KYVERNO_API_GROUP = 'kyverno.io';
|
|
10
|
+
export const KYVERNO_POLICIES_API_GROUP = 'policies.kyverno.io';
|
|
11
|
+
export const POLICY_REPORT_API_GROUP = 'wgpolicyk8s.io';
|
|
12
|
+
export const KRADLE_ORG_LABEL = 'kradle.a5c.ai/org';
|
|
13
|
+
export const KRADLE_ORG_NAMESPACE_LABEL = 'kradle.a5c.ai/namespace';
|
|
14
|
+
export const KRADLE_PLATFORM_NAMESPACE = process.env.KRADLE_NAMESPACE || 'kradle-system';
|
|
15
|
+
|
|
16
|
+
export const KUBERNETES_RESOURCE_CLIENT_BOUNDARY = {
|
|
17
|
+
role: 'kubernetes-resource-client',
|
|
18
|
+
scope: 'workspace API discovery, delegated access checks, list/get/apply/delete/watch, and command normalization',
|
|
19
|
+
owns: ['workspace command execution', 'Kradle API resource discovery', 'delegated access checks', 'workspace watch streams'],
|
|
20
|
+
mustNotOwn: ['HTTP route orchestration', 'Next.js page flows', 'forge DTO composition', 'business workflow decisions']
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
export const KRADLE_KUBERNETES_RECONCILER_BOUNDARY = {
|
|
24
|
+
role: 'kradle-kubernetes-reconciler',
|
|
25
|
+
scope: 'reconcile Kubernetes-style Kradle resources into status, repository hosting intent, policy projection, and data-plane sync intent',
|
|
26
|
+
owns: ['Repository status projection', 'identity and access status projection', 'repository hosting intent', 'policy sync intent', 'degraded condition reporting'],
|
|
27
|
+
delegatesTo: ['kubernetes-resource-gateway', 'git-data-plane'],
|
|
28
|
+
mustNotOwn: ['HTTP routes', 'web page navigation', 'API DTO shaping', 'browser form behavior']
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
export const KRADLE_RESOURCES = [
|
|
32
|
+
{ kind: 'Organization', plural: 'organizations', namespaced: true, namespace: KRADLE_PLATFORM_NAMESPACE, storage: 'etcd', platformScoped: true },
|
|
33
|
+
{ kind: 'OrgNamespaceBinding', plural: 'orgnamespacebindings', namespaced: true, namespace: KRADLE_PLATFORM_NAMESPACE, storage: 'etcd', platformScoped: true },
|
|
34
|
+
{ kind: 'User', plural: 'users', namespaced: true, storage: 'etcd' },
|
|
35
|
+
{ kind: 'Team', plural: 'teams', namespaced: true, storage: 'etcd' },
|
|
36
|
+
{ kind: 'Invite', plural: 'invites', namespaced: true, storage: 'etcd' },
|
|
37
|
+
{ kind: 'IdentityMapping', plural: 'identitymappings', namespaced: true, storage: 'etcd' },
|
|
38
|
+
{ kind: 'AuthProvider', plural: 'authproviders', namespaced: true, storage: 'etcd' },
|
|
39
|
+
{ kind: 'Repository', plural: 'repositories', namespaced: true, storage: 'etcd' },
|
|
40
|
+
{ kind: 'SSHKey', plural: 'sshkeys', namespaced: true, storage: 'etcd' },
|
|
41
|
+
{ kind: 'RepositoryPermission', plural: 'repositorypermissions', namespaced: true, storage: 'etcd' },
|
|
42
|
+
{ kind: 'BranchProtection', plural: 'branchprotections', namespaced: true, storage: 'etcd' },
|
|
43
|
+
{ kind: 'RefPolicy', plural: 'refpolicies', namespaced: true, storage: 'etcd' },
|
|
44
|
+
{ kind: 'PolicyProfile', plural: 'policyprofiles', namespaced: true, storage: 'etcd' },
|
|
45
|
+
{ kind: 'PolicyTemplate', plural: 'policytemplates', namespaced: true, storage: 'etcd' },
|
|
46
|
+
{ kind: 'PolicyBinding', plural: 'policybindings', namespaced: true, storage: 'etcd' },
|
|
47
|
+
{ kind: 'PolicyExceptionRequest', plural: 'policyexceptionrequests', namespaced: true, storage: 'etcd' },
|
|
48
|
+
{ kind: 'WebhookSubscription', plural: 'webhooksubscriptions', namespaced: true, storage: 'etcd' },
|
|
49
|
+
{ kind: 'RunnerPool', plural: 'runnerpools', namespaced: true, storage: 'etcd' },
|
|
50
|
+
{ kind: 'PullRequest', plural: 'pullrequests', namespaced: true, storage: 'postgres' },
|
|
51
|
+
{ kind: 'Issue', plural: 'issues', namespaced: true, storage: 'postgres' },
|
|
52
|
+
{ kind: 'Review', plural: 'reviews', namespaced: true, storage: 'postgres' },
|
|
53
|
+
{ kind: 'Pipeline', plural: 'pipelines', namespaced: true, storage: 'postgres' },
|
|
54
|
+
{ kind: 'Job', plural: 'jobs', namespaced: true, storage: 'postgres' },
|
|
55
|
+
{ kind: 'WebhookDelivery', plural: 'webhookdeliveries', namespaced: true, storage: 'postgres' },
|
|
56
|
+
{ kind: 'KubeVelaApplication', plural: 'applications', group: KUBEVELA_API_GROUP, namespaced: true, storage: 'kubevela' },
|
|
57
|
+
{ kind: 'KubeVelaApplicationRevision', plural: 'applicationrevisions', group: KUBEVELA_API_GROUP, namespaced: true, storage: 'kubevela' },
|
|
58
|
+
{ kind: 'KubeVelaComponentDefinition', plural: 'componentdefinitions', group: KUBEVELA_API_GROUP, namespaced: true, namespace: process.env.KRADLE_KUBEVELA_NAMESPACE || 'vela-system', storage: 'kubevela' },
|
|
59
|
+
{ kind: 'KubeVelaWorkloadDefinition', plural: 'workloaddefinitions', group: KUBEVELA_API_GROUP, namespaced: true, namespace: process.env.KRADLE_KUBEVELA_NAMESPACE || 'vela-system', storage: 'kubevela' },
|
|
60
|
+
{ kind: 'KubeVelaTraitDefinition', plural: 'traitdefinitions', group: KUBEVELA_API_GROUP, namespaced: true, namespace: process.env.KRADLE_KUBEVELA_NAMESPACE || 'vela-system', storage: 'kubevela' },
|
|
61
|
+
{ kind: 'KubeVelaScopeDefinition', plural: 'scopedefinitions', group: KUBEVELA_API_GROUP, namespaced: true, namespace: process.env.KRADLE_KUBEVELA_NAMESPACE || 'vela-system', storage: 'kubevela' },
|
|
62
|
+
{ kind: 'KubeVelaPolicyDefinition', plural: 'policydefinitions', group: KUBEVELA_API_GROUP, namespaced: true, namespace: process.env.KRADLE_KUBEVELA_NAMESPACE || 'vela-system', storage: 'kubevela' },
|
|
63
|
+
{ kind: 'KubeVelaPolicy', plural: 'policies', group: KUBEVELA_API_GROUP, namespaced: true, storage: 'kubevela' },
|
|
64
|
+
{ kind: 'KubeVelaWorkflowStepDefinition', plural: 'workflowstepdefinitions', group: KUBEVELA_API_GROUP, namespaced: true, namespace: process.env.KRADLE_KUBEVELA_NAMESPACE || 'vela-system', storage: 'kubevela' },
|
|
65
|
+
{ kind: 'KubeVelaWorkflow', plural: 'workflows', group: KUBEVELA_API_GROUP, namespaced: true, storage: 'kubevela' },
|
|
66
|
+
{ kind: 'KubeVelaResourceTracker', plural: 'resourcetrackers', group: KUBEVELA_API_GROUP, namespaced: false, storage: 'kubevela' },
|
|
67
|
+
{ kind: 'View', plural: 'views', namespaced: true, storage: 'etcd' },
|
|
68
|
+
{ kind: 'Selector', plural: 'selectors', namespaced: true, storage: 'etcd' },
|
|
69
|
+
// Agent orchestration CRDs (etcd-stored, kradle.a5c.ai group)
|
|
70
|
+
{ kind: 'AgentPersona', plural: 'agentpersonas', namespaced: true, storage: 'etcd' },
|
|
71
|
+
{ kind: 'AgentSoul', plural: 'agentsouls', namespaced: true, storage: 'etcd' },
|
|
72
|
+
{ kind: 'AgentAppearance', plural: 'agentappearances', namespaced: true, storage: 'etcd' },
|
|
73
|
+
{ kind: 'AgentVoiceProfile', plural: 'agentvoiceprofiles', namespaced: true, storage: 'etcd' },
|
|
74
|
+
{ kind: 'AgentDefinition', plural: 'agentdefinitions', namespaced: true, storage: 'etcd' },
|
|
75
|
+
{ kind: 'AgentStack', plural: 'agentstacks', namespaced: true, storage: 'etcd' },
|
|
76
|
+
{ kind: 'AgentSubagent', plural: 'agentsubagents', namespaced: true, storage: 'etcd' },
|
|
77
|
+
{ kind: 'AgentToolProfile', plural: 'agenttoolprofiles', namespaced: true, storage: 'etcd' },
|
|
78
|
+
{ kind: 'AgentMcpServer', plural: 'agentmcpservers', namespaced: true, storage: 'etcd' },
|
|
79
|
+
{ kind: 'AgentSkill', plural: 'agentskills', namespaced: true, storage: 'etcd' },
|
|
80
|
+
{ kind: 'AgentTriggerRule', plural: 'agenttriggerrules', namespaced: true, storage: 'etcd' },
|
|
81
|
+
{ kind: 'AgentContextLabel', plural: 'agentcontextlabels', namespaced: true, storage: 'etcd' },
|
|
82
|
+
{ kind: 'KradleWorkspacePolicy', plural: 'kradleworkspacepolicies', namespaced: true, storage: 'etcd' },
|
|
83
|
+
{ kind: 'AgentServiceAccount', plural: 'agentserviceaccounts', namespaced: true, storage: 'etcd' },
|
|
84
|
+
{ kind: 'AgentRoleBinding', plural: 'agentrolebindings', namespaced: true, storage: 'etcd' },
|
|
85
|
+
{ kind: 'AgentSecretGrant', plural: 'agentsecretgrants', namespaced: true, storage: 'etcd' },
|
|
86
|
+
{ kind: 'AgentConfigGrant', plural: 'agentconfiggrants', namespaced: true, storage: 'etcd' },
|
|
87
|
+
{ kind: 'AgentAdapter', plural: 'agentadapters', namespaced: true, storage: 'etcd' },
|
|
88
|
+
{ kind: 'AgentTransportBinding', plural: 'agenttransportbindings', namespaced: true, storage: 'etcd' },
|
|
89
|
+
{ kind: 'AgentProviderConfig', plural: 'agentproviderconfigs', namespaced: true, storage: 'etcd' },
|
|
90
|
+
{ kind: 'KradleProject', plural: 'kradleprojects', namespaced: true, storage: 'etcd' },
|
|
91
|
+
{ kind: 'AgentGatewayConfig', plural: 'agentgatewayconfigs', namespaced: true, storage: 'etcd' },
|
|
92
|
+
{ kind: 'AgentMemoryRepository', plural: 'agentmemoryrepositories', namespaced: true, storage: 'etcd' },
|
|
93
|
+
{ kind: 'AgentMemorySource', plural: 'agentmemorysources', namespaced: true, storage: 'etcd' },
|
|
94
|
+
{ kind: 'AgentMemoryOntology', plural: 'agentmemoryontologies', namespaced: true, storage: 'etcd' },
|
|
95
|
+
{ kind: 'AgentMemoryAssociation', plural: 'agentmemoryassociations', namespaced: true, storage: 'etcd' },
|
|
96
|
+
// Aggregated agent resources (postgres-stored, accessed via snapshot but need discovery)
|
|
97
|
+
{ kind: 'AgentDispatchRun', plural: 'agentdispatchruns', namespaced: true, storage: 'postgres' },
|
|
98
|
+
{ kind: 'AgentDispatchAttempt', plural: 'agentdispatchattempts', namespaced: true, storage: 'postgres' },
|
|
99
|
+
{ kind: 'AgentSession', plural: 'agentsessions', namespaced: true, storage: 'postgres' },
|
|
100
|
+
{ kind: 'AgentContextBundle', plural: 'agentcontextbundles', namespaced: true, storage: 'postgres' },
|
|
101
|
+
{ kind: 'KradleArtifact', plural: 'kradleartifacts', namespaced: true, storage: 'postgres' },
|
|
102
|
+
{ kind: 'AgentApproval', plural: 'agentapprovals', namespaced: true, storage: 'postgres' },
|
|
103
|
+
{ kind: 'KradleWorkspace', plural: 'kradleworkspaces', namespaced: true, storage: 'postgres' },
|
|
104
|
+
{ kind: 'AgentTriggerExecution', plural: 'agenttriggerexecutions', namespaced: true, storage: 'postgres' },
|
|
105
|
+
{ kind: 'KradleWorkspaceRuntime', plural: 'kradleworkspaceruntimes', namespaced: true, storage: 'postgres' },
|
|
106
|
+
{ kind: 'AgentSessionTranscript', plural: 'agentsessiontranscripts', namespaced: true, storage: 'postgres' },
|
|
107
|
+
// External backend resources (etcd-stored)
|
|
108
|
+
{ kind: 'ExternalBackendProvider', plural: 'externalbackendproviders', namespaced: true, storage: 'etcd' },
|
|
109
|
+
{ kind: 'ExternalBackendBinding', plural: 'externalbackendbindings', namespaced: true, storage: 'etcd' },
|
|
110
|
+
{ kind: 'ExternalBackendSyncPolicy', plural: 'externalbackendsyncpolicies', namespaced: true, storage: 'etcd' },
|
|
111
|
+
// Artifact registry resources (etcd-stored)
|
|
112
|
+
{ kind: 'ArtifactRegistry', plural: 'artifactregistries', namespaced: true, storage: 'etcd' },
|
|
113
|
+
{ kind: 'ArtifactFeed', plural: 'artifactfeeds', namespaced: true, storage: 'etcd' },
|
|
114
|
+
{ kind: 'ArtifactAccessPolicy', plural: 'artifactaccesspolicies', namespaced: true, storage: 'etcd' },
|
|
115
|
+
// Artifact registry resources (postgres-stored)
|
|
116
|
+
{ kind: 'ArtifactVersion', plural: 'artifactversions', namespaced: true, storage: 'postgres' },
|
|
117
|
+
{ kind: 'ArtifactDownload', plural: 'artifactdownloads', namespaced: true, storage: 'postgres' },
|
|
118
|
+
// Inference resources (etcd-stored, kradle.a5c.ai group)
|
|
119
|
+
{ kind: 'KradleInferenceService', plural: 'kradleinferenceservices', namespaced: true, storage: 'etcd' },
|
|
120
|
+
{ kind: 'KradleServingRuntime', plural: 'kradleservingruntimes', namespaced: true, storage: 'etcd' },
|
|
121
|
+
// Jitsi resources
|
|
122
|
+
{ kind: 'JitsiMeetProvider', plural: 'jitsimeetproviders', namespaced: true, storage: 'etcd' },
|
|
123
|
+
{ kind: 'JitsiMeetingTemplate', plural: 'jitsimeetingtemplates', namespaced: true, storage: 'etcd' },
|
|
124
|
+
{ kind: 'JitsiMeeting', plural: 'jitsimeetings', namespaced: true, storage: 'postgres' },
|
|
125
|
+
{ kind: 'JitsiRecording', plural: 'jitsirecordings', namespaced: true, storage: 'postgres' },
|
|
126
|
+
// Core Kubernetes resources (group: '' — no API group prefix for kubectl).
|
|
127
|
+
// These are excluded from snapshot discovery (storage: 'core') but are
|
|
128
|
+
// available for list/get/delete via findResourceDefinition.
|
|
129
|
+
{ kind: 'Secret', plural: 'secrets', group: '', namespaced: true, storage: 'core' },
|
|
130
|
+
{ kind: 'ConfigMap', plural: 'configmaps', group: '', namespaced: true, storage: 'core' }
|
|
131
|
+
];
|
|
132
|
+
|
|
133
|
+
export const KYVERNO_RESOURCES = [
|
|
134
|
+
{ kind: 'KyvernoPolicy', plural: 'policies', group: KYVERNO_API_GROUP, namespaced: true, storage: 'kyverno', namespace: process.env.KRADLE_KYVERNO_POLICY_NAMESPACE || process.env.KRADLE_NAMESPACE || 'kradle-system' },
|
|
135
|
+
{ kind: 'KyvernoClusterPolicy', plural: 'clusterpolicies', group: KYVERNO_API_GROUP, namespaced: false, storage: 'kyverno' },
|
|
136
|
+
{ kind: 'KyvernoValidatingPolicy', plural: 'validatingpolicies', group: KYVERNO_POLICIES_API_GROUP, namespaced: false, storage: 'kyverno' },
|
|
137
|
+
{ kind: 'KyvernoMutatingPolicy', plural: 'mutatingpolicies', group: KYVERNO_POLICIES_API_GROUP, namespaced: false, storage: 'kyverno' },
|
|
138
|
+
{ kind: 'KyvernoGeneratingPolicy', plural: 'generatingpolicies', group: KYVERNO_POLICIES_API_GROUP, namespaced: false, storage: 'kyverno' },
|
|
139
|
+
{ kind: 'KyvernoDeletingPolicy', plural: 'deletingpolicies', group: KYVERNO_POLICIES_API_GROUP, namespaced: false, storage: 'kyverno' },
|
|
140
|
+
{ kind: 'KyvernoImageValidatingPolicy', plural: 'imagevalidatingpolicies', group: KYVERNO_POLICIES_API_GROUP, namespaced: false, storage: 'kyverno' },
|
|
141
|
+
{ kind: 'KyvernoPolicyException', plural: 'policyexceptions', group: KYVERNO_POLICIES_API_GROUP, namespaced: true, storage: 'kyverno', namespace: process.env.KRADLE_KYVERNO_POLICY_NAMESPACE || process.env.KRADLE_NAMESPACE || 'kradle-system' },
|
|
142
|
+
{ kind: 'PolicyReport', plural: 'policyreports', group: POLICY_REPORT_API_GROUP, namespaced: true, storage: 'kyverno-reports' },
|
|
143
|
+
{ kind: 'ClusterPolicyReport', plural: 'clusterpolicyreports', group: POLICY_REPORT_API_GROUP, namespaced: false, storage: 'kyverno-reports' }
|
|
144
|
+
];
|
|
145
|
+
|
|
146
|
+
const KYVERNO_DISCOVERY_GROUPS = new Set([KYVERNO_API_GROUP, KYVERNO_POLICIES_API_GROUP, POLICY_REPORT_API_GROUP]);
|
|
147
|
+
|
|
148
|
+
export function createKubernetesResourceClient(options = {}) {
|
|
149
|
+
const kubectl = options.kubectl || process.env.KRADLE_KUBECTL || 'kubectl';
|
|
150
|
+
const namespace = options.namespace || process.env.KRADLE_NAMESPACE || 'kradle-system';
|
|
151
|
+
const timeoutMs = Number(options.timeoutMs || process.env.KRADLE_KUBECTL_TIMEOUT_MS || 3_000);
|
|
152
|
+
const env = { ...process.env, ...(options.env || {}) };
|
|
153
|
+
|
|
154
|
+
return {
|
|
155
|
+
...KUBERNETES_RESOURCE_CLIENT_BOUNDARY,
|
|
156
|
+
namespace,
|
|
157
|
+
kubectl,
|
|
158
|
+
resourceDefinitions: KRADLE_RESOURCES,
|
|
159
|
+
async snapshot() {
|
|
160
|
+
return getControllerSnapshot({ kubectl, namespace, timeoutMs, env });
|
|
161
|
+
},
|
|
162
|
+
async listResource(kindOrPlural) {
|
|
163
|
+
return listResource(kindOrPlural, { kubectl, namespace, timeoutMs, env });
|
|
164
|
+
},
|
|
165
|
+
async getResource(kindOrPlural, name) {
|
|
166
|
+
return getResource(kindOrPlural, name, { kubectl, namespace, timeoutMs, env });
|
|
167
|
+
},
|
|
168
|
+
async applyResource(resource) {
|
|
169
|
+
return applyResource(resource, { kubectl, namespace, timeoutMs, env });
|
|
170
|
+
},
|
|
171
|
+
async deleteResource(kindOrPlural, name) {
|
|
172
|
+
return deleteResource(kindOrPlural, name, { kubectl, namespace, timeoutMs, env });
|
|
173
|
+
},
|
|
174
|
+
async createRepository(input) {
|
|
175
|
+
return applyResource(repositoryManifest(input, namespace), { kubectl, namespace, timeoutMs, env });
|
|
176
|
+
},
|
|
177
|
+
async createOrganization(input) {
|
|
178
|
+
return createOrganization(input, { kubectl, namespace, timeoutMs, env });
|
|
179
|
+
},
|
|
180
|
+
watchResource(resourcePath, handlers = {}) {
|
|
181
|
+
return watchResource(resourcePath, { kubectl, namespace, env }, handlers);
|
|
182
|
+
}
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
export function createKubernetesController(options = {}) {
|
|
187
|
+
return createKubernetesResourceClient(options);
|
|
188
|
+
}
|
|
189
|
+
export function createKradleKubernetesReconciler(options = {}) {
|
|
190
|
+
const namespace = options.namespace || process.env.KRADLE_NAMESPACE || 'kradle-system';
|
|
191
|
+
return {
|
|
192
|
+
...KRADLE_KUBERNETES_RECONCILER_BOUNDARY,
|
|
193
|
+
namespace,
|
|
194
|
+
describeReconciliationScope() {
|
|
195
|
+
return {
|
|
196
|
+
...KRADLE_KUBERNETES_RECONCILER_BOUNDARY,
|
|
197
|
+
namespace,
|
|
198
|
+
resources: KRADLE_RESOURCES.map(({ kind, plural, storage }) => ({ kind, plural, storage }))
|
|
199
|
+
};
|
|
200
|
+
},
|
|
201
|
+
reconcileRepository(resource = {}) {
|
|
202
|
+
const name = resource.metadata?.name || 'unknown-repository';
|
|
203
|
+
return {
|
|
204
|
+
kind: 'RepositoryReconciliationPlan',
|
|
205
|
+
namespace: resource.metadata?.namespace || namespace,
|
|
206
|
+
name,
|
|
207
|
+
desiredStatus: {
|
|
208
|
+
phase: resource.status?.phase || 'Reconciling',
|
|
209
|
+
gitBackend: resource.status?.gitBackend || 'gitea',
|
|
210
|
+
conditions: [
|
|
211
|
+
{ type: 'ResourceObserved', status: 'True', reason: 'KubernetesResourceWatch' },
|
|
212
|
+
{ type: 'DataPlaneSyncPlanned', status: 'True', reason: 'RepositoryBackendProjection' }
|
|
213
|
+
]
|
|
214
|
+
},
|
|
215
|
+
syncIntents: [
|
|
216
|
+
{ target: 'git-data-plane', action: 'ensure-gitea-repository', repository: name },
|
|
217
|
+
{ target: 'policy-controller', action: 'compile-ref-policy', repository: name }
|
|
218
|
+
]
|
|
219
|
+
};
|
|
220
|
+
},
|
|
221
|
+
reconcileIdentityAccess(resource = {}, context = {}) {
|
|
222
|
+
return identityAccessReconciliationPlan(resource, { namespace, ...context });
|
|
223
|
+
},
|
|
224
|
+
reconcileIdentityAccessResources(resources = {}, context = {}) {
|
|
225
|
+
const items = ['User', 'Team', 'Invite', 'IdentityMapping', 'RepositoryPermission', 'SSHKey']
|
|
226
|
+
.flatMap((kind) => (resources[kind] || []).map((resource) => identityAccessReconciliationPlan(resource, { namespace, ...context })));
|
|
227
|
+
return {
|
|
228
|
+
kind: 'IdentityAccessReconciliationPlan',
|
|
229
|
+
namespace,
|
|
230
|
+
desiredStatuses: items.map(({ kind, name, desiredStatus }) => ({ kind, name, phase: desiredStatus.phase, conditions: desiredStatus.conditions })),
|
|
231
|
+
syncIntents: items.flatMap((item) => item.syncIntents),
|
|
232
|
+
counts: items.reduce((counts, item) => ({ ...counts, [item.kind]: (counts[item.kind] || 0) + 1 }), {})
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
export function identityAccessReconciliationPlan(resource = {}, options = {}) {
|
|
238
|
+
const kind = resource.kind || 'Unknown';
|
|
239
|
+
const name = resource.metadata?.name || `unknown-${kind.toLowerCase()}`;
|
|
240
|
+
const namespace = resource.metadata?.namespace || options.namespace || process.env.KRADLE_NAMESPACE || 'kradle-system';
|
|
241
|
+
const spec = resource.spec || {};
|
|
242
|
+
const baseCondition = { type: `${kind}Observed`, status: 'True', reason: 'KradleResourceWatch' };
|
|
243
|
+
const base = {
|
|
244
|
+
kind,
|
|
245
|
+
namespace,
|
|
246
|
+
name,
|
|
247
|
+
desiredStatus: { phase: resource.status?.phase || 'Reconciling', conditions: [baseCondition] },
|
|
248
|
+
syncIntents: []
|
|
249
|
+
};
|
|
250
|
+
if (kind === 'User') {
|
|
251
|
+
const disabled = Boolean(spec.disabled);
|
|
252
|
+
return {
|
|
253
|
+
...base,
|
|
254
|
+
desiredStatus: {
|
|
255
|
+
phase: disabled ? 'Disabled' : 'Active',
|
|
256
|
+
repositoryIdentity: spec.username || name,
|
|
257
|
+
groups: ['kradle:users', spec.admin ? 'kradle:platform-engineers' : 'kradle:developers', ...(spec.teams || []).map((team) => `team:${team}`)],
|
|
258
|
+
conditions: [baseCondition, { type: 'WorkspaceIdentityProjected', status: 'True', reason: disabled ? 'UserDisabled' : 'UserActive' }, { type: 'RepositoryIdentityProjected', status: disabled ? 'False' : 'True', reason: disabled ? 'RepositoryAccessSuspended' : 'RepositoryAccountPlanned' }]
|
|
259
|
+
},
|
|
260
|
+
syncIntents: [
|
|
261
|
+
{ target: 'workspace-identity', action: disabled ? 'suspend-user' : 'ensure-user', user: name },
|
|
262
|
+
{ target: 'repository-access', action: disabled ? 'suspend-repository-user' : 'ensure-repository-user', user: name, repositoryIdentity: spec.username || name }
|
|
263
|
+
]
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
if (kind === 'Team') {
|
|
267
|
+
return {
|
|
268
|
+
...base,
|
|
269
|
+
desiredStatus: { phase: 'Active', memberCount: (spec.members || []).length, maintainerCount: (spec.maintainers || []).length, conditions: [baseCondition, { type: 'TeamMembershipProjected', status: 'True', reason: 'MembersAndMaintainersPlanned' }, { type: 'RepositoryGrantsProjected', status: 'True', reason: 'TeamGrantProjectionPlanned' }] },
|
|
270
|
+
syncIntents: [
|
|
271
|
+
{ target: 'workspace-identity', action: 'sync-team-membership', team: name, members: spec.members || [], maintainers: spec.maintainers || [] },
|
|
272
|
+
...(spec.repositoryGrants || []).map((grant) => ({ target: 'repository-access', action: 'sync-team-repository-grant', team: name, repository: grant.repository, permission: grant.permission }))
|
|
273
|
+
]
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
if (kind === 'Invite') {
|
|
277
|
+
const phase = resource.status?.phase || 'Pending';
|
|
278
|
+
return {
|
|
279
|
+
...base,
|
|
280
|
+
desiredStatus: { phase, expiresAt: spec.expiresAt || '', conditions: [baseCondition, { type: 'InviteLifecycleTracked', status: 'True', reason: phase === 'Pending' ? 'InvitePending' : `Invite${phase}` }] },
|
|
281
|
+
syncIntents: [{ target: 'workspace-identity', action: phase === 'Pending' ? 'send-invite' : 'close-invite', invite: name, email: spec.email, phase }]
|
|
282
|
+
};
|
|
283
|
+
}
|
|
284
|
+
if (kind === 'IdentityMapping') {
|
|
285
|
+
const complete = Boolean(spec.user && spec.provider && spec.subject);
|
|
286
|
+
return {
|
|
287
|
+
...base,
|
|
288
|
+
desiredStatus: { phase: complete ? 'Synced' : 'Pending', workspaceIdentity: spec.workspaceIdentity?.name || spec.subject || '', repositoryIdentity: spec.repositoryIdentity?.username || spec.user || '', conditions: [baseCondition, { type: 'WorkspaceIdentityProjected', status: complete ? 'True' : 'False', reason: complete ? 'SubjectLinked' : 'MissingSubject' }, { type: 'RepositoryIdentityProjected', status: complete ? 'True' : 'False', reason: complete ? 'RepositoryAccountLinked' : 'MissingRepositoryIdentity' }] },
|
|
289
|
+
syncIntents: [
|
|
290
|
+
{ target: 'workspace-identity', action: 'link-identity', user: spec.user, provider: spec.provider, subject: spec.subject },
|
|
291
|
+
{ target: 'repository-access', action: 'link-repository-identity', user: spec.user, repositoryIdentity: spec.repositoryIdentity?.username || spec.user }
|
|
292
|
+
]
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
if (kind === 'RepositoryPermission') {
|
|
296
|
+
const revoked = Boolean(spec.revoked || resource.status?.phase === 'Revoked');
|
|
297
|
+
return {
|
|
298
|
+
...base,
|
|
299
|
+
desiredStatus: { phase: revoked ? 'Revoked' : 'Synced', repository: spec.repository, subject: spec.subject, permission: spec.permission || 'read', conditions: [baseCondition, { type: 'RepositoryPermissionProjected', status: revoked ? 'False' : 'True', reason: revoked ? 'GrantRevoked' : 'GrantSynced' }] },
|
|
300
|
+
syncIntents: [{ target: 'repository-access', action: revoked ? 'revoke-repository-permission' : 'sync-repository-permission', repository: spec.repository, subject: spec.subject, subjectKind: spec.subjectKind || 'user', permission: spec.permission || 'read' }]
|
|
301
|
+
};
|
|
302
|
+
}
|
|
303
|
+
if (kind === 'SSHKey') {
|
|
304
|
+
const fingerprint = spec.key ? `sha256:${createHash('sha256').update(spec.key).digest('base64url').slice(0, 32)}` : '';
|
|
305
|
+
const revoked = Boolean(spec.revoked || resource.status?.phase === 'Revoked');
|
|
306
|
+
return {
|
|
307
|
+
...base,
|
|
308
|
+
desiredStatus: { phase: revoked ? 'Revoked' : 'Synced', scope: spec.scope, fingerprint, conditions: [baseCondition, { type: 'SSHKeyProjected', status: revoked ? 'False' : 'True', reason: revoked ? 'KeyRevoked' : 'KeySynced' }] },
|
|
309
|
+
syncIntents: [{ target: 'repository-access', action: revoked ? 'revoke-ssh-key' : 'sync-ssh-key', name, scope: spec.scope, owner: spec.owner || spec.user, fingerprint }]
|
|
310
|
+
};
|
|
311
|
+
}
|
|
312
|
+
return base;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
export function orgNamespaceName(org) {
|
|
317
|
+
const slug = normalizeOrgSlug(org);
|
|
318
|
+
if (!slug) throw new Error('organization is required');
|
|
319
|
+
return `kradle-org-${slug}`;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
export function normalizeOrgSlug(value) {
|
|
323
|
+
return String(value || '').trim().toLowerCase().replace(/[^a-z0-9-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 63);
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
export function resolveResourceOrg(resource = {}, options = {}) {
|
|
327
|
+
const organizationRef = resource.spec?.organizationRef || resource.metadata?.labels?.[KRADLE_ORG_LABEL] || options.organization || options.org;
|
|
328
|
+
const org = normalizeOrgSlug(organizationRef);
|
|
329
|
+
if (!org && resource.kind !== 'Organization' && resource.kind !== 'OrgNamespaceBinding') throw new Error(`${resource.kind || 'Resource'} requires spec.organizationRef`);
|
|
330
|
+
const namespaceName = resource.kind === 'Organization'
|
|
331
|
+
? (resource.metadata?.namespace || options.platformNamespace || KRADLE_PLATFORM_NAMESPACE)
|
|
332
|
+
: (resource.spec?.namespaceName || resource.spec?.namespace || resource.metadata?.labels?.[KRADLE_ORG_NAMESPACE_LABEL] || (org ? orgNamespaceName(org) : resource.metadata?.namespace || options.platformNamespace || KRADLE_PLATFORM_NAMESPACE));
|
|
333
|
+
return { org, namespace: namespaceName };
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
export function withOrgScope(resource, options = {}) {
|
|
337
|
+
if (!resource || typeof resource !== 'object') throw new Error('resource object is required');
|
|
338
|
+
const platformNamespace = options.platformNamespace || options.namespace || KRADLE_PLATFORM_NAMESPACE;
|
|
339
|
+
if (resource.kind === 'Organization') {
|
|
340
|
+
const org = normalizeOrgSlug(resource.spec?.slug || resource.metadata?.name);
|
|
341
|
+
if (!org) throw new Error('Organization requires metadata.name or spec.slug');
|
|
342
|
+
const orgNamespace = resource.spec?.namespaceName || orgNamespaceName(org);
|
|
343
|
+
return {
|
|
344
|
+
apiVersion: resource.apiVersion || `${KRADLE_API_GROUP}/${KRADLE_API_VERSION}`,
|
|
345
|
+
...resource,
|
|
346
|
+
metadata: { ...(resource.metadata || {}), name: org, namespace: resource.metadata?.namespace || platformNamespace, labels: { ...(resource.metadata?.labels || {}), [KRADLE_ORG_LABEL]: org, [KRADLE_ORG_NAMESPACE_LABEL]: orgNamespace } },
|
|
347
|
+
spec: { ...(resource.spec || {}), slug: org, namespaceName: orgNamespace }
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
if (resource.kind === 'OrgNamespaceBinding') {
|
|
351
|
+
const org = normalizeOrgSlug(resource.spec?.organizationRef || resource.metadata?.labels?.[KRADLE_ORG_LABEL] || resource.metadata?.name);
|
|
352
|
+
if (!org) throw new Error('OrgNamespaceBinding requires spec.organizationRef');
|
|
353
|
+
const orgNamespace = resource.spec?.namespace || orgNamespaceName(org);
|
|
354
|
+
return {
|
|
355
|
+
apiVersion: resource.apiVersion || `${KRADLE_API_GROUP}/${KRADLE_API_VERSION}`,
|
|
356
|
+
...resource,
|
|
357
|
+
metadata: { ...(resource.metadata || {}), name: resource.metadata?.name || org, namespace: resource.metadata?.namespace || platformNamespace, labels: { ...(resource.metadata?.labels || {}), [KRADLE_ORG_LABEL]: org, [KRADLE_ORG_NAMESPACE_LABEL]: orgNamespace } },
|
|
358
|
+
spec: { createNamespace: true, ...(resource.spec || {}), organizationRef: org, namespace: orgNamespace, labels: { ...(resource.spec?.labels || {}), [KRADLE_ORG_LABEL]: org } }
|
|
359
|
+
};
|
|
360
|
+
}
|
|
361
|
+
const { org, namespace } = resolveResourceOrg(resource, options);
|
|
362
|
+
if (resource.metadata?.namespace && resource.metadata.namespace !== namespace) throw new Error(`${resource.kind} namespace ${resource.metadata.namespace} does not match organization ${org} namespace ${namespace}`);
|
|
363
|
+
if (resource.metadata?.labels?.[KRADLE_ORG_LABEL] && resource.metadata.labels[KRADLE_ORG_LABEL] !== org) throw new Error(`${resource.kind} org label does not match spec.organizationRef`);
|
|
364
|
+
return {
|
|
365
|
+
apiVersion: resource.apiVersion || `${KRADLE_API_GROUP}/${KRADLE_API_VERSION}`,
|
|
366
|
+
...resource,
|
|
367
|
+
metadata: { ...(resource.metadata || {}), namespace, labels: { ...(resource.metadata?.labels || {}), [KRADLE_ORG_LABEL]: org, [KRADLE_ORG_NAMESPACE_LABEL]: namespace } },
|
|
368
|
+
spec: { ...(resource.spec || {}), organizationRef: org }
|
|
369
|
+
};
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
export async function getControllerSnapshot(options = {}) {
|
|
373
|
+
const kubectl = options.kubectl || process.env.KRADLE_KUBECTL || 'kubectl';
|
|
374
|
+
const namespace = options.namespace || process.env.KRADLE_NAMESPACE || 'kradle-system';
|
|
375
|
+
const timeoutMs = Number(options.timeoutMs || process.env.KRADLE_KUBECTL_TIMEOUT_MS || 3_000);
|
|
376
|
+
const env = { ...process.env, ...(options.env || {}) };
|
|
377
|
+
const correlationId = randomUUID();
|
|
378
|
+
const contextResult = currentContextResult({ kubectl, timeoutMs, env });
|
|
379
|
+
const versionResult = runKubectl(['version', '--client=true', '-o', 'json'], { kubectl, timeoutMs, env, allowFailure: true });
|
|
380
|
+
if (!contextResult.ok || !versionResult.ok) {
|
|
381
|
+
const failed = [contextResult, versionResult].filter((result) => !result.ok);
|
|
382
|
+
return {
|
|
383
|
+
source: 'kubernetes',
|
|
384
|
+
mode: 'kubernetes-api',
|
|
385
|
+
namespace,
|
|
386
|
+
generatedAt: new Date().toISOString(),
|
|
387
|
+
correlationId,
|
|
388
|
+
kubectl: {
|
|
389
|
+
binary: kubectl,
|
|
390
|
+
context: contextResult.ok ? contextResult.stdout.trim() : null,
|
|
391
|
+
clientVersion: versionResult.ok ? safeJson(versionResult.stdout)?.clientVersion?.gitVersion || null : null,
|
|
392
|
+
available: false,
|
|
393
|
+
errors: failed.map((result) => commandFailure(result)).filter(Boolean)
|
|
394
|
+
},
|
|
395
|
+
apiService: null,
|
|
396
|
+
crds: [],
|
|
397
|
+
resources: Object.fromEntries(KRADLE_RESOURCES.filter((d) => d.storage !== 'core').map((definition) => [definition.kind, []])),
|
|
398
|
+
kyverno: emptyKyvernoDiscovery(namespace, env),
|
|
399
|
+
events: [],
|
|
400
|
+
permissions: [],
|
|
401
|
+
storage: storageBoundaries(),
|
|
402
|
+
commands: controllerCommands(namespace)
|
|
403
|
+
};
|
|
404
|
+
}
|
|
405
|
+
const apiServiceResult = runKubectl(['get', 'apiservice', KRADLE_API_VERSIONED_GROUP, '-o', 'json'], { kubectl, timeoutMs, env, allowFailure: true });
|
|
406
|
+
const crdResult = runKubectl(['get', 'crd', '-o', 'json'], { kubectl, timeoutMs, env, allowFailure: true });
|
|
407
|
+
if (!apiServiceResult.ok && !crdResult.ok) {
|
|
408
|
+
const failed = [apiServiceResult, crdResult].filter((result) => !result.ok);
|
|
409
|
+
return {
|
|
410
|
+
source: 'kubernetes',
|
|
411
|
+
mode: 'kubernetes-api',
|
|
412
|
+
namespace,
|
|
413
|
+
generatedAt: new Date().toISOString(),
|
|
414
|
+
correlationId,
|
|
415
|
+
kubectl: {
|
|
416
|
+
binary: kubectl,
|
|
417
|
+
context: contextResult.stdout.trim(),
|
|
418
|
+
clientVersion: safeJson(versionResult.stdout)?.clientVersion?.gitVersion || null,
|
|
419
|
+
available: true,
|
|
420
|
+
errors: failed.map((result) => commandFailure(result)).filter(Boolean)
|
|
421
|
+
},
|
|
422
|
+
apiService: null,
|
|
423
|
+
crds: [],
|
|
424
|
+
resources: Object.fromEntries(KRADLE_RESOURCES.filter((d) => d.storage !== 'core').map((definition) => [definition.kind, []])),
|
|
425
|
+
kyverno: emptyKyvernoDiscovery(namespace, env),
|
|
426
|
+
events: [],
|
|
427
|
+
permissions: [],
|
|
428
|
+
storage: storageBoundaries(),
|
|
429
|
+
commands: controllerCommands(namespace)
|
|
430
|
+
};
|
|
431
|
+
}
|
|
432
|
+
const discoveredCrds = crdResult.ok ? parseKubernetesList(crdResult.stdout).items.filter((crd) => [KRADLE_API_GROUP, KUBEVELA_API_GROUP].includes(crd.spec?.group) || KYVERNO_DISCOVERY_GROUPS.has(crd.spec?.group)) : [];
|
|
433
|
+
const discoveredPluralSet = new Set(discoveredCrds.map((crd) => `${crd.spec?.group || KRADLE_API_GROUP}/${crd.spec?.names?.plural}`).filter(Boolean));
|
|
434
|
+
if (!apiServiceResult.ok && discoveredCrds.length === 0) {
|
|
435
|
+
return {
|
|
436
|
+
source: 'kubernetes',
|
|
437
|
+
mode: 'kubernetes-api',
|
|
438
|
+
namespace,
|
|
439
|
+
generatedAt: new Date().toISOString(),
|
|
440
|
+
correlationId,
|
|
441
|
+
kubectl: {
|
|
442
|
+
binary: kubectl,
|
|
443
|
+
context: contextResult.stdout.trim(),
|
|
444
|
+
clientVersion: safeJson(versionResult.stdout)?.clientVersion?.gitVersion || null,
|
|
445
|
+
available: true,
|
|
446
|
+
errors: [commandFailure(apiServiceResult)].filter(Boolean)
|
|
447
|
+
},
|
|
448
|
+
apiService: null,
|
|
449
|
+
crds: [],
|
|
450
|
+
resources: Object.fromEntries(KRADLE_RESOURCES.filter((d) => d.storage !== 'core').map((definition) => [definition.kind, []])),
|
|
451
|
+
kyverno: emptyKyvernoDiscovery(namespace, env),
|
|
452
|
+
events: [],
|
|
453
|
+
permissions: [],
|
|
454
|
+
storage: storageBoundaries(),
|
|
455
|
+
commands: controllerCommands(namespace)
|
|
456
|
+
};
|
|
457
|
+
}
|
|
458
|
+
const kyverno = discoverKyverno({ kubectl, namespace, timeoutMs, env, discoveredPluralSet });
|
|
459
|
+
// Exclude core K8s resources (Secret, ConfigMap) from snapshot — they are
|
|
460
|
+
// accessed on-demand via listResource, not loaded into the full snapshot.
|
|
461
|
+
const snapshotResources = KRADLE_RESOURCES.filter((d) => d.storage !== 'core');
|
|
462
|
+
const resources = Object.fromEntries(snapshotResources.map((definition) => [definition.kind, []]));
|
|
463
|
+
const listResults = [];
|
|
464
|
+
const platformScopedDefinitions = snapshotResources.filter((definition) => definition.platformScoped);
|
|
465
|
+
const orgScopedDefinitions = snapshotResources.filter((definition) => !definition.platformScoped);
|
|
466
|
+
|
|
467
|
+
for (const definition of platformScopedDefinitions) {
|
|
468
|
+
if (!shouldListSnapshotDefinition(definition, discoveredPluralSet)) continue;
|
|
469
|
+
const resourceNamespace = definition.namespace || namespace;
|
|
470
|
+
const result = runKubectl(['get', apiResourceName(definition), ...namespaceArgs(definition, resourceNamespace), '-o', 'json', '--ignore-not-found'], { kubectl, timeoutMs, env, allowFailure: true });
|
|
471
|
+
listResults.push({ definition, result });
|
|
472
|
+
resources[definition.kind] = result.ok ? parseKubernetesList(result.stdout).items : [];
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
const orgNamespaces = organizationNamespaces(resources.Organization, resources.OrgNamespaceBinding, namespace);
|
|
476
|
+
for (const definition of orgScopedDefinitions) {
|
|
477
|
+
if (!shouldListSnapshotDefinition(definition, discoveredPluralSet)) continue;
|
|
478
|
+
const namespaces = definition.namespaced === false ? [null] : [definition.namespace || null].filter(Boolean).concat(definition.namespace ? [] : orgNamespaces);
|
|
479
|
+
resources[definition.kind] = namespaces.flatMap((resourceNamespace) => {
|
|
480
|
+
const effectiveNamespace = resourceNamespace || namespace;
|
|
481
|
+
const result = runKubectl(['get', apiResourceName(definition), ...namespaceArgs(definition, effectiveNamespace), '-o', 'json', '--ignore-not-found'], { kubectl, timeoutMs, env, allowFailure: true });
|
|
482
|
+
listResults.push({ definition, result });
|
|
483
|
+
return result.ok ? parseKubernetesList(result.stdout).items : [];
|
|
484
|
+
});
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
const eventsResult = runKubectl(['get', 'events', '-n', namespace, '-o', 'json', '--ignore-not-found'], { kubectl, timeoutMs, env, allowFailure: true });
|
|
488
|
+
const permissions = await Promise.all(snapshotResources.filter((definition) => discoveredPluralSet.has(`${definition.group || KRADLE_API_GROUP}/${definition.plural}`)).map(async (definition) => ({
|
|
489
|
+
kind: definition.kind,
|
|
490
|
+
plural: definition.plural,
|
|
491
|
+
verbs: Object.fromEntries(['get', 'list', 'watch', 'create', 'update', 'patch', 'delete'].map((verb) => [verb, canI(verb, definition, { kubectl, namespace: definition.namespace || namespace, timeoutMs, env })]))
|
|
492
|
+
})));
|
|
493
|
+
const unavailable = [contextResult, versionResult, ...listResults.map((item) => item.result)].filter((result) => !result.ok);
|
|
494
|
+
|
|
495
|
+
return {
|
|
496
|
+
source: 'kubernetes',
|
|
497
|
+
mode: 'kubernetes-api',
|
|
498
|
+
namespace,
|
|
499
|
+
generatedAt: new Date().toISOString(),
|
|
500
|
+
correlationId,
|
|
501
|
+
kubectl: {
|
|
502
|
+
binary: kubectl,
|
|
503
|
+
context: contextResult.ok ? contextResult.stdout.trim() : null,
|
|
504
|
+
clientVersion: versionResult.ok ? safeJson(versionResult.stdout)?.clientVersion?.gitVersion || null : null,
|
|
505
|
+
available: contextResult.ok && versionResult.ok,
|
|
506
|
+
errors: unavailable.map((result) => commandFailure(result)).filter(Boolean)
|
|
507
|
+
},
|
|
508
|
+
apiService: apiServiceResult.ok ? safeJson(apiServiceResult.stdout) : null,
|
|
509
|
+
crds: discoveredCrds,
|
|
510
|
+
resources,
|
|
511
|
+
kyverno,
|
|
512
|
+
events: eventsResult.ok ? parseKubernetesList(eventsResult.stdout).items : [],
|
|
513
|
+
permissions,
|
|
514
|
+
storage: storageBoundaries(),
|
|
515
|
+
commands: controllerCommands(namespace)
|
|
516
|
+
};
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
export async function listResource(kindOrPlural, options = {}) {
|
|
520
|
+
const namespace = options.namespace || process.env.KRADLE_NAMESPACE || 'kradle-system';
|
|
521
|
+
const definition = findResourceDefinition(kindOrPlural);
|
|
522
|
+
const resourceNamespace = definition.namespace || namespace;
|
|
523
|
+
const args = ['get', apiResourceName(definition), ...namespaceArgs(definition, resourceNamespace), '-o', 'json', '--ignore-not-found'];
|
|
524
|
+
const result = runKubectl(args, {
|
|
525
|
+
kubectl: options.kubectl || process.env.KRADLE_KUBECTL || 'kubectl',
|
|
526
|
+
timeoutMs: Number(options.timeoutMs || process.env.KRADLE_KUBECTL_TIMEOUT_MS || 3_000),
|
|
527
|
+
env: { ...process.env, ...(options.env || {}) },
|
|
528
|
+
allowFailure: false
|
|
529
|
+
});
|
|
530
|
+
return { operation: 'list', kind: definition.kind, command: `kubectl ${args.join(' ')}`, items: parseKubernetesList(result.stdout).items, stderr: result.stderr.trim() };
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
export async function getResource(kindOrPlural, name, options = {}) {
|
|
534
|
+
if (!name) throw new Error('resource name is required');
|
|
535
|
+
const namespace = options.namespace || process.env.KRADLE_NAMESPACE || 'kradle-system';
|
|
536
|
+
const definition = findResourceDefinition(kindOrPlural);
|
|
537
|
+
const resourceNamespace = definition.namespace || namespace;
|
|
538
|
+
const args = ['get', apiResourceName(definition), name, ...namespaceArgs(definition, resourceNamespace), '-o', 'json'];
|
|
539
|
+
const result = runKubectl(args, {
|
|
540
|
+
kubectl: options.kubectl || process.env.KRADLE_KUBECTL || 'kubectl',
|
|
541
|
+
timeoutMs: Number(options.timeoutMs || process.env.KRADLE_KUBECTL_TIMEOUT_MS || 3_000),
|
|
542
|
+
env: { ...process.env, ...(options.env || {}) },
|
|
543
|
+
allowFailure: false
|
|
544
|
+
});
|
|
545
|
+
return { operation: 'get', kind: definition.kind, name, command: `kubectl ${args.join(' ')}`, resource: safeJson(result.stdout), stderr: result.stderr.trim() };
|
|
546
|
+
}
|
|
547
|
+
export async function applyResource(resource, options = {}) {
|
|
548
|
+
if (!resource || typeof resource !== 'object') throw new Error('resource object is required');
|
|
549
|
+
if (!resource.kind) throw new Error('resource.kind is required');
|
|
550
|
+
const namespace = options.namespace || process.env.KRADLE_NAMESPACE || 'kradle-system';
|
|
551
|
+
const manifest = withOrgScope(resource, { namespace });
|
|
552
|
+
const kubectlBin = options.kubectl || process.env.KRADLE_KUBECTL || 'kubectl';
|
|
553
|
+
const timeoutMs = Number(options.timeoutMs || process.env.KRADLE_KUBECTL_TIMEOUT_MS || 3_000);
|
|
554
|
+
const env = { ...process.env, ...(options.env || {}) };
|
|
555
|
+
const targetNs = manifest.metadata?.namespace;
|
|
556
|
+
if (targetNs) {
|
|
557
|
+
ensureNamespace(targetNs, { kubectl: kubectlBin, timeoutMs, env });
|
|
558
|
+
}
|
|
559
|
+
const result = runKubectl(['apply', '-f', '-', '-o', 'json'], {
|
|
560
|
+
kubectl: kubectlBin,
|
|
561
|
+
timeoutMs,
|
|
562
|
+
env,
|
|
563
|
+
input: JSON.stringify(manifest),
|
|
564
|
+
allowFailure: false
|
|
565
|
+
});
|
|
566
|
+
return { operation: 'apply', command: 'kubectl apply -f -', resource: safeJson(result.stdout) || manifest, stderr: result.stderr.trim() };
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
function ensureNamespace(name, options) {
|
|
570
|
+
const check = runKubectl(['get', 'namespace', name], { ...options, allowFailure: true });
|
|
571
|
+
if (check.ok) return;
|
|
572
|
+
runKubectl(['create', 'namespace', name], { ...options, allowFailure: true });
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
export async function deleteResource(kindOrPlural, name, options = {}) {
|
|
576
|
+
if (!name) throw new Error('resource name is required');
|
|
577
|
+
const namespace = options.namespace || process.env.KRADLE_NAMESPACE || 'kradle-system';
|
|
578
|
+
const definition = findResourceDefinition(kindOrPlural);
|
|
579
|
+
const resourceNamespace = definition.namespace || namespace;
|
|
580
|
+
const args = ['delete', apiResourceName(definition), name, ...namespaceArgs(definition, resourceNamespace), '-o', 'json', '--ignore-not-found'];
|
|
581
|
+
const result = runKubectl(args, {
|
|
582
|
+
kubectl: options.kubectl || process.env.KRADLE_KUBECTL || 'kubectl',
|
|
583
|
+
timeoutMs: Number(options.timeoutMs || process.env.KRADLE_KUBECTL_TIMEOUT_MS || 3_000),
|
|
584
|
+
env: { ...process.env, ...(options.env || {}) },
|
|
585
|
+
allowFailure: false
|
|
586
|
+
});
|
|
587
|
+
return { operation: 'delete', command: `kubectl ${args.join(' ')}`, resource: safeJson(result.stdout), stdout: result.stdout.trim(), stderr: result.stderr.trim() };
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
export async function createOrganization(input = {}, options = {}) {
|
|
591
|
+
const namespace = options.namespace || process.env.KRADLE_NAMESPACE || KRADLE_PLATFORM_NAMESPACE;
|
|
592
|
+
const org = normalizeOrgSlug(input.slug || input.name || input.metadata?.name || input.spec?.slug);
|
|
593
|
+
if (!org) throw new Error('organization name is required');
|
|
594
|
+
const orgNamespace = input.namespaceName || input.namespace || input.spec?.namespaceName || orgNamespaceName(org);
|
|
595
|
+
const displayName = input.displayName || input.fullName || input.spec?.displayName || org;
|
|
596
|
+
const namespaceManifest = {
|
|
597
|
+
apiVersion: 'v1',
|
|
598
|
+
kind: 'Namespace',
|
|
599
|
+
metadata: { name: orgNamespace, labels: { [KRADLE_ORG_LABEL]: org, [KRADLE_ORG_NAMESPACE_LABEL]: orgNamespace, ...(input.labels || {}) } }
|
|
600
|
+
};
|
|
601
|
+
const organization = withOrgScope({
|
|
602
|
+
apiVersion: `${KRADLE_API_GROUP}/${KRADLE_API_VERSION}`,
|
|
603
|
+
kind: 'Organization',
|
|
604
|
+
metadata: { name: org },
|
|
605
|
+
spec: { displayName, slug: org, namespaceName: orgNamespace, ...(input.spec || {}) }
|
|
606
|
+
}, { namespace });
|
|
607
|
+
const binding = withOrgScope({
|
|
608
|
+
apiVersion: `${KRADLE_API_GROUP}/${KRADLE_API_VERSION}`,
|
|
609
|
+
kind: 'OrgNamespaceBinding',
|
|
610
|
+
metadata: { name: org },
|
|
611
|
+
spec: { organizationRef: org, namespace: orgNamespace, createNamespace: true, labels: input.labels || {} }
|
|
612
|
+
}, { namespace });
|
|
613
|
+
const applyOptions = {
|
|
614
|
+
kubectl: options.kubectl || process.env.KRADLE_KUBECTL || 'kubectl',
|
|
615
|
+
timeoutMs: Number(options.timeoutMs || process.env.KRADLE_KUBECTL_TIMEOUT_MS || 3_000),
|
|
616
|
+
env: { ...process.env, ...(options.env || {}) },
|
|
617
|
+
allowFailure: false
|
|
618
|
+
};
|
|
619
|
+
const namespaceResult = runKubectl(['apply', '-f', '-', '-o', 'json'], { ...applyOptions, input: JSON.stringify(namespaceManifest) });
|
|
620
|
+
const organizationResult = await applyResource(organization, { ...applyOptions, namespace });
|
|
621
|
+
const bindingResult = await applyResource(binding, { ...applyOptions, namespace });
|
|
622
|
+
return {
|
|
623
|
+
operation: 'create-organization',
|
|
624
|
+
organization: organizationResult.resource,
|
|
625
|
+
namespace: safeJson(namespaceResult.stdout) || namespaceManifest,
|
|
626
|
+
binding: bindingResult.resource,
|
|
627
|
+
command: 'kubectl apply -f -'
|
|
628
|
+
};
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
export function repositoryManifest(input = {}, namespace = process.env.KRADLE_NAMESPACE || 'kradle-system') {
|
|
632
|
+
const name = String(input.name || input.metadata?.name || '').trim();
|
|
633
|
+
const organizationRef = normalizeOrgSlug(input.organizationRef || input.org || input.spec?.organizationRef || input.metadata?.labels?.[KRADLE_ORG_LABEL]);
|
|
634
|
+
if (!name) throw new Error('repository name is required');
|
|
635
|
+
if (!organizationRef) throw new Error('repository organization is required');
|
|
636
|
+
return withOrgScope({
|
|
637
|
+
apiVersion: `${KRADLE_API_GROUP}/${KRADLE_API_VERSION}`,
|
|
638
|
+
kind: 'Repository',
|
|
639
|
+
metadata: { name, labels: input.labels || {} },
|
|
640
|
+
spec: {
|
|
641
|
+
organizationRef,
|
|
642
|
+
visibility: input.visibility || input.spec?.visibility || 'internal',
|
|
643
|
+
defaultBranch: input.defaultBranch || input.spec?.defaultBranch || 'main'
|
|
644
|
+
}
|
|
645
|
+
}, { namespace });
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
export function watchResource(resourcePath = 'orgs/default/repositories', options = {}, handlers = {}) {
|
|
649
|
+
const namespace = options.namespace || process.env.KRADLE_NAMESPACE || 'kradle-system';
|
|
650
|
+
const kubectl = options.kubectl || process.env.KRADLE_KUBECTL || 'kubectl';
|
|
651
|
+
const parts = String(resourcePath || '').split('/').filter(Boolean);
|
|
652
|
+
if (parts[0] !== 'orgs' || !parts[1] || !parts[2]) throw new Error('watch requires /api/watch/orgs/{org}/{resource}');
|
|
653
|
+
const org = normalizeOrgSlug(parts[1]);
|
|
654
|
+
const [pluralOrKind, name] = parts.slice(2);
|
|
655
|
+
const definition = findResourceDefinition(pluralOrKind || 'repositories');
|
|
656
|
+
const resourceNamespace = definition.namespace || (definition.platformScoped ? namespace : orgNamespaceName(org));
|
|
657
|
+
const args = ['get', apiResourceName(definition), ...(name ? [name] : []), ...namespaceArgs(definition, resourceNamespace), '--watch', '-o', 'json'];
|
|
658
|
+
const env = { ...process.env, ...(options.env || {}) };
|
|
659
|
+
const child = spawn(kubectl, kubectlInvocationArgs(args, env), { env, windowsHide: true });
|
|
660
|
+
child.stdout.on('data', (chunk) => handlers.stdout?.(chunk));
|
|
661
|
+
child.stderr.on('data', (chunk) => handlers.stderr?.(chunk));
|
|
662
|
+
child.on('error', (error) => handlers.error?.(error));
|
|
663
|
+
child.on('close', (code) => handlers.close?.(code));
|
|
664
|
+
return { child, command: `kubectl ${args.join(' ')}` };
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
export function findResourceDefinition(kindOrPlural) {
|
|
668
|
+
const normalized = String(kindOrPlural || '').toLowerCase();
|
|
669
|
+
const definition = KRADLE_RESOURCES.find((item) => item.kind.toLowerCase() === normalized || item.plural.toLowerCase() === normalized);
|
|
670
|
+
if (!definition) throw new Error(`Unsupported Kradle resource ${kindOrPlural}`);
|
|
671
|
+
return definition;
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
export function apiResourceName(definition) {
|
|
675
|
+
// Core K8s resources (Secret, ConfigMap) have group: '' — use bare plural name
|
|
676
|
+
const group = definition.group === '' ? '' : (definition.group || KRADLE_API_GROUP);
|
|
677
|
+
return group ? `${definition.plural}.${group}` : definition.plural;
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
export function withKradleDefaults(resource, namespace) {
|
|
681
|
+
if (resource?.kind && resource.kind !== 'Organization' && resource.kind !== 'OrgNamespaceBinding') return withOrgScope(resource, { namespace });
|
|
682
|
+
return {
|
|
683
|
+
apiVersion: resource.apiVersion || `${KRADLE_API_GROUP}/${KRADLE_API_VERSION}`,
|
|
684
|
+
...resource,
|
|
685
|
+
metadata: {
|
|
686
|
+
...(resource.metadata || {}),
|
|
687
|
+
namespace: resource.metadata?.namespace || namespace
|
|
688
|
+
}
|
|
689
|
+
};
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
function canI(verb, definition, options) {
|
|
693
|
+
const result = runKubectl(['auth', 'can-i', verb, apiResourceName(definition), ...namespaceArgs(definition, options.namespace)], { ...options, allowFailure: true });
|
|
694
|
+
return result.ok && result.stdout.trim().toLowerCase() === 'yes';
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
export function runKubectl(args, options = {}) {
|
|
698
|
+
const env = options.env || process.env;
|
|
699
|
+
const result = spawnSync(options.kubectl || 'kubectl', kubectlInvocationArgs(args, env), {
|
|
700
|
+
input: options.input,
|
|
701
|
+
encoding: 'utf8',
|
|
702
|
+
timeout: options.timeoutMs || 3_000,
|
|
703
|
+
env,
|
|
704
|
+
windowsHide: true,
|
|
705
|
+
maxBuffer: Number(env.KRADLE_KUBECTL_MAX_BUFFER_BYTES || 32 * 1024 * 1024)
|
|
706
|
+
});
|
|
707
|
+
const normalized = {
|
|
708
|
+
ok: result.status === 0 && !result.error,
|
|
709
|
+
status: result.status,
|
|
710
|
+
signal: result.signal,
|
|
711
|
+
stdout: result.stdout || '',
|
|
712
|
+
stderr: result.stderr || '',
|
|
713
|
+
error: result.error ? result.error.message : null,
|
|
714
|
+
command: `kubectl ${args.join(' ')}`
|
|
715
|
+
};
|
|
716
|
+
if (!normalized.ok && !options.allowFailure) {
|
|
717
|
+
throw new Error(commandFailure(normalized) || `kubectl failed: ${normalized.command}`);
|
|
718
|
+
}
|
|
719
|
+
return normalized;
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
|
|
723
|
+
function currentContextResult(options = {}) {
|
|
724
|
+
const inCluster = inClusterKubectlConfig(options.env || process.env);
|
|
725
|
+
if (inCluster) {
|
|
726
|
+
return {
|
|
727
|
+
ok: true,
|
|
728
|
+
status: 0,
|
|
729
|
+
signal: null,
|
|
730
|
+
stdout: `${inCluster.context}\n`,
|
|
731
|
+
stderr: '',
|
|
732
|
+
error: null,
|
|
733
|
+
command: 'kubectl config current-context'
|
|
734
|
+
};
|
|
735
|
+
}
|
|
736
|
+
return runKubectl(['config', 'current-context'], { ...options, allowFailure: true });
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
function kubectlInvocationArgs(args, env = process.env) {
|
|
740
|
+
const inCluster = inClusterKubectlConfig(env);
|
|
741
|
+
return inCluster ? [...inCluster.args, ...args] : args;
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
function inClusterKubectlConfig(env = process.env) {
|
|
745
|
+
if (String(env.KRADLE_DISABLE_IN_CLUSTER_KUBECTL || '').toLowerCase() === 'true') return null;
|
|
746
|
+
if (env.KUBECONFIG) return null;
|
|
747
|
+
const host = env.KUBERNETES_SERVICE_HOST;
|
|
748
|
+
const port = env.KUBERNETES_SERVICE_PORT || '443';
|
|
749
|
+
const serviceAccountDir = env.KRADLE_SERVICE_ACCOUNT_DIR || '/var/run/secrets/kubernetes.io/serviceaccount';
|
|
750
|
+
const tokenPath = env.KRADLE_SERVICE_ACCOUNT_TOKEN || `${serviceAccountDir}/token`;
|
|
751
|
+
const certificateAuthorityPath = env.KRADLE_SERVICE_ACCOUNT_CA || `${serviceAccountDir}/ca.crt`;
|
|
752
|
+
if (!host || !port || !existsSync(tokenPath) || !existsSync(certificateAuthorityPath)) return null;
|
|
753
|
+
const token = readFileSync(tokenPath, 'utf8').trim();
|
|
754
|
+
if (!token) return null;
|
|
755
|
+
return {
|
|
756
|
+
context: 'in-cluster',
|
|
757
|
+
args: [
|
|
758
|
+
`--server=https://${host}:${port}`,
|
|
759
|
+
`--certificate-authority=${certificateAuthorityPath}`,
|
|
760
|
+
`--token=${token}`
|
|
761
|
+
]
|
|
762
|
+
};
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
|
|
766
|
+
function kyvernoMode(env = process.env) {
|
|
767
|
+
const configured = env.KRADLE_KYVERNO_MODE || env.KRADLE_EXTERNAL_KYVERNO_MODE;
|
|
768
|
+
if (configured) return configured;
|
|
769
|
+
if (String(env.KRADLE_KYVERNO_ENABLED || '').toLowerCase() === 'true') return 'byo';
|
|
770
|
+
if (String(env.KRADLE_KYVERNO_DISCOVER_EXISTING || '').toLowerCase() !== 'false') return 'auto';
|
|
771
|
+
return 'disabled';
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
function emptyKyvernoDiscovery(namespace = KRADLE_PLATFORM_NAMESPACE, env = process.env) {
|
|
775
|
+
return {
|
|
776
|
+
mode: kyvernoMode(env),
|
|
777
|
+
namespace: env.KRADLE_KYVERNO_NAMESPACE || env.KRADLE_EXTERNAL_KYVERNO_NAMESPACE || 'kyverno',
|
|
778
|
+
policyNamespace: env.KRADLE_KYVERNO_POLICY_NAMESPACE || namespace,
|
|
779
|
+
requireForEnforceMode: String(env.KRADLE_KYVERNO_REQUIRE_FOR_ENFORCE_MODE || 'true') !== 'false',
|
|
780
|
+
detected: false,
|
|
781
|
+
controllers: [],
|
|
782
|
+
resources: Object.fromEntries(KYVERNO_RESOURCES.map((definition) => [definition.kind, []])),
|
|
783
|
+
reports: { policyReports: [], clusterPolicyReports: [], results: [], violations: [] },
|
|
784
|
+
permissions: [],
|
|
785
|
+
degraded: []
|
|
786
|
+
};
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
function discoverKyverno({ kubectl, namespace, timeoutMs, env, discoveredPluralSet }) {
|
|
790
|
+
const discovery = emptyKyvernoDiscovery(namespace, env);
|
|
791
|
+
const availableDefinitions = KYVERNO_RESOURCES.filter((definition) => discoveredPluralSet.has(`${definition.group || KRADLE_API_GROUP}/${definition.plural}`));
|
|
792
|
+
discovery.detected = availableDefinitions.length > 0;
|
|
793
|
+
if (discovery.detected && discovery.mode === 'auto') discovery.mode = 'byo';
|
|
794
|
+
if (!discovery.detected) {
|
|
795
|
+
if (discovery.mode !== 'disabled') discovery.degraded.push('Kyverno CRDs are not installed or are not readable by the Kradle service account.');
|
|
796
|
+
return discovery;
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
const listResults = [];
|
|
800
|
+
for (const definition of availableDefinitions) {
|
|
801
|
+
const resourceNamespace = definition.namespaced === false ? null : definition.namespace || (definition.kind === 'PolicyReport' ? namespace : discovery.policyNamespace);
|
|
802
|
+
const result = runKubectl(['get', apiResourceName(definition), ...namespaceArgs(definition, resourceNamespace), '-o', 'json', '--ignore-not-found'], { kubectl, timeoutMs, env, allowFailure: true });
|
|
803
|
+
listResults.push({ definition, result });
|
|
804
|
+
discovery.resources[definition.kind] = result.ok ? parseKubernetesList(result.stdout).items : [];
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
const deploymentsResult = runKubectl(['get', 'deploy', '-n', discovery.namespace, '-o', 'json', '--ignore-not-found'], { kubectl, timeoutMs, env, allowFailure: true });
|
|
808
|
+
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 })) : [];
|
|
809
|
+
|
|
810
|
+
discovery.permissions = availableDefinitions.map((definition) => {
|
|
811
|
+
const resourceNamespace = definition.namespaced === false ? null : definition.namespace || (definition.kind === 'PolicyReport' ? namespace : discovery.policyNamespace);
|
|
812
|
+
return {
|
|
813
|
+
kind: definition.kind,
|
|
814
|
+
plural: definition.plural,
|
|
815
|
+
apiResource: apiResourceName(definition),
|
|
816
|
+
verbs: Object.fromEntries(['get', 'list', 'watch', 'create', 'patch'].map((verb) => [verb, canI(verb, definition, { kubectl, namespace: resourceNamespace || namespace, timeoutMs, env })]))
|
|
817
|
+
};
|
|
818
|
+
});
|
|
819
|
+
|
|
820
|
+
const policyReports = discovery.resources.PolicyReport || [];
|
|
821
|
+
const clusterPolicyReports = discovery.resources.ClusterPolicyReport || [];
|
|
822
|
+
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 })));
|
|
823
|
+
discovery.reports = { policyReports, clusterPolicyReports, results, violations: results.filter((result) => ['fail', 'error', 'warn'].includes(String(result.result || '').toLowerCase())) };
|
|
824
|
+
discovery.degraded.push(...listResults.filter(({ result }) => !result.ok).map(({ definition, result }) => `${definition.kind}: ${commandFailure(result)}`));
|
|
825
|
+
if (discovery.mode !== 'disabled' && discovery.controllers.length === 0) discovery.degraded.push(`No Kyverno controller deployments were found in namespace ${discovery.namespace}.`);
|
|
826
|
+
return discovery;
|
|
827
|
+
}
|
|
828
|
+
function organizationNamespaces(organizations = [], bindings = [], fallbackNamespace = KRADLE_PLATFORM_NAMESPACE) {
|
|
829
|
+
const namespaces = [...new Set([
|
|
830
|
+
...organizations.map((org) => org.spec?.namespaceName || org.metadata?.labels?.[KRADLE_ORG_NAMESPACE_LABEL]).filter(Boolean),
|
|
831
|
+
...bindings.map((binding) => binding.spec?.namespace || binding.metadata?.labels?.[KRADLE_ORG_NAMESPACE_LABEL]).filter(Boolean)
|
|
832
|
+
])];
|
|
833
|
+
if (namespaces.length) return namespaces;
|
|
834
|
+
const fallbackOrgs = new Set();
|
|
835
|
+
const adminOrg = process.env.KRADLE_ADMIN_ORG;
|
|
836
|
+
const defaultOrg = process.env.KRADLE_ORG || 'default';
|
|
837
|
+
if (adminOrg) fallbackOrgs.add(orgNamespaceName(adminOrg));
|
|
838
|
+
fallbackOrgs.add(orgNamespaceName(defaultOrg));
|
|
839
|
+
return fallbackOrgs.size ? [...fallbackOrgs] : [fallbackNamespace];
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
function shouldListSnapshotDefinition(definition, discoveredPluralSet) {
|
|
843
|
+
const group = definition.group || KRADLE_API_GROUP;
|
|
844
|
+
if (discoveredPluralSet.has(`${group}/${definition.plural}`)) return true;
|
|
845
|
+
return group === KRADLE_API_GROUP;
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
function parseKubernetesList(stdout) {
|
|
849
|
+
const parsed = safeJson(stdout);
|
|
850
|
+
if (!parsed) return { items: [] };
|
|
851
|
+
if (Array.isArray(parsed.items)) return parsed;
|
|
852
|
+
if (parsed.kind && parsed.metadata) return { items: [parsed] };
|
|
853
|
+
return { items: [] };
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
function safeJson(text) {
|
|
857
|
+
try {
|
|
858
|
+
return text ? JSON.parse(text) : null;
|
|
859
|
+
} catch {
|
|
860
|
+
return null;
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
function commandFailure(result) {
|
|
865
|
+
if (!result || result.ok) return null;
|
|
866
|
+
const detail = (result.stderr || result.error || result.stdout || '').trim();
|
|
867
|
+
return `${result.command}: ${detail || `exit ${result.status ?? 'unknown'}`}`;
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
function namespaceArgs(definition, namespace) {
|
|
871
|
+
return definition.namespaced === false ? [] : ['-n', namespace];
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
function commandString(args) {
|
|
875
|
+
return args.join(' ');
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
function storageBoundaries() {
|
|
879
|
+
return {
|
|
880
|
+
etcd: 'Kradle CRDs: Organization, Repository, SSHKey, RepositoryPermission, BranchProtection, RefPolicy, WebhookSubscription, RunnerPool, View, Selector',
|
|
881
|
+
kubevela: 'Kradle deployment CRDs: Application, ApplicationRevision, ComponentDefinition, WorkloadDefinition, TraitDefinition, ScopeDefinition, PolicyDefinition, Policy, WorkflowStepDefinition, Workflow, ResourceTracker',
|
|
882
|
+
postgres: 'Aggregated API resources: PullRequest, Issue, Review, Pipeline, Job, WebhookDelivery',
|
|
883
|
+
repositories: 'Repository backend Deployment, repository storage, and integration plans',
|
|
884
|
+
objects: 'Object storage referenced by Repository specs and Pipeline artifacts'
|
|
885
|
+
};
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
function controllerCommands(namespace) {
|
|
889
|
+
return KRADLE_RESOURCES.map((definition) => {
|
|
890
|
+
const resourceNamespace = definition.namespace || namespace;
|
|
891
|
+
return {
|
|
892
|
+
kind: definition.kind,
|
|
893
|
+
list: commandString(['kubectl', 'get', apiResourceName(definition), ...namespaceArgs(definition, resourceNamespace)]),
|
|
894
|
+
watch: commandString(['kubectl', 'get', apiResourceName(definition), ...namespaceArgs(definition, resourceNamespace), '--watch', '-o', 'json']),
|
|
895
|
+
apply: 'kubectl apply -f -',
|
|
896
|
+
delete: commandString(['kubectl', 'delete', apiResourceName(definition), '<name>', ...namespaceArgs(definition, resourceNamespace)])
|
|
897
|
+
};
|
|
898
|
+
});
|
|
899
|
+
}
|
|
900
|
+
|
|
901
|
+
|
|
902
|
+
|
|
903
|
+
|
|
904
|
+
|