@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
@@ -0,0 +1,352 @@
1
+ # Krate System Specification v2
2
+
3
+ > Derived from implementation. Source: `packages/krate/core/src/`
4
+
5
+ ## 1. Resource Taxonomy
6
+
7
+ All 76 resource kinds from `RESOURCE_DEFINITIONS` in `packages/krate/core/src/resource-model.js`:
8
+
9
+ ### CONFIG Kinds (etcd storage — 44 kinds)
10
+
11
+ | Kind | Context | Plural | Purpose | RequiredSpec |
12
+ |------|---------|--------|---------|--------------|
13
+ | Organization | identity | organizations | Krate organization identity in the platform namespace | displayName, namespaceName |
14
+ | OrgNamespaceBinding | identity | orgnamespacebindings | Binding from org to tenant namespace | organizationRef, namespace |
15
+ | User | identity | users | Human account profile, sign-in state, admin flag | organizationRef, displayName, email |
16
+ | Team | identity | teams | Team membership, maintainers, permission grants | organizationRef, displayName |
17
+ | Invite | identity | invites | Pending user invitation with expiry | organizationRef, email, role |
18
+ | IdentityMapping | identity | identitymappings | Mapping between Krate users and external subjects | organizationRef, user, provider, subject |
19
+ | AuthProvider | identity | authproviders | Sign-in provider configuration | organizationRef, type |
20
+ | Repository | data-plane | repositories | Repository identity, visibility, hosting integration | organizationRef, visibility |
21
+ | SSHKey | data-plane | sshkeys | User/deploy/automation SSH keys | organizationRef, scope, key |
22
+ | RepositoryPermission | data-plane | repositorypermissions | Repository collaborators and teams | organizationRef, repository, subject, permission |
23
+ | WebhookSubscription | hooks-events | webhooksubscriptions | Endpoint, event filters, signing, delivery mode | organizationRef, url, events |
24
+ | RefPolicy | data-plane | refpolicies | Reference deny rules, force-push policy | organizationRef |
25
+ | BranchProtection | control-plane | branchprotections | Protected ref rules | organizationRef, refs |
26
+ | PolicyProfile | policy | policyprofiles | Org policy posture, default templates | organizationRef, displayName, mode |
27
+ | PolicyTemplate | policy | policytemplates | Kyverno policy template metadata | displayName, targetKinds, kyverno |
28
+ | PolicyBinding | policy | policybindings | Template binding with audit/enforce state | organizationRef, templateRef, mode |
29
+ | PolicyExceptionRequest | policy | policyexceptionrequests | Temporary PolicyException request | organizationRef, policyRef, justification, expiresAt |
30
+ | View | web-ui | views | Saved triage/dashboard view | organizationRef, selector |
31
+ | Selector | web-ui | selectors | Reusable label/query selector | organizationRef |
32
+ | RunnerPool | runners-ci | runnerpools | Runner capacity, warm/max replicas, cache | organizationRef, warmReplicas, maxReplicas |
33
+ | AgentStack | agents | agentstacks | Reusable agent definition with full config | organizationRef, baseAgent, adapter, runtimeIdentity |
34
+ | AgentSubagent | agents | agentsubagents | Named child-agent definition | organizationRef, rolePrompt, taskKinds |
35
+ | AgentToolProfile | agents | agenttoolprofiles | Native tool policy for filesystem/network/shell | organizationRef, filesystemPolicy, approvalPolicyByTool |
36
+ | AgentMcpServer | agents | agentmcpservers | Managed MCP endpoint with transport/health | organizationRef, transport, scope |
37
+ | AgentSkill | agents | agentskills | Reusable runbook/procedure bundle | organizationRef, format, sourceRef |
38
+ | AgentTriggerRule | agents | agenttriggerrules | Event-to-stack routing | organizationRef, sources, agentStack, taskKind |
39
+ | AgentContextLabel | agents | agentcontextlabels | Reviewed prompt fragment | organizationRef, promptFragment, allowedSources |
40
+ | KrateWorkspacePolicy | agents | krateworkspacepolicies | Workspace provisioning/cleanup policies | organizationRef, mode, retentionPolicy |
41
+ | AgentServiceAccount | identity | agentserviceaccounts | K8s ServiceAccount wrapper for agent identity | organizationRef, namespace, serviceAccountName |
42
+ | AgentRoleBinding | identity | agentrolebindings | Managed RBAC projection for agent identity | organizationRef, subject, roleRef, scope |
43
+ | AgentSecretGrant | identity | agentsecretgrants | Permission to access Secret keys | organizationRef, subject, secretRef, purpose |
44
+ | AgentConfigGrant | identity | agentconfiggrants | Permission to access ConfigMap keys | organizationRef, subject, configMapRef, purpose |
45
+ | AgentAdapter | agents | agentadapters | Agent adapter with transport/capabilities | organizationRef, adapterType, transport |
46
+ | AgentTransportBinding | agents | agenttransportbindings | Adapter connection configuration | organizationRef, adapterRef, endpoint, protocol |
47
+ | AgentProviderConfig | agents | agentproviderconfigs | Model provider configuration | organizationRef, provider, authType |
48
+ | KrateProject | agents | krateprojects | Org project grouping issues/repos | organizationRef, displayName |
49
+ | AgentGatewayConfig | agents | agentgatewayconfigs | Agent Mux gateway connection settings | organizationRef, gatewayUrl |
50
+ | AgentMemoryRepository | agents | agentmemoryrepositories | Git repo pointer for shared agent memory | organizationRef, repositoryRef, defaultBranch, layoutProfile |
51
+ | AgentMemorySource | agents | agentmemorysources | Read policy for memory paths/kinds | organizationRef, repositoryRef, appliesTo, include |
52
+ | AgentMemoryOntology | agents | agentmemoryontologies | Ontology policy with fields/edges/vocabulary | organizationRef, memoryRepository, ontologyPath |
53
+ | AgentMemoryAssociation | agents | agentmemoryassociations | Bridge linking memory to Krate resources | organizationRef, memoryRef, targetRef, relationship |
54
+ | KrateWorkspace | workspaces | krateworkspaces | Volume-backed git workspace with PVC lifecycle | organizationRef, repository, volumeSpec |
55
+ | ExternalBackendProvider | external-backends | externalbackendproviders | External provider registration | organizationRef, providerType, endpoint |
56
+ | ExternalBackendBinding | external-backends | externalbackendbindings | Provider binding to org | organizationRef, providerRef, credentialRef |
57
+ | ExternalBackendSyncPolicy | external-backends | externalbackendsyncpolicies | Sync interval, conflict resolution | organizationRef, providerRef, syncInterval |
58
+ | ExternalProviderCapabilityManifest | external-backends | externalprovidercapabilitymanifests | Discovered provider capabilities | organizationRef, providerRef, capabilities |
59
+
60
+ ### AGGREGATED Kinds (postgres storage — 32 kinds)
61
+
62
+ | Kind | Context | Plural | Purpose | RequiredSpec |
63
+ |------|---------|--------|---------|--------------|
64
+ | PullRequest | control-plane | pullrequests | Review unit with source/target refs | organizationRef, repository, title |
65
+ | Issue | control-plane | issues | Project-scoped work item | organizationRef, title |
66
+ | Review | control-plane | reviews | Approval/comment for a PR | organizationRef, pullRequest |
67
+ | Pipeline | runners-ci | pipelines | CI pipeline run state | organizationRef, repository, ref |
68
+ | Job | runners-ci | jobs | Executable CI step | organizationRef, pipeline, step |
69
+ | WebhookDelivery | hooks-events | webhookdeliveries | Outbound webhook delivery attempt | organizationRef, subscription, eventType, signature |
70
+ | AgentDispatchRun | agents | agentdispatchruns | Logical agent run with queue/status/cost | organizationRef, repository, sourceRefs, agentStack, taskKind |
71
+ | AgentDispatchAttempt | agents | agentdispatchattempts | Concrete execution attempt | organizationRef, agentDispatchRun, attemptReason, agentStackSnapshot |
72
+ | AgentSession | agents | agentsessions | Agent Mux session projection | organizationRef, agentMuxSessionId, dispatchRun |
73
+ | AgentContextBundle | agents | agentcontextbundles | Immutable prompt/context snapshot | organizationRef, dispatchRun, digest, sources |
74
+ | KrateArtifact | agents | krateartifacts | Durable agent output | organizationRef, dispatchRun, kind, digest |
75
+ | AgentApproval | agents | agentapprovals | Human gate for actions | organizationRef, dispatchRun, action, requestedBy |
76
+ | AgentTriggerExecution | agents | agenttriggerexecutions | Trigger evaluation record | organizationRef, triggerRule, sourceEvent, decision |
77
+ | AgentCapabilityRequirement | agents | agentcapabilityrequirements | Computed dependency record | organizationRef, ownerRef, requiredRoles |
78
+ | WorkItemSessionLink | agents | workitemsessionlinks | Issue/PR to session association | organizationRef, workItemRef, agentSession |
79
+ | WorkItemWorkspaceLink | agents | workitemworkspacelinks | Issue/PR to workspace association | organizationRef, workItemRef, workspace |
80
+ | AgentSessionTranscript | agents | agentsessiontranscripts | Chat transcript with cost | organizationRef, sessionRef, messages |
81
+ | AgentSessionAttachment | agents | agentsessionattachments | File attached to session | organizationRef, sessionRef, sourceType, digest |
82
+ | KrateWorkspaceRuntime | agents | krateworkspaceruntimes | Workspace runtime state | organizationRef, workspaceRef, status |
83
+ | AgentMemorySnapshot | agents | agentmemorysnapshots | Dispatch-time memory pin | organizationRef, memoryRepository, requestedRef, resolvedCommit |
84
+ | AgentMemoryQuery | agents | agentmemoryqueries | Retrieval record with results | organizationRef, snapshotRef, requester, query |
85
+ | AgentMemoryUpdate | agents | agentmemoryupdates | Proposed memory mutation | organizationRef, memoryRepository, sourceRun, changes |
86
+ | AgentRunMemoryImport | agents | agentrunmemoryimports | Import run metadata into memory | organizationRef, memoryRepository, source, include |
87
+ | ExternalWebhookDelivery | external-backends | externalwebhookdeliveries | Inbound webhook from external | organizationRef, providerRef, eventType, payload |
88
+ | ExternalSyncEvent | external-backends | externalsyncevents | Sync event record | organizationRef, providerRef, eventKind, resourceRef |
89
+ | ExternalSyncState | external-backends | externalsyncstates | Current sync phase/status | organizationRef, providerRef, resourceRef, phase |
90
+ | ExternalWriteIntent | external-backends | externalwriteintents | Queued write-back intent | organizationRef, providerRef, resourceRef, operation |
91
+ | ExternalSyncConflict | external-backends | externalsyncconflicts | Detected conflict with diff | organizationRef, providerRef, resourceRef, conflictKind |
92
+ | ExternalObjectLink | external-backends | externalobjectlinks | Mapping between local and external | organizationRef, providerRef, externalId, localRef |
93
+
94
+ ---
95
+
96
+ ## 2. API Surface
97
+
98
+ All HTTP routes from `packages/krate/core/src/http-server.js`:
99
+
100
+ | Method | Path | Auth | Description |
101
+ |--------|------|------|-------------|
102
+ | GET | `/healthz` | No | Health check |
103
+ | GET | `/api/controller` | No | Full controller UI model (optional `?org=`) |
104
+ | GET | `/api/orgs` | No | List organizations |
105
+ | POST | `/api/orgs` | Yes | Create organization |
106
+ | GET | `/api/orgs/:org/resources` | No | List resources by kind (`?kind=`) |
107
+ | POST | `/api/orgs/:org/resources` | Yes | Apply (create/update) resource |
108
+ | GET | `/api/orgs/:org/resources/:kind/:name` | No | Get single resource |
109
+ | DELETE | `/api/orgs/:org/resources/:kind/:name` | Yes | Delete resource |
110
+ | GET | `/api/orgs/:org/repositories` | No | List repositories |
111
+ | POST | `/api/orgs/:org/repositories` | Yes | Create repository |
112
+ | GET | `/api/orgs/:org/repositories/:name` | No | Get repository |
113
+ | DELETE | `/api/orgs/:org/repositories/:name` | Yes | Delete repository |
114
+ | GET | `/api/orgs/:org/snapshot` | No | Org runtime snapshot |
115
+ | POST | `/api/orgs/:org/snapshot` | Yes | Import snapshot |
116
+ | GET | `/api/orgs/:org/runtime-resources/:kind` | No | List runtime resources by kind |
117
+ | POST | `/api/orgs/:org/repositories/:repo/objects` | Yes | Record git object |
118
+ | POST | `/api/orgs/:org/repositories/:repo/search-index` | Yes | Enqueue search index |
119
+ | POST | `/api/orgs/:org/pullrequests` | Yes | Create pull request |
120
+ | POST | `/api/orgs/:org/pullrequests/:pr/reviews` | Yes | Add review |
121
+ | POST | `/api/orgs/:org/pullrequests/:pr/checks/complete` | Yes | Complete pipeline check |
122
+ | POST | `/api/orgs/:org/pullrequests/:pr/merge` | Yes | Merge pull request |
123
+ | POST | `/api/orgs/:org/agents/approvals/:name/decide` | Yes | Approve/deny agent action |
124
+ | POST | `/api/orgs/:org/agents/webhooks/ingest` | Yes | Ingest webhook event |
125
+ | POST | `/api/orgs/:org/agents/events/pipeline-failure` | Yes | Pipeline failure event |
126
+ | POST | `/api/orgs/:org/agents/events/comment` | Yes | Comment event |
127
+ | POST | `/api/orgs/:org/agents/events/label` | Yes | Label event |
128
+ | POST | `/api/orgs/:org/agents/triggers/process` | Yes | Process trigger |
129
+ | POST | `/api/orgs/:org/agents/memory/query` | Yes | Query agent memory |
130
+ | GET | `/api/orgs/:org/secrets` | No | List secrets |
131
+ | POST | `/api/orgs/:org/secrets` | Yes | Create secret |
132
+ | DELETE | `/api/orgs/:org/secrets/:name` | Yes | Delete secret |
133
+ | GET | `/api/orgs/:org/secret-grants` | No | List secret grants |
134
+ | POST | `/api/orgs/:org/secret-grants` | Yes | Create secret grant |
135
+ | POST | `/api/orgs/:org/external/sync` | Yes | Trigger external sync |
136
+ | POST | `/api/orgs/:org/external/conflicts/:name/resolve` | Yes | Resolve sync conflict |
137
+ | POST | `/api/orgs/:org/external/write-intents/:name/approve` | Yes | Approve write intent |
138
+ | POST | `/api/orgs/:org/external/write-intents/:name/cancel` | Yes | Cancel write intent |
139
+ | GET | `/api/orgs/:org/agents/events/stream` | No | SSE event stream |
140
+
141
+ ---
142
+
143
+ ## 3. Controller Boundaries
144
+
145
+ Each controller declares an explicit boundary object. Source: respective controller files.
146
+
147
+ | Controller | File | Role | Owns | Delegates To | Must Not Own |
148
+ |-----------|------|------|------|--------------|--------------|
149
+ | KubernetesResourceClient | `kubernetes-controller.js` | Workspace API, access checks | command execution, API discovery, access checks, watch streams | — | HTTP routes, Next.js pages, forge DTO, business workflows |
150
+ | KrateKubernetesReconciler | `kubernetes-controller.js` | Resource reconciliation | Repository status, identity projection, hosting intent, policy sync, degraded conditions | kubernetes-resource-gateway, git-data-plane | HTTP routes, web pages, API DTO, browser behavior |
151
+ | AgentStackController | `agent-stack-controller.js` | Stack readiness reconciliation | capability resolution, conditions, readiness, MCP health | agent-permission-review, resource-model | secret values, dispatch execution, Agent Mux sessions |
152
+ | AgentDispatchController | `agent-dispatch-controller.js` | Manual dispatch orchestration | dispatch creation, attempt lifecycle, session binding, workspace provisioning | agent-permission-review, agent-stack, agent-context-bundles, agent-mux-client, agent-memory, agent-approval, agent-workspace | secret values, UI rendering |
153
+ | AgentWorkspaceController | `agent-workspace-controller.js` | Volume-backed workspace provisioning | workspace creation, PVC generation, git specs, mount specs, reuse, codespace, associations, run history | resource-model | git execution, K8s API, secrets |
154
+ | AgentMemoryQuery | `agent-memory-query.js` | In-memory graph/grep query | graph traversal, nodeKind filtering, edge following, scoring, grep, context extraction | (none) | persistence, HTTP, K8s, secrets |
155
+ | WebhookController | `external/webhook-controller.js` | Inbound webhook delivery | HMAC validation, delivery records, dedup, event queue | sync-controller | resource persistence, ownership |
156
+ | SyncController | `external/sync-controller.js` | External sync orchestration | sync events, state transitions, watermarks | conflict-controller | webhook ingestion, write execution |
157
+ | ConflictController | `external/conflict-controller.js` | Conflict detection/resolution | conflict records, resolution strategies, diff computation | — | sync execution, write-back |
158
+ | WriteController | `external/write-controller.js` | Write intent management | intent creation, approval, execution queue | — | sync, conflict detection |
159
+ | AuditController | `audit-controller.js` | Audit event recording | event capture, query, time-range filtering | — | business logic, auth |
160
+ | RunnerController | `runner-controller.js` | Runner pool management | pool sizing, pod spec, capacity tracking | — | job execution |
161
+ | NotificationController | `notification-controller.js` | Notification delivery | notification creation, delivery, read status | — | business decisions |
162
+
163
+ ---
164
+
165
+ ## 4. Event System
166
+
167
+ Source: `packages/krate/core/src/event-bus.js`, `notification-controller.js`, `audit-controller.js`
168
+
169
+ ### 4.1 Event Bus
170
+
171
+ ```javascript
172
+ const bus = createEventBus();
173
+ bus.subscribe(listener); // Register listener
174
+ bus.emit(event); // Broadcast to all
175
+ bus.emitResourceChange(kind, name, operation); // Convenience
176
+ ```
177
+
178
+ Global singleton: `globalEventBus`
179
+
180
+ ### 4.2 SSE Streaming
181
+
182
+ Route: `GET /api/orgs/:org/agents/events/stream`
183
+
184
+ - Content-Type: `text/event-stream`
185
+ - Initial connection message: `{"type":"connected"}`
186
+ - Heartbeat every 30 seconds: `{"type":"heartbeat"}`
187
+ - Resource change events forwarded from globalEventBus
188
+ - Connection cleanup on client disconnect
189
+
190
+ ### 4.3 Notification Controller
191
+
192
+ Manages notification lifecycle:
193
+ - Create notifications with type, title, body, target
194
+ - Mark as read/unread
195
+ - List with filtering by read status
196
+ - Auto-expiry based on age
197
+
198
+ ### 4.4 Audit Controller
199
+
200
+ Records audit events with:
201
+ - Action (create, update, delete, login, dispatch)
202
+ - Actor (user, system, agent)
203
+ - Resource reference
204
+ - Timestamp
205
+ - Query by org, action, time range, with pagination
206
+
207
+ ---
208
+
209
+ ## 5. Workspace Lifecycle
210
+
211
+ Source: `packages/krate/core/src/agent-workspace-controller.js`
212
+
213
+ ### 5.1 Provisioning Flow
214
+
215
+ 1. **Create workspace** — Generate `KrateWorkspace` resource with PVC spec
216
+ 2. **PVC manifest** — StorageClass, capacity (default 10Gi), access modes (ReadWriteOnce)
217
+ 3. **Git clone spec** — Commands to clone repository into workspace volume
218
+ 4. **Checkout spec** — Branch/ref checkout commands
219
+ 5. **Runner mount spec** — Volume mount configuration for runner pods
220
+
221
+ ### 5.2 Workspace Reuse
222
+
223
+ Workspaces can be reused across dispatch runs:
224
+ - Match by repository + branch
225
+ - Update workspace status to reflect new session binding
226
+ - Track run history per workspace
227
+
228
+ ### 5.3 Codespace Management
229
+
230
+ - Live workspace runtime state (`KrateWorkspaceRuntime`)
231
+ - Process status, environment variables, preview URLs
232
+ - Session shell access via web console
233
+
234
+ ---
235
+
236
+ ## 6. Runner System
237
+
238
+ Source: `packages/krate/core/src/runner-controller.js`, `runners-ci.js`
239
+
240
+ ### 6.1 Pool Management
241
+
242
+ `RunnerPool` defines:
243
+ - `warmReplicas` — Pre-provisioned ready runners
244
+ - `maxReplicas` — Maximum capacity
245
+ - Cache policy for workspace data
246
+ - Trust boundary for execution isolation
247
+
248
+ ### 6.2 Pod Spec Generation
249
+
250
+ Runner pods include:
251
+ - Workspace PVC volume mount
252
+ - Service account binding (`AgentServiceAccount`)
253
+ - Resource limits and requests
254
+ - Network policy annotations
255
+
256
+ ### 6.3 Job Scheduling
257
+
258
+ `Pipeline` → `Job` hierarchy:
259
+ - Pipeline tracks overall state, steps, and resume point
260
+ - Job represents a single executable step
261
+ - Trust tier determines isolation level
262
+
263
+ ---
264
+
265
+ ## 7. External Sync Pipeline
266
+
267
+ Source: `packages/krate/core/src/external/`
268
+
269
+ ### 7.1 Full Pipeline Flow
270
+
271
+ ```
272
+ Webhook Ingest → HMAC Verify → Dedup → Normalize → Sync Event → State Update → Conflict Check → Write Intent
273
+ ```
274
+
275
+ ### 7.2 Step Details
276
+
277
+ | Step | Controller | Action |
278
+ |------|-----------|--------|
279
+ | 1. Ingest | WebhookController | Receive POST, extract signature header |
280
+ | 2. HMAC Verify | WebhookController | `sha256=` prefix comparison, timing-safe |
281
+ | 3. Dedup | WebhookController | Check deliveryId against store |
282
+ | 4. Normalize | WebhookController | Create `ExternalWebhookDelivery` record |
283
+ | 5. Sync Event | SyncController | Create `ExternalSyncEvent`, update watermark |
284
+ | 6. State Update | SyncController | Update `ExternalSyncState` phase |
285
+ | 7. Conflict Check | ConflictController | Compare local vs external, create `ExternalSyncConflict` if diverged |
286
+ | 8. Write Intent | WriteController | Queue `ExternalWriteIntent` if write-back needed |
287
+
288
+ ### 7.3 Conflict Resolution Strategies
289
+
290
+ - `local-wins` — Keep local version
291
+ - `remote-wins` — Accept external version
292
+ - `manual` — Create conflict record for human resolution
293
+ - `merge` — Attempt field-level merge
294
+
295
+ ---
296
+
297
+ ## 8. MCP Protocol
298
+
299
+ Source: `packages/krate/cli/src/mcp-server.js`
300
+
301
+ ### 8.1 Tools (14)
302
+
303
+ | Tool | Description | Required Inputs |
304
+ |------|-------------|-----------------|
305
+ | `krate_list_resources` | List resources of a given kind | `kind` |
306
+ | `krate_get_resource` | Get single resource | `kind`, `name` |
307
+ | `krate_apply_resource` | Create or update resource | `resource` (object) |
308
+ | `krate_delete_resource` | Delete a resource | `kind`, `name` |
309
+ | `krate_snapshot` | Full org runtime snapshot | (none) |
310
+ | `krate_search` | Search resources by query | `query` |
311
+ | `krate_list_stacks` | List agent stacks | (none) |
312
+ | `krate_create_stack` | Create AgentStack | `name`, `org` |
313
+ | `krate_dispatch_agent` | Dispatch an agent run | `stackRef` |
314
+ | `krate_list_secrets` | List AgentSecretGrant resources | `org` (optional) |
315
+ | `krate_create_secret` | Create AgentSecretGrant | `name`, `org`, `agentRef`, `secretRef` |
316
+ | `krate_sync_external` | Trigger external sync | `bindingName`, `kind`, `localName` |
317
+ | `krate_resolve_conflict` | Resolve sync conflict | `conflictName`, `strategy` |
318
+ | `krate_audit_query` | Query audit events | (all optional: org, action, since, until, limit, offset) |
319
+
320
+ ### 8.2 Prompts (3)
321
+
322
+ | Prompt | Description |
323
+ |--------|-------------|
324
+ | `krate_workspace_setup` | Guide for setting up a new krate workspace |
325
+ | `krate_stack_config` | Help configuring an agent stack |
326
+ | `krate_troubleshoot` | Diagnose common krate issues |
327
+
328
+ ### 8.3 Resources (2)
329
+
330
+ | URI | Name | MIME Type |
331
+ |-----|------|-----------|
332
+ | `krate://snapshot` | Workspace Snapshot | application/json |
333
+ | `krate://stacks` | Agent Stacks | application/json |
334
+
335
+ ---
336
+
337
+ ## 9. CLI Commands
338
+
339
+ Source: `packages/krate/cli/src/index.js`, `packages/krate/core/CLAUDE.md`
340
+
341
+ | Command | Description | Key Options |
342
+ |---------|-------------|-------------|
343
+ | `krate serve` | Start HTTP API server | `--port 3080` |
344
+ | `krate mcp` | Start MCP server over stdio | — |
345
+ | `krate status` | Show workspace status | `--org`, `--json` |
346
+ | `krate stacks` | List agent stacks | `--org`, `--json` |
347
+ | `krate dispatch` | Dispatch an agent run | `--stack`, `--repo`, `--ref` |
348
+ | `krate apply` | Apply resource from file | `--file`, `--org` |
349
+ | `krate get` | Get resource by kind/name | `kind`, `name`, `--org` |
350
+ | `krate list` | List resources by kind | `kind`, `--org`, `--json` |
351
+ | `krate delete` | Delete resource | `kind`, `name`, `--org` |
352
+ | `krate version` | Show CLI version | — |
package/docs/todos.md ADDED
@@ -0,0 +1,4 @@
1
+ https://krate-staging.a5c.ai/api/orgs/default/policy-reports shows: Kyverno CRDs are not installed or are not readable by the Krate service account - helm should install everything needed.
2
+
3
+ ❯ refactor the C:\Users\tmusk\IdeaProjects\babysitter\packages\krate\web to 3 packages , krate\sdk, krate\web and krate\cli (web and cli
4
+ should depend on sdk), the sdk is the client sdk. the cli should have a command to run itself as an mcp server.