Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# 0021: Publish-gated packages; no in-process composition runtime

- **Status:** accepted
- **Date:** 2026-08-18

## Context

A preprint on spatiotemporal composability (Cordis / Koishi) describes
in-process plugin load/unload, reactive dependent deactivation, and live
self-modification of an agent harness. Those ideas map onto Kody's packages,
jobs, services, and community listings, so they needed an explicit decision
against project intent (personal software, per-user isolation, compact MCP
surface, Workers isolates). Versioning and auto-republish of dependents are
already declined in [0001](./0001-no-package-versioning.md). Session-trace
self-improvement is declined in [0008](./0008-declined-adlc-primitives.md).

## Decision

Keep Kody publish-gated and snapshot-isolated:

- Agents create and publish packages under existing checks and secret/host
approval. They do not hot-patch a running harness or skip those gates.
- Do not adopt an in-process fiber/HMR/context-proxy composition runtime. Worker
Loader isolates plus durable surfaces are the composition model.
- Do not add a package-level disable primitive. Jobs and webhooks already have
per-surface enable flags; `hidden` is search visibility; full stop is delete.
- Do not deactivate or auto-republish dependents when a provider changes or is
deleted. Publish already reports stale static snapshots for the agent to
decide.
- Ad hoc `execute` stays ambient. Packages remain the declared-authority unit
(`kody.secretMounts`, host approval, integration allowlists,
`kody.dependencies`).

## Consequences

- Package delete is the inverse of a package existing. Closing leftover
community listings, minted webhooks, and service DO state is cleanup of that
inverse, not a new lifecycle.
- Repo checks reject `kody.dependencies` cycles at publish time, including
reachable cyclic subgraphs the package under check depends on. A saved sibling
whose published manifest cannot load fails the dependency check instead of
being treated as a leaf. There is no runtime that leaves cyclic packages
"permanently inactive."
- Revisit only if a concrete user need requires live in-process composition or a
package-wide kill switch that is not delete.
1 change: 1 addition & 0 deletions docs/contributing/decisions/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,4 @@ behavior (see [documentation principles](../documentation.md)).
- [0018 — Inbound CLA for external contributions to this repository](./0018-inbound-cla.md)
- [0019 — Self-hosted Nx remote cache (not Nx Cloud)](./0019-self-hosted-nx-remote-cache.md)
- [0020 — Repo sessions spill Workspace objects to R2; do not adopt `@cloudflare/computer`](./0020-repo-session-workspace-r2-not-computer.md)
- [0021 — Publish-gated packages; no in-process composition runtime](./0021-publish-gated-package-composition.md)
3 changes: 2 additions & 1 deletion docs/contributing/packages-and-manifests.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ Use `package.json` as the canonical source of truth for saved package metadata.
- `kody.tags` — search tags
- `kody.searchText` — optional longer search text beyond the short description
- `kody.dependencies` — direct static saved package dependencies imported via
`kody:@...`
`kody:@...`. Repo checks reject cycles in this graph at publish time, and fail
closed if a reachable saved package manifest cannot be loaded.
- `kody.secretMounts` — optional package-scoped secret mount declarations
- `kody.app` — optional hosted package app config
- `kody.services` — optional package-owned service runtimes
Expand Down
7 changes: 7 additions & 0 deletions docs/guides/package-lifecycle.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,13 @@ Keep the module focused and return structured evidence. Do not treat the
ephemeral module as the durable source for behavior that must be maintained,
reused, or evolved.

Ad hoc `execute` runs with the signed-in user's ambient authority: it can call
discovered capabilities through `kody`. A saved package is the
declared-authority unit. Secret mounts, host approval, integration allowlists,
and `kody.dependencies` are the request, and agents cannot widen those. Outbound
emissions (email, paid APIs, third-party writes) are not invertible; use a
package `dryRun` and fresh user confirmation before a live mutation.

### Fork a close community package before creating

Community listings are excluded from general `search`. When you need durable
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
import { expect, test, vi } from 'vitest'

const mocks = vi.hoisted(() => ({
listSavedPackagesByUserId: vi.fn(),
loadPackageManifestBySourceId: vi.fn(),
}))

vi.mock('#worker/package-registry/repo.ts', () => ({
listSavedPackagesByUserId: (...args: Array<unknown>) =>
mocks.listSavedPackagesByUserId(...args),
}))

vi.mock('#worker/package-registry/source.ts', () => ({
loadPackageManifestBySourceId: (...args: Array<unknown>) =>
mocks.loadPackageManifestBySourceId(...args),
}))

import {
findStaticKodyDependencyCycle,
formatStaticKodyDependencyCycleMessage,
formatStaticKodyDependencyLoadFailureMessage,
loadReachableStaticKodyDependencyEdges,
} from './static-dependency-cycles.ts'

test('findStaticKodyDependencyCycle reports reachable loops and ignores unreachable ones', () => {
expect(
findStaticKodyDependencyCycle({
rootPackageName: '@scope/a',
edges: new Map([
['@scope/a', ['@scope/b']],
['@scope/b', ['@scope/a']],
['@scope/c', ['@scope/d']],
]),
}),
).toEqual(['@scope/a', '@scope/b', '@scope/a'])
expect(
findStaticKodyDependencyCycle({
rootPackageName: '@scope/c',
edges: new Map([
['@scope/c', ['@scope/d']],
['@scope/d', ['@scope/e']],
['@scope/e', ['@scope/c']],
]),
}),
).toEqual(['@scope/c', '@scope/d', '@scope/e', '@scope/c'])
expect(
findStaticKodyDependencyCycle({
rootPackageName: '@scope/c',
edges: new Map([
['@scope/c', ['@scope/a']],
['@scope/a', ['@scope/b']],
['@scope/b', ['@scope/a']],
]),
}),
).toEqual(['@scope/a', '@scope/b', '@scope/a'])
expect(
findStaticKodyDependencyCycle({
rootPackageName: '@scope/c',
edges: new Map([
['@scope/a', ['@scope/b']],
['@scope/b', ['@scope/a']],
['@scope/c', ['@scope/d']],
]),
}),
).toBeNull()
expect(
findStaticKodyDependencyCycle({
rootPackageName: '@scope/missing',
edges: new Map([['@scope/a', ['@scope/b']]]),
}),
).toBeNull()
expect(
formatStaticKodyDependencyCycleMessage([
'@scope/a',
'@scope/b',
'@scope/a',
]),
).toBe(
'package.json#kody.dependencies forms a cycle: @scope/a -> @scope/b -> @scope/a.',
)
expect(
formatStaticKodyDependencyLoadFailureMessage({
packageName: '@scope/c',
cause: new Error('manifest unavailable'),
}),
).toBe(
'Could not load the saved package manifest for @scope/c while checking package.json#kody.dependencies: manifest unavailable.',
)
})

test('loadReachableStaticKodyDependencyEdges walks published sibling manifests and treats missing packages as sinks', async () => {
mocks.listSavedPackagesByUserId.mockReset()
mocks.loadPackageManifestBySourceId.mockReset()
mocks.listSavedPackagesByUserId.mockResolvedValue([
{ name: '@scope/b', sourceId: 'source-b' },
{ name: '@scope/c', sourceId: 'source-c' },
])
mocks.loadPackageManifestBySourceId.mockImplementation(
async (input: { sourceId: string }) => {
if (input.sourceId === 'source-b') {
return {
manifest: { kody: { dependencies: ['@scope/c', '@scope/missing'] } },
}
}
return { manifest: { kody: { dependencies: [] } } }
},
)

const graph = await loadReachableStaticKodyDependencyEdges({
env: { APP_DB: {} } as Env,
baseUrl: 'https://example.test',
userId: 'user-1',
rootPackageName: '@scope/a',
rootDependencies: ['@scope/b', ' @scope/b '],
})

expect(graph).toMatchObject({ ok: true })
if (!graph.ok) throw new Error('expected loaded edges')
expect(graph.edges.get('@scope/a')).toEqual(['@scope/b'])
expect(graph.edges.get('@scope/b')).toEqual(['@scope/c', '@scope/missing'])
expect(graph.edges.get('@scope/c')).toEqual([])
expect(graph.edges.get('@scope/missing')).toEqual([])
expect(mocks.loadPackageManifestBySourceId).toHaveBeenCalledTimes(2)
expect(
findStaticKodyDependencyCycle({
rootPackageName: '@scope/a',
edges: graph.edges,
}),
).toBeNull()
})

test('loadReachableStaticKodyDependencyEdges fails closed when a saved package manifest cannot load', async () => {
mocks.listSavedPackagesByUserId.mockReset()
mocks.loadPackageManifestBySourceId.mockReset()
mocks.listSavedPackagesByUserId.mockResolvedValue([
{ name: '@scope/b', sourceId: 'source-b' },
{ name: '@scope/c', sourceId: 'source-c' },
])
mocks.loadPackageManifestBySourceId.mockImplementation(
async (input: { sourceId: string }) => {
if (input.sourceId === 'source-b') {
return {
manifest: { kody: { dependencies: ['@scope/c'] } },
}
}
throw new Error('manifest unavailable')
},
)

await expect(
loadReachableStaticKodyDependencyEdges({
env: { APP_DB: {} } as Env,
baseUrl: 'https://example.test',
userId: 'user-1',
rootPackageName: '@scope/a',
rootDependencies: ['@scope/b'],
}),
).resolves.toEqual({
ok: false,
message:
'Could not load the saved package manifest for @scope/c while checking package.json#kody.dependencies: manifest unavailable.',
})
})
117 changes: 117 additions & 0 deletions packages/worker/src/package-registry/static-dependency-cycles.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
import { getErrorMessage } from '@kody-internal/shared/error-message.ts'
import { listSavedPackagesByUserId } from '#worker/package-registry/repo.ts'
import { loadPackageManifestBySourceId } from '#worker/package-registry/source.ts'

/**
* Detect cycles in static `kody:@` / `package.json#kody.dependencies` graphs.
* Edges are package names (`@scope/leaf`). Missing nodes have no outgoing
* edges (an unpublished or platform-live dependency cannot close a user-local
* cycle). A saved package whose published manifest cannot load fails the
* graph walk instead of pretending it has no dependencies.
*/

export type LoadedStaticKodyDependencyEdges =
| { ok: true; edges: Map<string, Array<string>> }
| { ok: false; message: string }
export function findStaticKodyDependencyCycle(input: {
rootPackageName: string
edges: ReadonlyMap<string, ReadonlyArray<string>>
}): Array<string> | null {
const root = input.rootPackageName.trim()
if (!root) return null
const visiting = new Set<string>()
const visited = new Set<string>()
const path: Array<string> = []

function walk(packageName: string): Array<string> | null {
if (visiting.has(packageName)) {
const cycleStart = path.indexOf(packageName)
if (cycleStart === -1) return null
return [...path.slice(cycleStart), packageName]
}
if (visited.has(packageName)) return null
visiting.add(packageName)
path.push(packageName)
for (const dependency of input.edges.get(packageName) ?? []) {
const next = dependency.trim()
if (!next) continue
const cycle = walk(next)
if (cycle) return cycle

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cycle check rejects unrelated dependency loops

Medium Severity

findStaticKodyDependencyCycle returns the first back-edge cycle in the reachable graph, even when that loop never includes rootPackageName. Publish then fails for packages that only depend on an already-cyclic subgraph, instead of only when the package under check participates in or closes a cycle.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 938a20b. Configure here.

}
path.pop()
visiting.delete(packageName)
visited.add(packageName)
return null
}

return walk(root)
}

export function formatStaticKodyDependencyCycleMessage(
cycle: ReadonlyArray<string>,
) {
return `package.json#kody.dependencies forms a cycle: ${cycle.join(' -> ')}.`
}

export function formatStaticKodyDependencyLoadFailureMessage(input: {
packageName: string
cause: unknown
}) {
return `Could not load the saved package manifest for ${input.packageName} while checking package.json#kody.dependencies: ${getErrorMessage(input.cause)}.`
}

export async function loadReachableStaticKodyDependencyEdges(input: {
env: Env
baseUrl: string
userId: string
rootPackageName: string
rootDependencies: ReadonlyArray<string>
}): Promise<LoadedStaticKodyDependencyEdges> {
const edges = new Map<string, Array<string>>()
const rootDependencies = uniqueTrimmedNames(input.rootDependencies)
edges.set(input.rootPackageName, rootDependencies)
const savedPackages = await listSavedPackagesByUserId(input.env.APP_DB, {
userId: input.userId,
})
const savedByName = new Map(
savedPackages.map((savedPackage) => [savedPackage.name, savedPackage]),
)
const pending = [...rootDependencies]
while (pending.length > 0) {
const packageName = pending.pop()
if (!packageName || edges.has(packageName)) continue
const savedPackage = savedByName.get(packageName)
if (!savedPackage) {
edges.set(packageName, [])
continue
}
try {
const loaded = await loadPackageManifestBySourceId({
env: input.env,
baseUrl: input.baseUrl,
userId: input.userId,
sourceId: savedPackage.sourceId,
})
const dependencies = uniqueTrimmedNames(
loaded.manifest.kody.dependencies ?? [],
)
edges.set(packageName, dependencies)
pending.push(...dependencies)
} catch (cause) {
return {
ok: false,
message: formatStaticKodyDependencyLoadFailureMessage({
packageName,
cause,
}),
}
}
}
return { ok: true, edges }
}

function uniqueTrimmedNames(names: ReadonlyArray<string>) {
return Array.from(
new Set(names.map((name) => name.trim()).filter((name) => name.length > 0)),
)
}
Loading
Loading