@sudoke/kernel 0.0.0-stage → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +29 -4
- package/src/auth.ts +125 -0
- package/src/gate.ts +710 -0
- package/src/index.ts +26 -0
- package/src/mcp.ts +154 -0
- package/src/policy.ts +60 -0
- package/src/projections.ts +115 -0
- package/src/protocol.ts +51 -0
- package/src/queries.ts +176 -0
- package/src/registry.ts +235 -0
- package/src/state.ts +135 -0
- package/src/storage.ts +208 -0
- package/src/types.ts +121 -0
- package/src/visibility.ts +97 -0
- package/README.md +0 -3
package/src/types.ts
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import type { ZodType } from 'zod'
|
|
2
|
+
|
|
3
|
+
/** Role name — the app defines and registers its vocabulary (registerRoles). The kernel knows nothing about role semantics */
|
|
4
|
+
export type Role = string
|
|
5
|
+
|
|
6
|
+
/** Recovery action classification — the value of recovery.action in refusal responses. The common protocol explains each action's meaning */
|
|
7
|
+
export type RecoveryAction = 'refresh' | 'fix_input' | 'reauthenticate' | 'retry' | 'stop'
|
|
8
|
+
|
|
9
|
+
/** Next-step guidance after a refusal — the error-code definition provides the default action; the throw site only adds extras such as query */
|
|
10
|
+
export interface RecoveryHint {
|
|
11
|
+
action?: RecoveryAction
|
|
12
|
+
/** Query name (a registered query) to re-read when the action is refresh — e.g. 'portfolio' */
|
|
13
|
+
query?: string
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Error-code definition — an entry of the registry (registerErrorCodes). The sentence (reason) may change; the code stays stable */
|
|
17
|
+
export interface ErrorCodeDefinition {
|
|
18
|
+
description: string
|
|
19
|
+
recovery: RecoveryAction
|
|
20
|
+
/** Whether refusals with this code are warnings that can be overridden with a force:true retry — a flag separate from the recovery action */
|
|
21
|
+
canForce?: boolean
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Identity that passed gate stages 1-2 (a human or their agent) */
|
|
25
|
+
export interface Identity {
|
|
26
|
+
userId: string
|
|
27
|
+
name: string
|
|
28
|
+
role: Role
|
|
29
|
+
/** Accessible business-target scope — interpretation belongs to the app policy */
|
|
30
|
+
scopes: string[]
|
|
31
|
+
/** Acting subject (app/agent) name for delegated execution — filled for delegation tokens */
|
|
32
|
+
act?: string
|
|
33
|
+
/** Delegation info — present only for agent tokens. Permissions are delegator permissions ∩ scopes */
|
|
34
|
+
delegation?: {
|
|
35
|
+
id: string
|
|
36
|
+
name: string
|
|
37
|
+
scopes: string[]
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface DomainEvent {
|
|
42
|
+
type: string
|
|
43
|
+
aggregate_type: string
|
|
44
|
+
aggregate_id: string
|
|
45
|
+
payload: Record<string, unknown>
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Command definition (the form). One entry of the command catalog.
|
|
50
|
+
* REST/MCP/CLI/docs are derived from this definition.
|
|
51
|
+
* Every hook that may touch storage (transition.current·precondition·invariants·execute) is
|
|
52
|
+
* asynchronous — the storage port is async, so hooks await their reads; targetOf stays synchronous
|
|
53
|
+
* (pure input extraction, no storage).
|
|
54
|
+
*/
|
|
55
|
+
export interface CommandDefinition<I = any, O = any> {
|
|
56
|
+
name: string
|
|
57
|
+
description: string
|
|
58
|
+
example?: string
|
|
59
|
+
/** Deprecation notice — exposed in the catalog so connecting agents learn the replacement */
|
|
60
|
+
deprecated?: string
|
|
61
|
+
allowedRoles: Role[]
|
|
62
|
+
/** Scope kind — 'none' skips scope checks; any other value is interpreted by the app policy */
|
|
63
|
+
scope: 'none' | (string & {})
|
|
64
|
+
/** Extracts the business-target id from the input — feeds the app policy scope check */
|
|
65
|
+
targetOf?: (input: I) => string | undefined
|
|
66
|
+
input: ZodType<I>
|
|
67
|
+
/** Output contract — the shape of result in a success response. The gate validates it before commit (violation = stage-8 refusal + rollback) */
|
|
68
|
+
output: ZodType<O>
|
|
69
|
+
/** Business error codes (registered in the domain registry) this command can raise — published in the catalog.
|
|
70
|
+
* Gate-common codes (schema, permissions, transitions — common to every command) are not listed here */
|
|
71
|
+
errors?: readonly string[]
|
|
72
|
+
/** State-transition declaration — enforced against the transition table (machine) registered in the kernel registry.
|
|
73
|
+
* Convention: if the input has a `to` (target status) field, only rules leading to that status are accepted
|
|
74
|
+
* (otherwise the first rule for this command from the current status applies) */
|
|
75
|
+
transition?: {
|
|
76
|
+
machine: string
|
|
77
|
+
command: string
|
|
78
|
+
current: (input: I) => Promise<{ id: string | null; status: string }>
|
|
79
|
+
}
|
|
80
|
+
precondition?: (input: I) => Promise<void>
|
|
81
|
+
invariants?: (input: I, identity: Identity) => Promise<void>
|
|
82
|
+
/** Pure by design: never mutate state directly, only return events. The kernel applies projections.
|
|
83
|
+
* result is checked against the output contract */
|
|
84
|
+
execute: (input: I, identity: Identity) => Promise<{ events: DomainEvent[]; result: O }>
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Stage names of the 9-stage gate — a fixed, published contract. GateError derives stageName from the
|
|
88
|
+
* stage number through this table, so a wrong name at a throw site can never reach responses or audits. */
|
|
89
|
+
export const STAGE_NAMES: readonly string[] = [
|
|
90
|
+
'registry', // 0
|
|
91
|
+
'identify', // 1
|
|
92
|
+
'delegation', // 2
|
|
93
|
+
'policy', // 3
|
|
94
|
+
'schema', // 4
|
|
95
|
+
'precondition', // 5
|
|
96
|
+
'invariant', // 6
|
|
97
|
+
'transition', // 7
|
|
98
|
+
'execute', // 8
|
|
99
|
+
]
|
|
100
|
+
|
|
101
|
+
/** A refusal with a stage number and a reason. Recorded as an audit event.
|
|
102
|
+
* Attaching code adds a stable identifier and recovery guidance to responses and audits
|
|
103
|
+
* (machines act on it without parsing sentences). */
|
|
104
|
+
export class GateError extends Error {
|
|
105
|
+
code?: string
|
|
106
|
+
recovery?: RecoveryHint
|
|
107
|
+
stageName: string
|
|
108
|
+
constructor(
|
|
109
|
+
public stage: number,
|
|
110
|
+
/** @deprecated derived from the stage number — whenever the stage is in STAGE_NAMES this argument is
|
|
111
|
+
* ignored and the table value is published (I6 fixed contract); kept only as a fallback for unknown numbers */
|
|
112
|
+
stageName: string,
|
|
113
|
+
message: string,
|
|
114
|
+
meta?: { code?: string; recovery?: RecoveryHint },
|
|
115
|
+
) {
|
|
116
|
+
super(message)
|
|
117
|
+
this.stageName = STAGE_NAMES[stage] ?? stageName
|
|
118
|
+
if (meta?.code !== undefined) this.code = meta.code
|
|
119
|
+
if (meta?.recovery !== undefined) this.recovery = meta.recovery
|
|
120
|
+
}
|
|
121
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Permission visibility — the single derivation that decides which registered commands·queries·
|
|
3
|
+
* transition rules a given identity may be told about. The gate enforces permissions at run time
|
|
4
|
+
* (stage 2 delegation · stage 3 policy); this module answers the catalog-side question "what may
|
|
5
|
+
* this identity see in its manual?" using the SAME predicates, shared by construction:
|
|
6
|
+
*
|
|
7
|
+
* - roleAllowsCommand·delegationScopeEntries are the gate's own checks, extracted as pure
|
|
8
|
+
* functions so the gate and every catalog surface (REST /api/catalog · MCP catalog tool · MCP
|
|
9
|
+
* tool list) can never drift apart.
|
|
10
|
+
* - Derivation is read-only: it inspects definitions and the identity object only — no targetOf,
|
|
11
|
+
* no app-policy calls, no storage reads, no command execution, no dry-run, no audit. Building
|
|
12
|
+
* a catalog for any identity is side-effect free.
|
|
13
|
+
*
|
|
14
|
+
* The kernel knows no role names or business rules: role vocabulary and scope-kind meaning stay
|
|
15
|
+
* with the app (registerRoles · app policy). Delegation target restrictions surface the raw scope
|
|
16
|
+
* suffixes — interpreting what a target names is the reader's (app policy's) job.
|
|
17
|
+
*/
|
|
18
|
+
import type { CommandDefinition, Identity, Role } from './types.js'
|
|
19
|
+
import type { TransitionRule } from './registry.js'
|
|
20
|
+
import { allCommands, allTransitionMachines, catalogMeta } from './registry.js'
|
|
21
|
+
import { allQueries, type QueryDefinition } from './queries.js'
|
|
22
|
+
|
|
23
|
+
/** Stage-3 role predicate — the gate refuses with its own message when this returns false */
|
|
24
|
+
export function roleAllowsCommand(def: CommandDefinition<any>, role: Role): boolean {
|
|
25
|
+
return def.allowedRoles.includes(role)
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Scope entries attached to a command ('*' or an exact name match) — the selection half of the
|
|
29
|
+
* gate's delegation check (G-05: entries of other commands never mix in). Target-restricted
|
|
30
|
+
* entries ('cmd:target') are included as-is; what a target refers to is the app policy's business */
|
|
31
|
+
export function delegationScopeEntries(scopes: readonly string[], commandName: string): string[] {
|
|
32
|
+
return scopes.filter((sc) => {
|
|
33
|
+
const cmd = sc.includes(':') ? sc.slice(0, sc.indexOf(':')) : sc
|
|
34
|
+
return cmd === '*' || cmd === commandName
|
|
35
|
+
})
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Target restriction attached to a visible command — how the catalog says "allowed, but not everywhere" */
|
|
39
|
+
export type CommandRestriction =
|
|
40
|
+
/** scope kind ≠ 'none': every call's target is re-approved by the app policy at run time */
|
|
41
|
+
| { type: 'target-policy' }
|
|
42
|
+
/** the delegation covers only these targets (raw scope suffixes, interpreted by the app policy) */
|
|
43
|
+
| { type: 'delegation-targets'; targets: string[] }
|
|
44
|
+
|
|
45
|
+
export type CommandAccess = { visible: false } | { visible: true; restriction?: CommandRestriction }
|
|
46
|
+
|
|
47
|
+
/** Whether (and under what restriction) an identity may be told about a command. Pure — no input,
|
|
48
|
+
* no targetOf, no policy call: a delegation with only target-restricted entries is announced as
|
|
49
|
+
* restricted rather than proven per-target (proving needs an input; the gate re-checks at execution) */
|
|
50
|
+
export function commandAccessOf(def: CommandDefinition<any>, identity: Identity | null): CommandAccess {
|
|
51
|
+
if (!identity) return { visible: false }
|
|
52
|
+
if (!roleAllowsCommand(def, identity.role)) return { visible: false }
|
|
53
|
+
if (identity.delegation) {
|
|
54
|
+
const entries = delegationScopeEntries(identity.delegation.scopes, def.name)
|
|
55
|
+
if (entries.length === 0) return { visible: false }
|
|
56
|
+
if (!entries.some((sc) => !sc.includes(':')))
|
|
57
|
+
return {
|
|
58
|
+
visible: true,
|
|
59
|
+
restriction: { type: 'delegation-targets', targets: entries.map((sc) => sc.slice(sc.indexOf(':') + 1)) },
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return def.scope !== 'none' ? { visible: true, restriction: { type: 'target-policy' } } : { visible: true }
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Personal catalog guidance — catalogMeta() entries for the commands this identity may use,
|
|
66
|
+
* annotated with the target restriction. catalogMeta() and allCommands() walk the same ordered
|
|
67
|
+
* registry, so indexes pair 1:1. Deriving writes nothing (registry·ledger·audit untouched) */
|
|
68
|
+
export function visibleCatalogMeta(identity: Identity | null) {
|
|
69
|
+
const meta = catalogMeta()
|
|
70
|
+
return allCommands().flatMap((def, i) => {
|
|
71
|
+
const access = commandAccessOf(def, identity)
|
|
72
|
+
return access.visible
|
|
73
|
+
? [{ ...meta[i], ...(access.restriction ? { restriction: access.restriction } : {}) }]
|
|
74
|
+
: []
|
|
75
|
+
})
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Queries this identity may be told about — allowedRoles (omitted = open to every role, the
|
|
79
|
+
* historical behavior) is the same declaration executeQuery enforces */
|
|
80
|
+
export function visibleQueriesFor(identity: Identity | null): QueryDefinition[] {
|
|
81
|
+
if (!identity) return allQueries().filter((q) => q.public === true)
|
|
82
|
+
return allQueries().filter((q) => !q.allowedRoles || q.allowedRoles.includes(identity.role))
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Transition rules this identity may act on — a rule stays when its command is visible to the
|
|
86
|
+
* identity AND the rule's roles include the identity's role. Machines with no remaining rule are
|
|
87
|
+
* dropped entirely (an empty table would read as "everything forbidden" instead of "nothing to say") */
|
|
88
|
+
export function visibleTransitionMachinesFor(identity: Identity | null): Record<string, readonly TransitionRule[]> {
|
|
89
|
+
if (!identity) return {}
|
|
90
|
+
const visible = new Set(allCommands().filter((def) => commandAccessOf(def, identity).visible).map((def) => def.name))
|
|
91
|
+
const out: Record<string, readonly TransitionRule[]> = {}
|
|
92
|
+
for (const [machine, rules] of Object.entries(allTransitionMachines())) {
|
|
93
|
+
const kept = rules.filter((r) => visible.has(r.command) && r.roles.includes(identity!.role))
|
|
94
|
+
if (kept.length > 0) out[machine] = kept
|
|
95
|
+
}
|
|
96
|
+
return out
|
|
97
|
+
}
|
package/README.md
DELETED