Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
fix(playbooks): point the editor at the published step vocabulary
Beenu Arora8ee0aae0d935
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ea749a2ae..0254fb96b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,89 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Fixed++- **The playbook editor could author nine of the engine's twenty-two step+ types, and the build was green.** `apps/web/src/components/playbooks/types.ts`+ declared its own nine-member `StepType` union under a header comment+ claiming it mirrored `services/agents/app/playbook/models.py`, which+ declares twenty-two. The registry behind every form is keyed+ `Record<StepType, StepSchema>`, so exhaustiveness was satisfied against the+ *local* union and thirteen missing forms compiled cleanly; had it imported+ the union from `packages/types`, `Record` would have failed with thirteen+ missing keys. None of the fourteen files in the directory imported the+ published package. It now re-exports `StepType` from `@aisoc/types`, and the+ compiler named the gap.++ The thirteen forms are built: `block_ioc`, `osquery_live_query`,+ `disable_user`, `reset_password`, `revoke_session`, `force_mfa`,+ `kill_process`, `quarantine_file`, `run_av_scan`, `run_script`,+ `search_siem`, `create_notable_event`, and `approval`. Each collects what+ its executor in `services/actions` reads, and each governed verb's target+ field is keyed on the name `engine._resolve_target` actually looks for, so a+ saved step carries its own target rather than depending on the alert context+ happening to hold one. Nothing collects a credential — those are resolved+ per tenant from the connector vault at dispatch — and nothing offers a+ `dry_run` control, because the bridge does not read one.++ `approval` is presented, never offered. The engine records it in+ `_UNBRIDGEABLE` with a full reason, so the palette and the type dropdown+ filter on `execution !== 'unimplemented'` rather than on its name, an+ existing `approval` step still renders so an imported playbook can be read+ and fixed, and the inspector states that the engine fails the step closed+ and the run stops there.++- **`osquery_live_query` reported SUCCESS while running nothing.** Its handler+ returned an error dict when the osquery backend clients could not be+ imported — which is always, in the shipped agents image, because those+ clients live in `services/actions` — and a returned dict leaves the step+ status at SUCCESS. Reachable from the console the moment the editor could+ author the type, so it now raises `PermanentStepFailure` and fails closed.++- **Three more partial vocabularies in the same directory.** `stepColors.ts`+ held a second nine-entry `Record<StepType, …>`; `StepInspector` and+ `PlaybookEditor` each hard-coded a nine-member array. All three are derived+ from the registry now. `packHelpers.ts` mapped step types to integration+ badges as a `Record<string, …>` covering eighteen of twenty-two, so a+ playbook built from the other four claimed to use no integrations at all.++### Added++- **The playbook parity gate now reads every declaration of the step+ vocabulary, wherever it is.** `scripts/check_playbook_schema_parity.py`+ compared the engine against `packages/types/src/playbook.ts` and never+ opened `apps/web`; naming the editor's file here would have fixed that file+ and left the next one free. The TypeScript half is a scan: every `.ts` and+ `.tsx` file in the tree is parsed for literal collections of step-type+ names, and any collection overlapping the engine's vocabulary must either+ match it exactly or be a recorded subset with a reason, checked in both+ directions so an exemption that stops being needed fails the build. The+ editor's execution annotations are compared against the schema's+ `x-aisoc-execution` in both directions as well, so a surface cannot tell an+ author a step will run when the contract says it will not. `--list` prints+ what the scan credited, not only what it flagged, and the gate refuses to+ report agreement when it finds no declaration at all.++ Against `origin/main` it reports 56 disagreements across all five+ vocabularies; against this tree it credits five declarations, each complete.++ Two limits are stated rather than left implicit: a collection overlapping+ the vocabulary by fewer than two members is not treated as one, and a list+ derived at runtime is not a literal and is not seen — which is the shape the+ gate wants, because a derived list cannot drift. A file the reader cannot+ parse to the end is never silently skipped: it is checked for step-type+ names in its raw bytes first, and the gate refuses the tree if it finds any.++- **A WCAG AA sweep over all twenty-two inspector forms.** The labels in+ `SchemaForm` and `StepInspector` sat beside their controls with no+ association, requiredness was an `aria-hidden` asterisk, help text was+ unreferenced, and the error summary named fields it could not be reached+ from. Controls now carry ids, labels `htmlFor`, `aria-required`,+ `aria-invalid` and `aria-describedby`; errors are reported per field as well+ as in the summary; the condition and params groups are fieldsets. The sweep+ also caught `<ul role="alert">`, which is not an allowed role for a list and+ left its items without a list parent.+## [10.0.0] — 2026-09-25**Two ways for a control to be absent: not written, or written and notdiff --git a/apps/web/src/components/playbooks/PlaybookEditor.tsx b/apps/web/src/components/playbooks/PlaybookEditor.tsxindex b63300f99..80cfe5954 100644--- a/apps/web/src/components/playbooks/PlaybookEditor.tsx+++ b/apps/web/src/components/playbooks/PlaybookEditor.tsx@@ -24,21 +24,16 @@ import { PlaybookFlowCanvas } from './PlaybookFlowCanvas';import { StepInspector } from './StepInspector';import type { Playbook, PlaybookStep, StepType } from './types';import { STEP_TYPE_META } from './stepColors';-import { defaultParamsFor } from './stepSchemas';+import { AUTHORABLE_STEP_TYPES, defaultParamsFor } from './stepSchemas';import { ContextualActions } from '@/components/copilot/ContextualActions';import { useHistoryState } from '@/hooks/useHistoryState';-const STEP_TYPES: StepType[] = [- 'enrich',- 'investigate',- 'notify',- 'block_ip',- 'isolate_host',- 'create_ticket',- 'close_case',- 'http',- 'condition',-];+/**+ * What the palette offers. Derived from the registry, and filtered on+ * whether the engine can run the type rather than on its name — a step the+ * engine fails closed is not something to hand somebody a button for.+ */+const STEP_TYPES: readonly StepType[] = AUTHORABLE_STEP_TYPES;function generateId(): string {return Math.random().toString(36).slice(2, 10);diff --git a/apps/web/src/components/playbooks/SchemaForm.test.tsx b/apps/web/src/components/playbooks/SchemaForm.test.tsxindex ee95846c4..f39a2f30f 100644--- a/apps/web/src/components/playbooks/SchemaForm.test.tsx+++ b/apps/web/src/components/playbooks/SchemaForm.test.tsx@@ -53,7 +53,7 @@ import {} from './stepSchemas';describe('SchemaForm — rendering', () => {- it('renders all required fields with required asterisks', () => {+ it('marks required fields as required on the control, not just visually', () => {const onChange = vi.fn();render(<SchemaForm@@ -63,12 +63,17 @@ describe('SchemaForm — rendering', () => {/>,);- // Both fields on block_ip are required.- expect(screen.getByText(/IP address field/i)).toBeInTheDocument();- expect(screen.getByText(/Duration \(seconds\)/i)).toBeInTheDocument();- // Two asterisks for two required fields.- const asterisks = screen.getAllByText('*');- expect(asterisks).toHaveLength(2);+ // Both fields on block_ip are required. Found by label, which also+ // asserts the label is associated with its control — it used to be a+ // `<label>` sitting next to the input with no `htmlFor`, so a screen+ // reader announced an unnamed text box.+ for (const label of [/IP address field/i, /Duration \(seconds\)/i]) {+ const control = screen.getByLabelText(label);+ expect(control).toBeInTheDocument();+ // The requiredness has to reach assistive technology. An `aria-hidden`+ // asterisk is a cue for sighted users only.+ expect(control).toHaveAttribute('aria-required', 'true');+ }});it('renders a select with the configured options', () => {@@ -109,12 +114,19 @@ describe('SchemaForm — rendering', () => {schema={STEP_SCHEMAS.block_ip}value={{}}onChange={vi.fn()}- validationErrors={['IP address field is required.']}+ validationErrors={[+ { key: 'ip_field', message: 'IP address field is required.' },+ ]}/>,);expect(screen.getByRole('alert'),).toHaveTextContent(/IP address field is required/i);+ // The error is also reachable from the control it belongs to, which a+ // summary list at the foot of the form is not.+ expect(screen.getByLabelText(/IP address field/i)).toHaveAccessibleDescription(+ /IP address field is required/i,+ );});it('warns about extra params not modelled by the schema', () => {diff --git a/apps/web/src/components/playbooks/SchemaForm.tsx b/apps/web/src/components/playbooks/SchemaForm.tsxindex 4f452dbec..08107effa 100644--- a/apps/web/src/components/playbooks/SchemaForm.tsx+++ b/apps/web/src/components/playbooks/SchemaForm.tsx@@ -9,47 +9,79 @@* longer ship malformed playbooks (the canonical failure mode pre-WS-F4).** Each field knows its kind (string, number, boolean, select, env-ref,- * jsonpath, textarea) and renders the matching control. Unknown keys- * already present in `params` are surfaced under an "Advanced (raw JSON)"- * disclosure so power-users can still edit anything the schema does not- * model.+ * jsonpath, textarea, string-list) and renders the matching control. Unknown+ * keys already present in `params` are surfaced under an "Advanced (raw+ * JSON)" disclosure so power-users can still edit anything the schema does+ * not model.+ *+ * Accessibility+ * -------------+ * Every control carries an `id`, its label a matching `htmlFor`, and its help+ * text and error are referenced through `aria-describedby`. The labels used+ * to be `<label>` elements sitting next to their inputs with no association+ * at all, so a screen reader announced "edit text, blank" for all four fields+ * on a notify step, and the required marker was an `aria-hidden` asterisk+ * conveying requiredness to sighted users only. Errors are now reported per+ * field as well as in the summary, because a list at the bottom of a form+ * saying "Duration is required" does not tell you which control to move to.*/-import React, { useMemo, useState } from 'react';-import type { FieldDescriptor, StepSchema } from './stepSchemas';+import React, { useId, useMemo, useState } from 'react';+import type { FieldDescriptor, StepParamError, StepSchema } from './stepSchemas';interface SchemaFormProps {schema: StepSchema;value: Record<string, unknown>;onChange: (next: Record<string, unknown>) => void;readOnly?: boolean;- validationErrors?: readonly string[];+ validationErrors?: readonly StepParamError[];+}++interface ControlProps {+ field: FieldDescriptor;+ id: string;+ value: unknown;+ onChange: (v: unknown) => void;+ readOnly: boolean;+ describedBy?: string;+ invalid: boolean;}-function renderControl(- field: FieldDescriptor,- value: unknown,- onChange: (v: unknown) => void,- readOnly: boolean,-): React.ReactNode {+function renderControl({+ field,+ id,+ value,+ onChange,+ readOnly,+ describedBy,+ invalid,+}: ControlProps): React.ReactNode {const baseClass ='w-full bg-gray-800 border border-gray-700 rounded px-3 py-1.5 text-white text-sm focus:outline-none focus:border-blue-500 disabled:opacity-60';+ const shared = {+ id,+ disabled: readOnly,+ 'aria-describedby': describedBy,+ 'aria-required': field.required || undefined,+ 'aria-invalid': invalid || undefined,+ } as const;switch (field.kind) {case 'textarea':return (<textarea+ {...shared}rows={4}placeholder={field.placeholder}value={typeof value === 'string' ? value : ''}onChange={(e) => onChange(e.target.value)}- disabled={readOnly}className={`${baseClass} font-mono text-xs`}/>);case 'number':return (<input+ {...shared}type="number"placeholder={field.placeholder}value={value === undefined || value === null ? '' : String(value)}@@ -62,28 +94,24 @@ function renderControl(onChange(Number.isFinite(n) ? n : raw);}}}- disabled={readOnly}className={baseClass}/>);case 'boolean':return (- <label className="inline-flex items-center gap-2 text-gray-300">- <input- type="checkbox"- checked={Boolean(value)}- onChange={(e) => onChange(e.target.checked)}- disabled={readOnly}- />- <span className="text-xs">Enabled</span>- </label>+ <input+ {...shared}+ type="checkbox"+ checked={Boolean(value)}+ onChange={(e) => onChange(e.target.checked)}+ />);case 'select':return (<select+ {...shared}value={typeof value === 'string' ? value : ''}onChange={(e) => onChange(e.target.value || undefined)}- disabled={readOnly}className={baseClass}><option value="">— select —</option>@@ -94,25 +122,35 @@ function renderControl())}</select>);- case 'env_ref':+ case 'string_list':+ // Stored as an array because that is what the handler reads; edited as+ // a comma-separated line because a repeating-row control for two+ // hostnames is more chrome than it is worth.return (<input+ {...shared}type="text"placeholder={field.placeholder}- value={typeof value === 'string' ? value : ''}- onChange={(e) => onChange(e.target.value || undefined)}- disabled={readOnly}+ value={Array.isArray(value) ? value.join(', ') : typeof value === 'string' ? value : ''}+ onChange={(e) => {+ const parts = e.target.value+ .split(',')+ .map((part) => part.trim())+ .filter(Boolean);+ onChange(parts.length ? parts : undefined);+ }}className={`${baseClass} font-mono`}/>);+ case 'env_ref':case 'jsonpath':return (<input+ {...shared}type="text"placeholder={field.placeholder}value={typeof value === 'string' ? value : ''}onChange={(e) => onChange(e.target.value || undefined)}- disabled={readOnly}className={`${baseClass} font-mono`}/>);@@ -120,11 +158,11 @@ function renderControl(default:return (<input+ {...shared}type="text"placeholder={field.placeholder}value={typeof value === 'string' ? value : ''}onChange={(e) => onChange(e.target.value || undefined)}- disabled={readOnly}className={baseClass}/>);@@ -138,6 +176,7 @@ export function SchemaForm({readOnly = false,validationErrors,}: SchemaFormProps) {+ const formId = useId();const knownKeys = useMemo(() => new Set(schema.fields.map((f) => f.key)),[schema],@@ -146,6 +185,15 @@ export function SchemaForm({() => Object.keys(value).filter((k) => !knownKeys.has(k)),[value, knownKeys],);+ const errorsByKey = useMemo(() => {+ const byKey = new Map<string, string[]>();+ for (const error of validationErrors ?? []) {+ if (!error.key) continue;+ byKey.set(error.key, [...(byKey.get(error.key) ?? []), error.message]);+ }+ return byKey;+ }, [validationErrors]);+ const stepLevelErrors = (validationErrors ?? []).filter((e) => !e.key);const [showRaw, setShowRaw] = useState(false);const [rawDraft, setRawDraft] = useState<string>(() =>@@ -165,47 +213,87 @@ export function SchemaForm({if (schema.fields.length === 0 && extraKeys.length === 0) {return (- <div className="text-xs text-gray-500 italic">- {schema.type === 'condition'- ? 'Conditions have no params — configure the predicate via the Condition section above.'- : 'No parameters for this step type.'}+ <div className="space-y-2">+ <p className="text-xs text-gray-500 italic">+ {schema.type === 'condition'+ ? 'Conditions have no params — configure the predicate via the Condition section above.'+ : 'No parameters for this step type.'}+ </p>+ {stepLevelErrors.length > 0 && (+ // `role="alert"` on the wrapper, not on the list: the role replaces+ // the element's own semantics, so a `<ul role="alert">` stops being+ // a list and its `<li>` children are left without a list parent.+ <div role="alert" className="text-xs text-red-400">+ <ul className="space-y-1">+ {stepLevelErrors.map((error) => (+ <li key={error.message}>{error.message}</li>+ ))}+ </ul>+ </div>+ )}</div>);}return (<div className="space-y-3">- {schema.fields.map((field) => (- <div key={field.key}>- <label className="block text-gray-400 text-xs mb-1">- {field.label}- {field.required && (- <span className="text-red-400 ml-1" aria-hidden>- *- </span>+ {schema.fields.map((field) => {+ const controlId = `${formId}-${field.key}`;+ const helpId = field.help ? `${controlId}-help` : undefined;+ const fieldErrors = errorsByKey.get(field.key) ?? [];+ const errorId = fieldErrors.length ? `${controlId}-error` : undefined;+ const describedBy =+ [errorId, helpId].filter(Boolean).join(' ') || undefined;++ return (+ <div key={field.key}>+ <label+ htmlFor={controlId}+ className="block text-gray-400 text-xs mb-1"+ >+ {field.label}+ {field.required && (+ // Spelled out rather than a bare asterisk: the marker is the+ // only cue a non-sighted user gets from the label text, and+ // `aria-required` on the control alone is not announced by+ // every combination of browser and screen reader.+ <span className="text-red-400 ml-1">(required)</span>+ )}+ </label>+ {renderControl({+ field,+ id: controlId,+ value: value[field.key],+ onChange: (v) => setField(field.key, v),+ readOnly,+ describedBy,+ invalid: fieldErrors.length > 0,+ })}+ {fieldErrors.length > 0 && (+ <p id={errorId} className="text-[11px] text-red-400 mt-1">+ {fieldErrors.join(' ')}+ </p>)}- </label>- {renderControl(- field,- value[field.key],- (v) => setField(field.key, v),- readOnly,- )}- {field.help && (- <div className="text-[11px] text-gray-500 mt-1">{field.help}</div>- )}- </div>- ))}+ {field.help && (+ <p id={helpId} className="text-[11px] text-gray-500 mt-1">+ {field.help}+ </p>+ )}+ </div>+ );+ })}{validationErrors && validationErrors.length > 0 && (- <ul+ <divrole="alert"- className="text-xs text-red-400 bg-red-950/30 border border-red-900 rounded p-2 space-y-1"+ className="text-xs text-red-400 bg-red-950/30 border border-red-900 rounded p-2">- {validationErrors.map((msg) => (- <li key={msg}>• {msg}</li>- ))}- </ul>+ <ul className="space-y-1">+ {validationErrors.map((error) => (+ <li key={`${error.key ?? ''}:${error.message}`}>• {error.message}</li>+ ))}+ </ul>+ </div>)}{extraKeys.length > 0 && (@@ -220,6 +308,8 @@ export function SchemaForm({<div className="border-t border-gray-800 pt-3"><buttontype="button"+ aria-expanded={showRaw}+ aria-controls={`${formId}-raw`}onClick={() => {setRawDraft(JSON.stringify(value, null, 2));setRawError(null);@@ -230,10 +320,16 @@ export function SchemaForm({{showRaw ? '▾' : '▸'} Advanced (raw JSON)</button>{showRaw && (- <div className="mt-2">+ <div className="mt-2" id={`${formId}-raw`}>+ <label htmlFor={`${formId}-raw-input`} className="sr-only">+ Raw step parameters as JSON+ </label><textarea+ id={`${formId}-raw-input`}rows={6}value={rawDraft}+ aria-invalid={rawError ? true : undefined}+ aria-describedby={rawError ? `${formId}-raw-error` : undefined}onChange={(e) => {setRawDraft(e.target.value);try {@@ -258,7 +354,9 @@ export function SchemaForm({className="w-full bg-gray-900 border border-gray-700 rounded px-3 py-2 text-green-400 font-mono text-xs focus:outline-none focus:border-blue-500 disabled:opacity-60"/>{rawError && (- <div className="text-xs text-red-400 mt-1">{rawError}</div>+ <p id={`${formId}-raw-error`} className="text-xs text-red-400 mt-1">+ {rawError}+ </p>)}</div>)}diff --git a/apps/web/src/components/playbooks/StepExecutionNotice.tsx b/apps/web/src/components/playbooks/StepExecutionNotice.tsxnew file mode 100644index 000000000..be68f81b9--- /dev/null+++ b/apps/web/src/components/playbooks/StepExecutionNotice.tsx@@ -0,0 +1,95 @@+'use client';++/**+ * What the engine will actually do with a step of this type.+ *+ * The three states come from the schema's `x-aisoc-execution` map, which+ * `scripts/check_playbook_schema_parity.py` compares against the engine's+ * real handler table in both directions — so this is a checked fact rather+ * than a label somebody typed.+ *+ * The distinction the editor has to keep is between *accepting* a step type+ * and *performing* it:+ *+ * - `executed` — a handler runs in the agents service.+ * - `governed` — the step is handed to the action registry, which grades it+ * against the capability contract and the tenant's autonomy policy. That+ * is not the same as a vendor being touched, and the run's own report says+ * which happened. Saying "this will isolate the host" would be a promise+ * the editor is in no position to make.+ * - `unimplemented` — there is no handler. The engine fails the step closed+ * and the default `on_failure: abort` halts the run. `approval` is the one+ * type in this state and it is deliberate: an approval step is a pause and+ * the engine has nothing to suspend.+ *+ * Colour never carries the meaning on its own — each state is named in text,+ * because the WCAG AA gate is not the only reason that matters.+ */++import React from 'react';+import type { StepSchema } from './stepSchemas';++const BADGE: Record<StepSchema['execution'], { text: string; className: string }> = {+ executed: {+ text: 'Runs in the engine',+ className: 'text-sky-300 border-sky-800 bg-sky-950/40',+ },+ governed: {+ text: 'Governed action',+ className: 'text-amber-300 border-amber-800 bg-amber-950/40',+ },+ unimplemented: {+ text: 'Not runnable',+ className: 'text-red-300 border-red-800 bg-red-950/40',+ },+};++const EXPLANATION: Record<StepSchema['execution'], string> = {+ executed: 'The agents service handles this step directly.',+ governed:+ 'Dispatched to the action registry, which applies this capability\u2019s contract and the ' ++ 'tenant\u2019s autonomy policy. Reaching dispatch is not the same as a vendor being changed: ' ++ 'a preview, an approval queue and a missing integration are each reported as not executed.',+ unimplemented: '',+};++export function StepExecutionNotice({ schema }: { schema: StepSchema }) {+ const badge = BADGE[schema.execution];+ const unavailable = schema.unavailable;++ return (+ <div className="space-y-2">+ <p className="flex items-center gap-2 text-xs text-gray-500 leading-relaxed">+ <span+ className={`shrink-0 rounded border px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wide ${badge.className}`}+ >+ {badge.text}+ </span>+ <span>{schema.description}</span>+ </p>++ {EXPLANATION[schema.execution] && (+ <p className="text-[11px] text-gray-500 leading-relaxed">+ {EXPLANATION[schema.execution]}+ </p>+ )}++ {unavailable && (+ // `role="note"` rather than `alert`: this is a standing property of+ // the step type, not something that just went wrong, and an assertive+ // live region firing on every selection would be noise.+ <div+ role="note"+ aria-label={`${schema.label} steps cannot run`}+ className="rounded border border-red-900 bg-red-950/30 p-2 text-[11px] leading-relaxed text-red-200"+ >+ <p className="font-semibold">+ The engine will not run this step. It fails closed and the run stops+ there.+ </p>+ <p className="mt-1 text-red-300/90">{unavailable}</p>+ </div>+ )}+ </div>+ );+}diff --git a/apps/web/src/components/playbooks/StepInspector.a11y.test.tsx b/apps/web/src/components/playbooks/StepInspector.a11y.test.tsxnew file mode 100644index 000000000..3e2475f44--- /dev/null+++ b/apps/web/src/components/playbooks/StepInspector.a11y.test.tsx@@ -0,0 +1,102 @@+/**+ * WCAG 2.1 AA sweep over the step inspector — every step type it can render.+ *+ * These are forms, and they carry the two defects forms carry: a `<label>`+ * that sits beside its control rather than pointing at it, and an error+ * summary that names a field without being reachable from it. The inspector+ * had both. Thirteen new forms went in on top, so the sweep runs over the+ * whole vocabulary rather than one representative type — a schema whose+ * descriptor happens to produce an unlabelled control would otherwise be+ * caught only if somebody had picked that step type for the test.+ *+ * `color-contrast` is disabled for the same reason as+ * `src/test/a11y.test.tsx`: jsdom does not compute CSS variables, so the rule+ * returns "incomplete" rather than a useful answer.+ */++import { afterEach, describe, expect, it, vi } from 'vitest';+import { cleanup, render, screen } from '@testing-library/react';+import { axe } from 'vitest-axe';+import { StepInspector } from './StepInspector';+import { ALL_STEP_TYPES, STEP_SCHEMAS, defaultParamsFor } from './stepSchemas';+import type { PlaybookStep, StepType } from './types';++const AXE_OPTIONS = { rules: { 'color-contrast': { enabled: false } } };++function stepOf(type: StepType): PlaybookStep {+ return {+ id: 'step-1',+ name: `A ${STEP_SCHEMAS[type].label} step`,+ type,+ params: defaultParamsFor(type),+ on_failure: 'abort',+ retry_max: 0,+ timeout_seconds: 30,+ };+}++afterEach(cleanup);++describe('StepInspector — WCAG 2.1 AA', () => {+ it.each(ALL_STEP_TYPES.map((type) => [type] as const))(+ 'the %s form has no accessibility violations',+ async (type) => {+ const { container } = render(+ <StepInspector step={stepOf(type)} onUpdate={vi.fn()} onDelete={vi.fn()} />,+ );+ expect(await axe(container, AXE_OPTIONS)).toHaveNoViolations();+ },+ );++ it('associates every parameter control with its label, exactly one each', () => {+ for (const type of ALL_STEP_TYPES) {+ render(<StepInspector step={stepOf(type)} onUpdate={vi.fn()} onDelete={vi.fn()} />);+ for (const field of STEP_SCHEMAS[type].fields) {+ // Matched exactly rather than by substring: "Title" is a substring of+ // "Exact title (optional)", and a substring match that happens to hit+ // two controls would pass for a field whose label reaches neither.+ // Throws when no control carries the label, which is the state every+ // one of these was in before.+ const controls = screen.getAllByLabelText(+ (content) => stripRequiredMarker(content) === field.label,+ );+ expect(controls, `${type}.${field.key} has no uniquely-labelled control`).toHaveLength(1);+ }+ cleanup();+ }+ });++ it('reaches a field error from the control it belongs to', () => {+ // `quarantine_file` requires a path and the default params have none, so+ // the inspector renders with a real validation error rather than a+ // synthetic one.+ render(+ <StepInspector step={stepOf('quarantine_file')} onUpdate={vi.fn()} onDelete={vi.fn()} />,+ );+ expect(screen.getByLabelText(/File path/i)).toHaveAttribute('aria-invalid', 'true');+ expect(screen.getByLabelText(/File path/i)).toHaveAccessibleDescription(+ /File path is required/i,+ );+ });++ it('tells a screen reader that an unrunnable step will not run', async () => {+ const unrunnable = ALL_STEP_TYPES.filter(+ (t) => STEP_SCHEMAS[t].execution === 'unimplemented',+ );+ expect(unrunnable.length).toBeGreaterThan(0);+ for (const type of unrunnable) {+ const { container } = render(+ <StepInspector step={stepOf(type)} onUpdate={vi.fn()} onDelete={vi.fn()} />,+ );+ const note = screen.getByRole('note');+ expect(note).toHaveTextContent(/will not run this step/i);+ expect(await axe(container, AXE_OPTIONS)).toHaveNoViolations();+ cleanup();+ }+ });+});++/** The label text without the "(required)" marker the form appends to it. */+function stripRequiredMarker(content: string): string {+ return content.replace(/\s*\(required\)\s*$/, '').trim();+}diff --git a/apps/web/src/components/playbooks/StepInspector.tsx b/apps/web/src/components/playbooks/StepInspector.tsxindex 169d74846..4161afc41 100644--- a/apps/web/src/components/playbooks/StepInspector.tsx+++ b/apps/web/src/components/playbooks/StepInspector.tsx@@ -16,27 +16,26 @@* - The `condition` editor still applies to every step kind; it* gates whether the step runs (and, for `condition` steps, drives* true/false branching on the canvas).- * - `validateStepParams` is run on every change and surfaced in the+ * - `validateStepFields` is run on every change and surfaced in the* form so users see required-field issues before saving.+ * - The type dropdown offers what the engine can run. A step whose type+ * it cannot — `approval`, today — still renders, because a playbook+ * imported with one has to be readable in order to be fixed; it is+ * listed in the dropdown only while it is the step's current type, and+ * `StepExecutionNotice` says plainly that the run will stop there.*/-import React, { useEffect, useMemo, useState } from 'react';+import React, { useEffect, useId, useMemo, useState } from 'react';import type { PlaybookStep, StepType, OnFailure } from './types';import { STEP_TYPE_META } from './stepColors';-import { STEP_SCHEMAS, defaultParamsFor, validateStepParams } from './stepSchemas';+import {+ AUTHORABLE_STEP_TYPES,+ STEP_SCHEMAS,+ defaultParamsFor,+ validateStepFields,+} from './stepSchemas';import { SchemaForm } from './SchemaForm';--const ALL_TYPES: StepType[] = [- 'enrich',- 'investigate',- 'notify',- 'block_ip',- 'isolate_host',- 'create_ticket',- 'close_case',- 'http',- 'condition',-];+import { StepExecutionNotice } from './StepExecutionNotice';interface StepInspectorProps {step: PlaybookStep;@@ -51,6 +50,7 @@ export function StepInspector({onDelete,readOnly = false,}: StepInspectorProps) {+ const uid = useId();const [local, setLocal] = useState<PlaybookStep>(step);useEffect(() => {@@ -76,9 +76,19 @@ export function StepInspector({const meta = STEP_TYPE_META[local.type];const schema = STEP_SCHEMAS[local.type];const validationErrors = useMemo(- () => validateStepParams(local.type, local.params ?? {}),+ () => validateStepFields(local.type, local.params ?? {}),[local.type, local.params],);+ // An unrunnable type is not offered, but it is kept in the list while it is+ // the step's own type — otherwise the select would silently display some+ // other step kind for a step that is not one.+ const typeOptions = useMemo(+ () =>+ AUTHORABLE_STEP_TYPES.includes(local.type)+ ? AUTHORABLE_STEP_TYPES+ : [local.type, ...AUTHORABLE_STEP_TYPES],+ [local.type],+ );return (<div className="h-full overflow-y-auto p-4 space-y-4 text-sm">@@ -107,16 +117,15 @@ export function StepInspector({)}</div>- {schema.description && (- <div className="text-xs text-gray-500 leading-relaxed">- {schema.description}- </div>- )}+ <StepExecutionNotice schema={schema} />{/* Name */}<div>- <label className="block text-gray-400 text-xs mb-1">Step Name</label>+ <label htmlFor={`${uid}-name`} className="block text-gray-400 text-xs mb-1">+ Step Name+ </label><input+ id={`${uid}-name`}value={local.name}onChange={(e) => update({ name: e.target.value })}disabled={readOnly}@@ -126,16 +135,22 @@ export function StepInspector({{/* Type */}<div>- <label className="block text-gray-400 text-xs mb-1">Step Type</label>+ <label htmlFor={`${uid}-type`} className="block text-gray-400 text-xs mb-1">+ Step Type+ </label><select+ id={`${uid}-type`}value={local.type}onChange={(e) => changeType(e.target.value as StepType)}disabled={readOnly}className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-1.5 text-white text-sm focus:outline-none focus:border-blue-500 disabled:opacity-60">- {ALL_TYPES.map((t) => (+ {typeOptions.map((t) => (<option key={t} value={t}>- {STEP_TYPE_META[t].icon} {STEP_TYPE_META[t].label}+ {STEP_SCHEMAS[t].icon} {STEP_SCHEMAS[t].label}+ {STEP_SCHEMAS[t].execution === 'unimplemented'+ ? ' — not runnable'+ : ''}</option>))}</select>@@ -143,8 +158,14 @@ export function StepInspector({{/* On Failure */}<div>- <label className="block text-gray-400 text-xs mb-1">On Failure</label>+ <label+ htmlFor={`${uid}-on-failure`}+ className="block text-gray-400 text-xs mb-1"+ >+ On Failure+ </label><select+ id={`${uid}-on-failure`}value={local.on_failure}onChange={(e) => update({ on_failure: e.target.value as OnFailure })}disabled={readOnly}@@ -159,8 +180,14 @@ export function StepInspector({{/* Retry / Timeout */}<div className="grid grid-cols-2 gap-3"><div>- <label className="block text-gray-400 text-xs mb-1">Retry Max</label>+ <label+ htmlFor={`${uid}-retry-max`}+ className="block text-gray-400 text-xs mb-1"+ >+ Retry Max+ </label><input+ id={`${uid}-retry-max`}type="number"min={0}max={5}@@ -171,8 +198,14 @@ export function StepInspector({/></div><div>- <label className="block text-gray-400 text-xs mb-1">Timeout (s)</label>+ <label+ htmlFor={`${uid}-timeout`}+ className="block text-gray-400 text-xs mb-1"+ >+ Timeout (s)+ </label><input+ id={`${uid}-timeout`}type="number"min={1}max={600}@@ -186,14 +219,19 @@ export function StepInspector({</div></div>- {/* Condition */}- <div>- <label className="block text-gray-400 text-xs mb-1">+ {/* Condition — a group of three controls, so a fieldset rather than a+ label pointing at nothing in particular. */}+ <fieldset className="border-0 p-0 m-0">+ <legend className="block text-gray-400 text-xs mb-1">Condition (optional)- </label>+ </legend><div className="space-y-2 border border-gray-700 rounded p-3"><div>+ <label htmlFor={`${uid}-cond-field`} className="sr-only">+ Condition field+ </label><input+ id={`${uid}-cond-field`}placeholder="field e.g. verdict"value={local.condition?.field ?? ''}onChange={(e) =>@@ -210,7 +248,11 @@ export function StepInspector({/></div><div className="grid grid-cols-2 gap-2">+ <label htmlFor={`${uid}-cond-operator`} className="sr-only">+ Condition operator+ </label><select+ id={`${uid}-cond-operator`}value={local.condition?.operator ?? 'eq'}onChange={(e) =>update({@@ -237,7 +279,11 @@ export function StepInspector({<option value="contains">contains</option><option value="exists">exists</option></select>+ <label htmlFor={`${uid}-cond-value`} className="sr-only">+ Condition value+ </label><input+ id={`${uid}-cond-value`}placeholder="value"value={String(local.condition?.value ?? '')}onChange={(e) =>@@ -263,11 +309,11 @@ export function StepInspector({</button>)}</div>- </div>+ </fieldset>{/* Params — schema-driven */}- <div>- <label className="block text-gray-400 text-xs mb-1">Params</label>+ <fieldset className="border-0 p-0 m-0">+ <legend className="block text-gray-400 text-xs mb-1">Params</legend><SchemaFormschema={schema}value={(local.params ?? {}) as Record<string, unknown>}@@ -275,7 +321,7 @@ export function StepInspector({readOnly={readOnly}validationErrors={validationErrors}/>- </div>+ </fieldset>{/* Step ID */}<div className="text-xs text-gray-600 font-mono">id: {local.id}</div>diff --git a/apps/web/src/components/playbooks/packHelpers.ts b/apps/web/src/components/playbooks/packHelpers.tsindex fb4867689..a9964de74 100644--- a/apps/web/src/components/playbooks/packHelpers.ts+++ b/apps/web/src/components/playbooks/packHelpers.ts@@ -23,7 +23,7 @@* logical buckets (EDR, IAM, Ticketing, SIEM, Notify, AI, Firewall).*/-import type { Playbook } from './types';+import type { Playbook, StepType } from './types';const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;@@ -220,7 +220,17 @@ export const INTEGRATION_TYPES = [export type IntegrationType = (typeof INTEGRATION_TYPES)[number];-const STEP_TYPE_TO_INTEGRATION: Record<string, IntegrationType> = {+/**+ * Which integration a step type reaches, or `null` where it reaches none.+ *+ * Keyed `Record<StepType, …>` rather than `Record<string, …>`: as a+ * string-keyed map it listed eighteen of the engine's twenty-two step types+ * and the compiler had nothing to say about the four it did not, so a+ * playbook built entirely from those four claimed to use no integrations at+ * all. `null` is spelled out per type so "reaches nothing" is a decision+ * somebody made rather than a key nobody added.+ */+const STEP_TYPE_TO_INTEGRATION: Record<StepType, IntegrationType | null> = {investigate: 'AI Analysis',enrich: 'AI Analysis',isolate_host: 'EDR / Endpoint',@@ -228,6 +238,7 @@ const STEP_TYPE_TO_INTEGRATION: Record<string, IntegrationType> = {kill_process: 'EDR / Endpoint',run_av_scan: 'EDR / Endpoint',run_script: 'EDR / Endpoint',+ osquery_live_query: 'EDR / Endpoint',disable_user: 'Identity / IAM',reset_password: 'Identity / IAM',revoke_session: 'Identity / IAM',@@ -239,6 +250,12 @@ const STEP_TYPE_TO_INTEGRATION: Record<string, IntegrationType> = {block_ip: 'Firewall / Network',block_ioc: 'Firewall / Network',http: 'HTTP / Custom',+ // Engine-internal: these reach the AiSOC API or nothing at all, and+ // showing a vendor badge for them would overstate what a pack integrates.+ close_case: null,+ condition: null,+ // Not runnable at all — see `STEP_SCHEMAS.approval`.+ approval: null,};/**diff --git a/apps/web/src/components/playbooks/stepColors.ts b/apps/web/src/components/playbooks/stepColors.tsindex 5de6fec86..ec1ea742c 100644--- a/apps/web/src/components/playbooks/stepColors.ts+++ b/apps/web/src/components/playbooks/stepColors.ts@@ -1,16 +1,35 @@+/**+ * Canvas and palette presentation for each step type.+ *+ * Derived from `STEP_SCHEMAS` rather than declared. This file used to hold a+ * second nine-entry `Record<StepType, …>` beside the one in `stepSchemas`,+ * which meant adding a step type required remembering both — and the thirteen+ * the engine already ran were missing from each.+ */+import type { StepType } from './types';+import { STEP_SCHEMAS, ALL_STEP_TYPES } from './stepSchemas';++export interface StepTypeMeta {+ label: string;+ color: string;+ bgColor: string;+ icon: string;+}-export const STEP_TYPE_META: Record<- StepType,- { label: string; color: string; bgColor: string; icon: string }-> = {- enrich: { label: 'Enrich', color: '#60a5fa', bgColor: '#1e3a5f', icon: 'enr' },- investigate: { label: 'Investigate', color: '#a78bfa', bgColor: '#2e1f5e', icon: 'inv' },- notify: { label: 'Notify', color: '#34d399', bgColor: '#1a3d2e', icon: 'ntf' },- block_ip: { label: 'Block IP', color: '#f87171', bgColor: '#3d1a1a', icon: 'blk' },- isolate_host: { label: 'Isolate Host', color: '#fb923c', bgColor: '#3d2a1a', icon: 'iso' },- create_ticket: { label: 'Create Ticket', color: '#fbbf24', bgColor: '#3d341a', icon: 'tkt' },- close_case: { label: 'Close Case', color: '#94a3b8', bgColor: '#252d3a', icon: 'cls' },- http: { label: 'HTTP', color: '#38bdf8', bgColor: '#1a3040', icon: 'http' },- condition: { label: 'Condition', color: '#e879f9', bgColor: '#3a1a40', icon: 'if' },-};+export const STEP_TYPE_META: Record<StepType, StepTypeMeta> = Object.fromEntries(+ ALL_STEP_TYPES.map((type) => {+ const schema = STEP_SCHEMAS[type];+ return [+ type,+ {+ label: schema.label,+ color: schema.accent,+ bgColor: schema.bgColor,+ // The canvas node is too narrow for an emoji plus a name, so it shows+ // the short code; the palette uses `schema.icon`.+ icon: schema.shortCode,+ },+ ];+ }),+) as Record<StepType, StepTypeMeta>;diff --git a/apps/web/src/components/playbooks/stepSchemas.ts b/apps/web/src/components/playbooks/stepSchemas.tsindex abc0a4a04..8756eef9a 100644--- a/apps/web/src/components/playbooks/stepSchemas.ts+++ b/apps/web/src/components/playbooks/stepSchemas.ts@@ -2,27 +2,51 @@* stepSchemas* ===========*- * Lightweight schema registry for playbook step parameters. Drives the- * StepInspector form so each step kind gets a typed editor instead of a- * raw JSON textarea.+ * The editor's single registry of the playbook step vocabulary: what each+ * step type is called, what the engine does with it, and what its parameters+ * are.*- * The shape is *deliberately* simpler than full JSON Schema: only the- * features the SOAR canvas actually needs (string, textarea, number,- * boolean, select, env-ref, jsonpath). Extending later is straightforward.+ * Single, now. It used to be one of five vocabularies. The engine+ * (`services/agents/app/playbook/models.py`) declares twenty-two step types+ * and the published package (`packages/types/src/playbook.ts`) publishes the+ * same twenty-two, but this directory declared its own nine-member union in+ * `./types` and keyed `STEP_SCHEMAS` on *that* — so `Record<StepType, …>` was+ * satisfied with thirteen forms missing and the build stayed green. Keying it+ * on the published union is what makes the compiler enumerate a new verb+ * instead of a reviewer having to.*- * Empirical canonical shapes (from `playbooks/packs/v1/`):- * block_ip : { duration, ip_field }- * close_case : { resolution }- * condition : { (no params; the condition lives on the step itself) }- * create_ticket : { priority, queue, title_template }- * enrich : { indicator_field }- * http : { body_template?, headers_env?, method, url }- * investigate : { case_id_field, focus? }- * isolate_host : { host_field }- * notify : { channel, message_template, service_key_env? | webhook_env? }+ * `stepColors`, the editor palette and the inspector's type dropdown are all+ * derived from this map rather than restating it, and+ * `scripts/check_playbook_schema_parity.py` reads it against the engine and+ * the schema in both directions. A sixth vocabulary is a failed build.+ *+ * Two conventions live here, and the difference is worth knowing+ * -------------------------------------------------------------+ * The nine original forms collect `*_field` keys — `ip_field`,+ * `host_field`, `case_id_field`. The engine does **not** dereference those:+ * `_resolve_target` and the `enrich` / `investigate` handlers read fixed keys+ * (`ip`, `src_ip`, `host`, `case_id`, …) from `step.params` first and the+ * trigger context second. `*_field` is an authoring convention that the 833+ * steps in `playbooks/packs/v1` are written in, and those steps run because+ * the alert context supplies the value — not because the parameter is read.+ * Changing it means changing the engine or the packs, neither of which is+ * this file's to change, so the nine are left as they are.+ *+ * The thirteen added here write the keys the engine and the executor actually+ * read, and each target field's help text names the fallback chain+ * `_resolve_target` implements. Where a parameter is inert, it is not offered:+ * the shipped packs carry a `dry_run` param on response steps and nothing+ * reads it — whether a vendor is touched is decided by+ * `AISOC_PLAYBOOK_ACTIONS_EXECUTE` and the capability contract — so there is+ * no `dry_run` control here rather than a checkbox that does nothing.+ *+ * Credentials are never collected. `services/api` resolves them per tenant+ * from the connector vault at dispatch time; a form asking for+ * `cs_client_secret` would be asking an author to paste a secret into a+ * playbook document.*/-import type { StepType } from './types';+import type { StepExecution, StepType } from './types';export type FieldKind =| 'string'@@ -31,7 +55,8 @@ export type FieldKind =| 'boolean'| 'select'| 'env_ref'- | 'jsonpath';+ | 'jsonpath'+ | 'string_list';export interface FieldOption {value: string;@@ -58,13 +83,37 @@ export interface FieldDescriptor {export interface StepSchema {type: StepType;+ /**+ * What the engine does with this type, mirroring the schema's+ * `x-aisoc-execution` map — which the parity gate compares against the+ * engine's real handler table, so it cannot become an aspirational claim.+ *+ * - `executed` — a handler runs and has a real effect.+ * - `governed` — dispatched to `services/actions`, where the capability+ * contract and the tenant's autonomy policy decide whether a vendor is+ * touched. Reaching dispatch is not executing; the run's own report says+ * which happened.+ * - `unimplemented` — no handler. The engine fails the step closed and the+ * default `on_failure: abort` halts the run.+ */+ execution: StepExecution;label: string;description: string;/** Pretty colour token used in the canvas / palette. */accent: string;+ /** Canvas node background. */+ bgColor: string;/** Single-emoji icon used in the palette. */icon: string;+ /** Short badge rendered on the canvas node, where an emoji is too wide. */+ shortCode: string;fields: readonly FieldDescriptor[];+ /**+ * Why this type cannot run, in the engine's own words. Set on every+ * `unimplemented` type and on no other, so the UI can explain rather than+ * offer. See `_UNBRIDGEABLE` in `services/agents/app/playbook/engine.py`.+ */+ unavailable?: string;}const NOTIFY_CHANNELS: readonly FieldOption[] = [@@ -97,13 +146,80 @@ const INVESTIGATE_FOCUS: readonly FieldOption[] = [{ value: 'malware', label: 'Malware' },];+/** Defender's indicator vocabulary, from `BlockIOCExecutor`. */+const IOC_TYPES: readonly FieldOption[] = [+ { value: 'IpAddress', label: 'IP address' },+ { value: 'DomainName', label: 'Domain name' },+ { value: 'Url', label: 'URL' },+ { value: 'FileSha256', label: 'File hash — SHA256' },+ { value: 'FileSha1', label: 'File hash — SHA1' },+];++/** The platform's five-tier ladder, as `CreateNotableEventExecutor` reads it. */+const SEVERITIES: readonly FieldOption[] = [+ { value: 'info', label: 'Info' },+ { value: 'low', label: 'Low' },+ { value: 'medium', label: 'Medium' },+ { value: 'high', label: 'High' },+ { value: 'critical', label: 'Critical' },+];++const OSQUERY_BACKENDS: readonly FieldOption[] = [+ { value: 'osctrl', label: 'osctrl' },+ { value: 'fleetdm', label: 'FleetDM' },+ { value: 'aisoc_direct', label: 'AiSOC direct' },+];++const AV_SCAN_TYPES: readonly FieldOption[] = [+ { value: 'Quick', label: 'Quick' },+ { value: 'Full', label: 'Full' },+];++/**+ * The target a response verb acts on, keyed on the first name+ * `engine._TARGET_KEYS` looks for. Left blank, the engine falls back to the+ * remaining names in `step.params` and then to the trigger context — which is+ * how a playbook says "the host in this alert" rather than a fixed one.+ */+function target(+ key: string,+ label: string,+ placeholder: string,+ fallbacks: readonly string[],+): FieldDescriptor {+ const names = [key, ...fallbacks].join(', ');+ return {+ key,+ label,+ kind: 'string',+ placeholder,+ help: `Leave blank to take ${names} from the triggering alert instead.`,+ };+}++const HOST_TARGET = target('host', 'Host', 'web-prod-04', [+ 'hostname',+ 'device_id',+ 'host_id',+]);++const USER_TARGET = target('user', 'User', '[email protected]', [+ 'username',+ 'user_id',+ 'upn',+ 'email',+]);+export const STEP_SCHEMAS: Record<StepType, StepSchema> = {enrich: {type: 'enrich',+ execution: 'executed',label: 'Enrich',description: 'Look up additional context for an indicator (IP, hash, user, asset).',accent: '#38bdf8',+ bgColor: '#1a3040',icon: '🔍',+ shortCode: 'enr',fields: [{key: 'indicator_field',@@ -117,10 +233,13 @@ export const STEP_SCHEMAS: Record<StepType, StepSchema> = {},investigate: {type: 'investigate',+ execution: 'executed',label: 'Investigate',description: 'Run the investigator agent against a case to gather artefacts and timeline.',accent: '#a78bfa',+ bgColor: '#2e1f5e',icon: '🕵️',+ shortCode: 'inv',fields: [{key: 'case_id_field',@@ -140,10 +259,13 @@ export const STEP_SCHEMAS: Record<StepType, StepSchema> = {},notify: {type: 'notify',+ execution: 'executed',label: 'Notify',description: 'Send a notification to Slack, PagerDuty, email, or a generic webhook.',accent: '#facc15',+ bgColor: '#1a3d2e',icon: '🔔',+ shortCode: 'ntf',fields: [{key: 'channel',@@ -179,10 +301,13 @@ export const STEP_SCHEMAS: Record<StepType, StepSchema> = {},block_ip: {type: 'block_ip',+ execution: 'governed',label: 'Block IP',description: 'Push a blocklist rule into the network executor (firewall / WAF / cloud SG).',accent: '#f87171',+ bgColor: '#3d1a1a',icon: '🚫',+ shortCode: 'blk',fields: [{key: 'ip_field',@@ -201,12 +326,45 @@ export const STEP_SCHEMAS: Record<StepType, StepSchema> = {},],},+ block_ioc: {+ type: 'block_ioc',+ execution: 'governed',+ label: 'Block IOC',+ description:+ 'Add an indicator — hash, domain, URL or address — to the EDR blocklist. Breadth depends on the indicator type, so the contract grades it at the worst case.',+ accent: '#ef4444',+ bgColor: '#3d1a1a',+ icon: '⛔',+ shortCode: 'ioc',+ fields: [+ target('ioc', 'Indicator', '203.0.113.10', ['indicator', 'hash', 'domain', 'ip']),+ {+ key: 'ioc_type',+ label: 'Indicator type',+ kind: 'select',+ required: true,+ options: IOC_TYPES,+ defaultValue: 'IpAddress',+ help: 'Must match the indicator: blocking a SHA256 as an IP address is rejected by the vendor.',+ },+ {+ key: 'title',+ label: 'Blocklist entry title',+ kind: 'string',+ placeholder: 'C2 infrastructure — campaign RAVEN',+ help: 'Shown in the vendor console. Defaults to "AiSOC — blocked <type>: <indicator>".',+ },+ ],+ },isolate_host: {type: 'isolate_host',+ execution: 'governed',label: 'Isolate host',description: 'Quarantine an endpoint via the EDR (CrowdStrike, Defender, etc.).',accent: '#fb7185',+ bgColor: '#3d2a1a',icon: '🛡️',+ shortCode: 'iso',fields: [{key: 'host_field',@@ -219,10 +377,13 @@ export const STEP_SCHEMAS: Record<StepType, StepSchema> = {},create_ticket: {type: 'create_ticket',+ execution: 'governed',label: 'Create ticket',description: 'Open a Jira / ServiceNow ticket for SOC follow-up.',accent: '#34d399',+ bgColor: '#3d341a',icon: '📝',+ shortCode: 'tkt',fields: [{key: 'priority',@@ -251,10 +412,13 @@ export const STEP_SCHEMAS: Record<StepType, StepSchema> = {},close_case: {type: 'close_case',+ execution: 'executed',label: 'Close case',description: 'Mark the case resolved. Terminal step — no outgoing edges allowed.',accent: '#94a3b8',+ bgColor: '#252d3a',icon: '✅',+ shortCode: 'cls',fields: [{key: 'resolution',@@ -274,10 +438,13 @@ export const STEP_SCHEMAS: Record<StepType, StepSchema> = {},http: {type: 'http',+ execution: 'executed',label: 'HTTP request',description: 'Generic outbound HTTP — useful for arbitrary integrations.',accent: '#60a5fa',+ bgColor: '#1a3040',icon: '🌐',+ shortCode: 'http',fields: [{key: 'method',@@ -312,16 +479,353 @@ export const STEP_SCHEMAS: Record<StepType, StepSchema> = {},condition: {type: 'condition',+ execution: 'executed',label: 'Condition',description:'Branch the playbook on a field check. Configure the predicate via the Condition section above.',accent: '#fbbf24',+ bgColor: '#3a1a40',icon: '❓',+ shortCode: 'if',// condition has no params — its predicate lives on `step.condition`.fields: [],},+ osquery_live_query: {+ type: 'osquery_live_query',+ execution: 'executed',+ label: 'Live query',+ description:+ 'Run an allowlisted osquery query across hosts through osctrl, FleetDM or the AiSOC agent. The query itself is a template ID, not free SQL, so a playbook cannot ask an endpoint an arbitrary question. Needs an agents image carrying the osquery backend clients; without them the engine fails the step rather than reporting a query it never sent.',+ accent: '#2dd4bf',+ bgColor: '#123333',+ icon: '🔎',+ shortCode: 'osq',+ fields: [+ {+ key: 'template',+ label: 'Query template',+ kind: 'string',+ required: true,+ placeholder: 'running_processes',+ help: 'Allowlist template ID. The engine refuses the step without one.',+ },+ {+ key: 'backend',+ label: 'Backend',+ kind: 'select',+ required: true,+ options: OSQUERY_BACKENDS,+ defaultValue: 'osctrl',+ },+ {+ key: 'target_hosts',+ label: 'Target hosts',+ kind: 'string_list',+ placeholder: 'web-prod-04, web-prod-05',+ help: 'Comma-separated host UUIDs or names. Leave blank to query the host named in the alert.',+ },+ {+ key: 'instance_id',+ label: 'Connector instance',+ kind: 'string',+ placeholder: 'a1b2c3d4-…',+ help:+ 'Connector instance whose credentials the backend should use. Leave blank to use ' ++ '`connector_instance_id` from the alert. Credentials are read from the vault, never from this playbook.',+ },+ {+ key: 'timeout_seconds',+ label: 'Collection window (seconds)',+ kind: 'number',+ defaultValue: 60,+ help: 'How long to wait for hosts to answer. Clamped to the engine ceiling of 3600.',+ },+ ],+ },+ approval: {+ type: 'approval',+ execution: 'unimplemented',+ label: 'Approval',+ description:+ 'Not runnable. The engine fails an approval step closed and the run stops there.',+ accent: '#64748b',+ bgColor: '#1e232b',+ icon: '⛔',+ shortCode: 'appr',+ fields: [],+ unavailable:+ 'An approval step is a pause, and the engine is a single-threaded index walk with no pause ' ++ 'or resume — there is nothing to suspend and nothing to wake. It is also no longer the ' ++ 'mechanism: every response step is graded against its own capability contract at dispatch ' ++ 'and returns "pending approval" on its own when a human is required, so an approval step in ' ++ 'front of one would gate a decision that is already gated. Remove it, or hold the action in ' ++ 'the actions service, which does queue for an analyst.',+ },+ disable_user: {+ type: 'disable_user',+ execution: 'governed',+ label: 'Disable user',+ description:+ 'Disable an account in Okta, Entra or Google Workspace. Stops one person working; reversible, and instantly noticed.',+ accent: '#fb923c',+ bgColor: '#3d2a1a',+ icon: '🔒',+ shortCode: 'dis',+ fields: [USER_TARGET],+ },+ reset_password: {+ type: 'reset_password',+ execution: 'governed',+ label: 'Reset password',+ description: 'Force a password reset for an account in Okta, Entra or Google Workspace.',+ accent: '#fb923c',+ bgColor: '#3d2a1a',+ icon: '🔑',+ shortCode: 'pwd',+ fields: [+ USER_TARGET,+ {+ key: 'send_email',+ label: 'Email the user a reset link',+ kind: 'boolean',+ defaultValue: true,+ help: 'Okta only. Entra and Workspace have no equivalent option and ignore it.',+ },+ ],+ },+ revoke_session: {+ type: 'revoke_session',+ execution: 'governed',+ label: 'Revoke sessions',+ description:+ "Kill an account's live sessions and refresh tokens. Leaves the account enabled — use Disable user for that.",+ accent: '#f59e0b',+ bgColor: '#3d2a1a',+ icon: '🚪',+ shortCode: 'ses',+ fields: [USER_TARGET],+ },+ force_mfa: {+ type: 'force_mfa',+ execution: 'governed',+ label: 'Force MFA',+ description: 'Require the account to re-enrol its second factor at next sign-in.',+ accent: '#f59e0b',+ bgColor: '#3d2a1a',+ icon: '📲',+ shortCode: 'mfa',+ fields: [USER_TARGET],+ },+ kill_process: {+ type: 'kill_process',+ execution: 'governed',+ label: 'Kill process',+ description:+ 'Terminate a process on an endpoint. A killed process cannot be un-killed, but the effect does not persist: a service restarts, a user runs the program again.',+ accent: '#f472b6',+ bgColor: '#3d1a2e',+ icon: '💀',+ shortCode: 'kill',+ fields: [+ HOST_TARGET,+ {+ key: 'pid',+ label: 'Process ID',+ kind: 'number',+ placeholder: '4821',+ help: 'CrowdStrike terminates by PID and refuses the action without one.',+ },+ {+ key: 'process_name',+ label: 'Process name',+ kind: 'string',+ placeholder: 'rundll32.exe',+ help: 'SentinelOne targets binaries by name rather than PID. Give at least one of the two.',+ },+ ],+ },+ quarantine_file: {+ type: 'quarantine_file',+ execution: 'governed',+ label: 'Quarantine file',+ description:+ 'Move a file on an endpoint into vendor quarantine. Quarantining a legitimate binary breaks whatever depended on it.',+ accent: '#f472b6',+ bgColor: '#3d1a2e',+ icon: '🧪',+ shortCode: 'qrn',+ fields: [+ HOST_TARGET,+ {+ key: 'file_path',+ label: 'File path',+ kind: 'string',+ required: true,+ placeholder: 'C:\\Users\\Public\\svchost.exe',+ help: 'Absolute path on the host. Required: with no path the executor falls back to the hostname.',+ },+ {+ key: 'file_hash',+ label: 'File hash',+ kind: 'string',+ placeholder: 'e3b0c44298fc1c14…',+ help: 'Optional. Recorded with the action so the file can be identified after the fact.',+ },+ ],+ },+ run_av_scan: {+ type: 'run_av_scan',+ execution: 'governed',+ label: 'Run AV scan',+ description: 'Start an antivirus scan on an endpoint. Consumes CPU on one host and finishes; nothing to undo.',+ accent: '#fb7185',+ bgColor: '#3d1a2e',+ icon: '🧹',+ shortCode: 'av',+ fields: [+ HOST_TARGET,+ {+ key: 'scan_type',+ label: 'Scan type',+ kind: 'select',+ required: true,+ options: AV_SCAN_TYPES,+ defaultValue: 'Full',+ help: 'Microsoft Defender honours the distinction. SentinelOne runs a full scan either way.',+ },+ ],+ },+ run_script: {+ type: 'run_script',+ execution: 'governed',+ label: 'Run script',+ description:+ 'Execute a script on an endpoint. The most dangerous verb the platform has: the contract marks it severe, manual-rollback-only, and requires a named human — there is nothing to probe afterwards because the platform cannot know what an arbitrary script was meant to do.',+ accent: '#e11d48',+ bgColor: '#40161f',+ icon: '⚙️',+ shortCode: 'scr',+ fields: [+ HOST_TARGET,+ {+ key: 'script_name',+ label: 'Pre-staged script',+ kind: 'string',+ placeholder: 'collect-persistence',+ help: 'Name of a script already staged in the EDR console. Preferred: the body is reviewed once, there.',+ },+ {+ key: 'script_args',+ label: 'Arguments',+ kind: 'string',+ placeholder: '-Scope AllUsers',+ help: 'Passed to the pre-staged script. Ignored when a raw body is supplied below.',+ },+ {+ key: 'script_content',+ label: 'Raw script body',+ kind: 'textarea',+ placeholder: 'Get-CimInstance Win32_StartupCommand | ConvertTo-Json',+ help: 'Sent verbatim and used in preference to the pre-staged name. Give at least one of the two.',+ },+ ],+ },+ search_siem: {+ type: 'search_siem',+ execution: 'governed',+ label: 'Search SIEM',+ description:+ 'Run a query against the connected SIEM and bring the rows back into the run context. Read-only, so the contract clears it at any confidence.',+ accent: '#38bdf8',+ bgColor: '#12304a',+ icon: '🔭',+ shortCode: 'siem',+ fields: [+ {+ key: 'query',+ label: 'Query',+ kind: 'textarea',+ required: true,+ placeholder: 'index=proxy dest_ip=203.0.113.10 earliest=-24h',+ help: 'SPL for Splunk, ES|QL for Elastic. Also the step target, so the run record names what was asked.',+ },+ {+ key: 'max_results',+ label: 'Maximum rows',+ kind: 'number',+ defaultValue: 500,+ help: 'Rows to bring back into the run context.',+ },+ ],+ },+ create_notable_event: {+ type: 'create_notable_event',+ execution: 'governed',+ label: 'Create notable event',+ description:+ 'Raise a notable event in Splunk ES. Writes a record into someone else\u2019s queue: noise, not damage.',+ accent: '#0ea5e9',+ bgColor: '#12304a',+ icon: '📣',+ shortCode: 'note',+ fields: [+ {+ key: 'title',+ label: 'Title',+ kind: 'string',+ required: true,+ placeholder: 'Credential access on web-prod-04',+ help: 'The step target. Splunk records it as "AiSOC Alert — <title>" unless overridden below.',+ },+ {+ key: 'severity',+ label: 'Severity',+ kind: 'select',+ required: true,+ options: SEVERITIES,+ defaultValue: 'high',+ },+ {+ key: 'description',+ label: 'Description',+ kind: 'textarea',+ placeholder: 'Four failed sudo attempts followed by a successful root shell.',+ },+ {+ key: 'event_title',+ label: 'Exact title (optional)',+ kind: 'string',+ placeholder: 'SOC-2291 credential access',+ help: 'Recorded verbatim, without the "AiSOC Alert — " prefix.',+ },+ ],+ },};+/**+ * Every step type the engine accepts, in registry order.+ *+ * Derived rather than restated: a hand-written copy of this list in+ * `StepInspector` and another in `PlaybookEditor` were two of the five+ * vocabularies.+ */+export const ALL_STEP_TYPES: readonly StepType[] = Object.keys(+ STEP_SCHEMAS,+) as StepType[];++/**+ * The types the palette may offer.+ *+ * Filtered on `execution`, not on a name: a type the engine cannot run must+ * not be offered as a thing to add, and hard-coding `!== 'approval'` would+ * stop being true the next time a verb is declared ahead of its handler.+ * Existing steps of an unrunnable type still render — an imported playbook+ * has to be readable in order to be fixed.+ */+export const AUTHORABLE_STEP_TYPES: readonly StepType[] = ALL_STEP_TYPES.filter(+ (type) => STEP_SCHEMAS[type].execution !== 'unimplemented',+);+/*** Default `params` object for a freshly added step. Honours `defaultValue`* on each field descriptor so the inspector form is never blank for known@@ -338,51 +842,107 @@ export function defaultParamsFor(type: StepType): Record<string, unknown> {return params;}+/** A validation problem, carrying the field it belongs to when it has one. */+export interface StepParamError {+ /** Param key this belongs to, or undefined for a whole-step problem. */+ key?: string;+ message: string;+}++function isBlank(value: unknown): boolean {+ return value === undefined || value === null || value === '';+}+/**- * Returns a list of human-readable validation problems for the given- * params object against the schema for `type`. An empty array means the- * step is valid.+ * Validation problems for `params` against the schema for `type`, each tied+ * to the field it came from so the form can associate it with the control+ * rather than dumping an unattached list at the bottom.+ *+ * An empty array means the step is valid.*/-export function validateStepParams(+export function validateStepFields(type: StepType,params: Record<string, unknown>,-): string[] {+): StepParamError[] {const schema = STEP_SCHEMAS[type];- const errors: string[] = [];+ const errors: StepParamError[] = [];++ if (schema.execution === 'unimplemented') {+ errors.push({+ message:+ `${schema.label} steps are not runnable: the engine fails the step and the run stops there. ` ++ `Remove this step.`,+ });+ }+for (const field of schema.fields) {const value = params[field.key];- if (- field.required &&- (value === undefined || value === null || value === '')- ) {- errors.push(`${field.label} is required.`);+ if (field.required && isBlank(value)) {+ errors.push({ key: field.key, message: `${field.label} is required.` });}- if (- field.kind === 'number' &&- value !== undefined &&- value !== null &&- value !== '' &&- typeof value !== 'number'- ) {- errors.push(`${field.label} must be a number.`);+ if (field.kind === 'number' && !isBlank(value) && typeof value !== 'number') {+ errors.push({ key: field.key, message: `${field.label} must be a number.` });}if (field.kind === 'boolean' &&value !== undefined &&typeof value !== 'boolean') {- errors.push(`${field.label} must be true/false.`);+ errors.push({ key: field.key, message: `${field.label} must be true/false.` });+ }+ if (field.kind === 'string_list' && value !== undefined && !Array.isArray(value)) {+ errors.push({ key: field.key, message: `${field.label} must be a list.` });}}- // Notify channel-specific cross-field check.++ // Cross-field checks: a required-one-of cannot be expressed on a single+ // descriptor, and each of these mirrors a refusal in the executor rather+ // than a house style.if (type === 'notify') {const channel = params.channel;if (channel === 'pagerduty' && !params.service_key_env) {- errors.push('PagerDuty channel requires a service-key env var.');+ errors.push({+ key: 'service_key_env',+ message: 'PagerDuty channel requires a service-key env var.',+ });}if (channel === 'webhook' && !params.webhook_env) {- errors.push('Webhook channel requires a webhook env var.');+ errors.push({+ key: 'webhook_env',+ message: 'Webhook channel requires a webhook env var.',+ });}}+ if (type === 'kill_process' && isBlank(params.pid) && isBlank(params.process_name)) {+ errors.push({+ key: 'pid',+ message:+ 'Give a process ID or a process name — CrowdStrike kills by PID, SentinelOne by name, and neither can act on nothing.',+ });+ }+ if (+ type === 'run_script' &&+ isBlank(params.script_name) &&+ isBlank(params.script_content)+ ) {+ errors.push({+ key: 'script_name',+ message: 'Name a pre-staged script or supply a raw body; there is nothing to run otherwise.',+ });+ }+return errors;}++/**+ * Human-readable validation problems for the given params object.+ *+ * Kept as the string-shaped view over {@link validateStepFields} for callers+ * that only render a list.+ */+export function validateStepParams(+ type: StepType,+ params: Record<string, unknown>,+): string[] {+ return validateStepFields(type, params).map((error) => error.message);+}diff --git a/apps/web/src/components/playbooks/stepVocabulary.test.ts b/apps/web/src/components/playbooks/stepVocabulary.test.tsnew file mode 100644index 000000000..f7ba7fcf3--- /dev/null+++ b/apps/web/src/components/playbooks/stepVocabulary.test.ts@@ -0,0 +1,272 @@+/**+ * The editor must be able to author every step type the engine runs.+ *+ * This directory declared its own nine-member `StepType` union while the+ * engine declared twenty-two and `packages/types` published twenty-two. The+ * build stayed green because `STEP_SCHEMAS` was keyed `Record<StepType, …>`+ * on the *local* union, so exhaustiveness was satisfied by the nine that+ * existed — thirteen verbs the product could run had no way to be authored,+ * and nothing said so.+ *+ * The union is now imported, so the compiler catches the next one. These+ * tests cover what the compiler cannot: that the published file really does+ * still hold the union being imported (a rename would leave both sides+ * agreeing on the wrong thing), that no entry is a placeholder, and that the+ * one type the engine cannot run is presented as such rather than offered.+ *+ * `scripts/check_playbook_schema_parity.py` is the other half — it reads the+ * engine, the JSON schema, the published package and this directory, in both+ * directions. This file is the half that can execute the registry.+ */++import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import { describe, expect, it } from 'vitest';+import type { StepType } from './types';+import {+ ALL_STEP_TYPES,+ AUTHORABLE_STEP_TYPES,+ STEP_SCHEMAS,+ defaultParamsFor,+ validateStepFields,+} from './stepSchemas';+import { STEP_TYPE_META } from './stepColors';++/**+ * One set of parameters that makes a step of each type valid.+ *+ * Exhaustive by construction. `approval` is present and empty because there+ * is nothing that makes it valid — the test that asserts so reads this too.+ */+const VALID_PARAMS: Record<StepType, Record<string, unknown>> = {+ enrich: { indicator_field: 'alert.src_ip' },+ investigate: { case_id_field: 'alert.case_id' },+ notify: { message_template: 'Lateral movement on {{alert.host}}' },+ block_ip: { ip_field: 'alert.src_ip' },+ block_ioc: { ioc: '203.0.113.10', ioc_type: 'IpAddress' },+ isolate_host: { host_field: 'alert.host' },+ create_ticket: { title_template: 'Credential access on {{alert.host}}' },+ close_case: {},+ http: { url: 'https://example.com/hook' },+ condition: {},+ osquery_live_query: { template: 'running_processes' },+ approval: {},+ disable_user: { user: '[email protected]' },+ reset_password: { user: '[email protected]' },+ revoke_session: { user: '[email protected]' },+ force_mfa: { user: '[email protected]' },+ kill_process: { host: 'web-prod-04', pid: 4821 },+ quarantine_file: { host: 'web-prod-04', file_path: 'C:/temp/svchost.exe' },+ run_av_scan: { host: 'web-prod-04' },+ run_script: { host: 'web-prod-04', script_name: 'collect-persistence' },+ search_siem: { query: 'index=proxy dest_ip=203.0.113.10' },+ create_notable_event: { title: 'Credential access on web-prod-04' },+};++/**+ * The first key `engine._resolve_target` looks for, per governed verb, or+ * `null` where the verb has no scalar target and its details ride in params.+ *+ * A form collecting `user_field` writes a key nothing dereferences, which is+ * how a step ends up dispatching with an empty target. The two marked as+ * pre-existing keep the `*_field` convention the 833 shipped steps are+ * written in; see the header of `stepSchemas.ts`.+ */+const TARGET_KEY: Record<StepType, string | null> = {+ enrich: null,+ investigate: null,+ notify: null,+ close_case: null,+ http: null,+ condition: null,+ osquery_live_query: null,+ approval: null,+ block_ip: 'ip_field', // pre-existing convention+ isolate_host: 'host_field', // pre-existing convention+ create_ticket: 'title_template', // no scalar target; details ride in params+ block_ioc: 'ioc',+ kill_process: 'host',+ quarantine_file: 'host',+ run_av_scan: 'host',+ run_script: 'host',+ disable_user: 'user',+ reset_password: 'user',+ revoke_session: 'user',+ force_mfa: 'user',+ search_siem: 'query',+ create_notable_event: 'title',+};++/**+ * The `StepType` union as published, read from source.+ *+ * Parsed rather than imported because a TypeScript union does not exist at+ * runtime — and parsing is the point: it proves the file the editor imports+ * from still declares what the editor thinks it does.+ */+function publishedStepTypes(): string[] {+ const path = join(__dirname, '../../../../../packages/types/src/playbook.ts');+ const source = readFileSync(path, 'utf8');+ const start = source.indexOf('export type StepType =');+ expect(start, `no StepType union in ${path}`).toBeGreaterThan(-1);+ const body = source.slice(start, source.indexOf(';', start));+ const members = [...body.matchAll(/\|\s*"([a-z_]+)"/g)].map((m) => m[1]);+ expect(members.length, 'the published union parsed to nothing').toBeGreaterThan(0);+ return members;+}++describe('the editor step vocabulary', () => {+ it('offers a form for every step type the published package declares', () => {+ const published = publishedStepTypes();+ expect([...ALL_STEP_TYPES].sort()).toEqual([...published].sort());+ });++ it('declares nothing the published package does not', () => {+ const published = new Set(publishedStepTypes());+ for (const type of ALL_STEP_TYPES) {+ expect(published.has(type), `${type} is not a published step type`).toBe(true);+ }+ });++ it('gives every type canvas and palette presentation', () => {+ for (const type of ALL_STEP_TYPES) {+ expect(STEP_TYPE_META[type], `no canvas metadata for ${type}`).toBeDefined();+ expect(STEP_TYPE_META[type].label).toBe(STEP_SCHEMAS[type].label);+ }+ });++ it('gives every type a label, a description and an execution class', () => {+ for (const type of ALL_STEP_TYPES) {+ const schema = STEP_SCHEMAS[type];+ expect(schema.type, `${type}: the key and the declared type disagree`).toBe(type);+ expect(schema.label.trim().length, `${type}: empty label`).toBeGreaterThan(0);+ expect(+ schema.description.trim().length,+ `${type}: empty description`,+ ).toBeGreaterThan(20);+ expect(['executed', 'governed', 'unimplemented']).toContain(schema.execution);+ }+ });++ it('never asks an author to paste a credential into a playbook', () => {+ // Credentials are resolved per tenant from the connector vault by+ // `services/api` at dispatch. A form collecting `cs_client_secret` would+ // be putting a secret in a document that gets exported and shared.+ const secretish = /(secret|password|token|api_key|client_id|credential)/i;+ for (const type of ALL_STEP_TYPES) {+ for (const field of STEP_SCHEMAS[type].fields) {+ // `send_email` and `reset_password`'s own label mention passwords+ // without collecting one; the key is what ends up in the document.+ expect(+ secretish.test(field.key),+ `${type}.${field.key} looks like a credential`,+ ).toBe(false);+ }+ }+ });+});++describe('a type the engine cannot run', () => {+ const unrunnable = ALL_STEP_TYPES.filter(+ (t) => STEP_SCHEMAS[t].execution === 'unimplemented',+ );++ it('is still known to the editor, so an imported playbook can be read', () => {+ // Not asserted to be `approval` specifically: the property worth holding+ // is that whatever is unrunnable is handled this way.+ expect(unrunnable.length).toBeGreaterThan(0);+ for (const type of unrunnable) {+ expect(STEP_SCHEMAS[type]).toBeDefined();+ expect(STEP_TYPE_META[type]).toBeDefined();+ }+ });++ it('is not offered as something to add', () => {+ for (const type of unrunnable) {+ expect(AUTHORABLE_STEP_TYPES).not.toContain(type);+ }+ // ...and everything else is.+ expect(AUTHORABLE_STEP_TYPES.length).toBe(+ ALL_STEP_TYPES.length - unrunnable.length,+ );+ });++ it('says why, rather than implying it will execute', () => {+ for (const type of unrunnable) {+ const schema = STEP_SCHEMAS[type];+ expect(schema.unavailable, `${type} has no reason recorded`).toBeTruthy();+ expect(schema.unavailable!.length).toBeGreaterThan(80);+ // The engine fails the step and the default policy aborts the run. The+ // editor has to say that, not hint at it.+ expect(schema.description.toLowerCase()).toContain('not runnable');+ }+ });++ it('reports the step as invalid so the author is told before they save', () => {+ for (const type of unrunnable) {+ const errors = validateStepFields(type, defaultParamsFor(type));+ expect(errors.length).toBeGreaterThan(0);+ expect(errors.some((e) => /not runnable/i.test(e.message))).toBe(true);+ }+ });++ it('carries no fields, so there is nothing to fill in that would do anything', () => {+ for (const type of unrunnable) {+ expect(STEP_SCHEMAS[type].fields).toHaveLength(0);+ }+ });+});++describe('a runnable type', () => {+ const runnable = ALL_STEP_TYPES.filter(+ (t) => STEP_SCHEMAS[t].execution !== 'unimplemented',+ );++ it('records no "unavailable" reason, which is reserved for what cannot run', () => {+ for (const type of runnable) {+ expect(STEP_SCHEMAS[type].unavailable).toBeUndefined();+ }+ });++ it('validates clean once its required fields are filled', () => {+ // A form that cannot produce a valid step is worse than the type being+ // absent, so every schema must have at least one set of inputs that+ // passes its own validator.+ //+ // Keyed on the full `StepType` so the compiler demands an entry for a new+ // verb. A `Partial<>` here would have been a sixth partial vocabulary in+ // a file written to stop there being a fifth.+ for (const type of runnable) {+ const params = { ...defaultParamsFor(type), ...VALID_PARAMS[type] };+ expect(validateStepFields(type, params), `${type} cannot be made valid`).toEqual(+ [],+ );+ }+ });+});++describe('the governed response verbs', () => {+ const governed = ALL_STEP_TYPES.filter(+ (t) => STEP_SCHEMAS[t].execution === 'governed',+ );++ it('collect a target under a key the engine resolves', () => {+ for (const type of governed) {+ const expected = TARGET_KEY[type];+ expect(expected, `${type} is governed and has no recorded target key`).not.toBeNull();+ const keys = STEP_SCHEMAS[type].fields.map((f) => f.key);+ expect(keys, `${type} does not collect ${expected}`).toContain(expected);+ }+ });++ it('offers no dry-run control, because nothing reads one', () => {+ // Whether a vendor is touched is decided by+ // `AISOC_PLAYBOOK_ACTIONS_EXECUTE` and the capability contract, not by a+ // param on the step. The shipped packs carry `dry_run` and the bridge+ // ignores it; a checkbox here would be a control that does nothing.+ for (const type of governed) {+ const keys = STEP_SCHEMAS[type].fields.map((f) => f.key);+ expect(keys, `${type} offers an inert dry_run control`).not.toContain('dry_run');+ }+ });+});diff --git a/apps/web/src/components/playbooks/types.ts b/apps/web/src/components/playbooks/types.tsindex 84f920d5a..2db449e10 100644--- a/apps/web/src/components/playbooks/types.ts+++ b/apps/web/src/components/playbooks/types.ts@@ -1,18 +1,24 @@/*** Shared TypeScript types for the Playbook editor and list UI.- * Mirrors services/agents/app/playbook/models.py+ *+ * `StepType` is re-exported from `@aisoc/types` rather than restated here.+ * The restatement was a nine-member union under a header comment claiming it+ * mirrored `services/agents/app/playbook/models.py`, which declares+ * twenty-two. Nothing checked the claim, and because `STEP_SCHEMAS` is keyed+ * `Record<StepType, StepSchema>` on the *local* union, thirteen missing forms+ * satisfied exhaustiveness and the build stayed green. Importing the published+ * union puts the compiler back in charge: a verb the engine grows is a type+ * error here until the editor can author it.+ *+ * `scripts/check_playbook_schema_parity.py` reads every declaration of this+ * vocabulary — the engine, the schema, the published package and this+ * directory — in both directions, so the comment above is a checked property+ * rather than an assertion.*/-export type StepType =- | 'enrich'- | 'investigate'- | 'notify'- | 'block_ip'- | 'isolate_host'- | 'create_ticket'- | 'close_case'- | 'http'- | 'condition';+import type { StepType } from '@aisoc/types';++export type { StepType, StepExecution } from '@aisoc/types';export type OnFailure = 'abort' | 'continue' | 'retry';diff --git a/scripts/check_playbook_schema_parity.py b/scripts/check_playbook_schema_parity.pyindex 8954cc227..8af6a9f64 100644--- a/scripts/check_playbook_schema_parity.py+++ b/scripts/check_playbook_schema_parity.py@@ -25,8 +25,43 @@ drift accumulates in the direction things actually change — the engine growsa verb and nobody tells the schema. That is how a sibling gate in this reporeported "OK" on a YAML file declaring 17 labels against Go code with 28.+The fifth vocabulary, and why the file list is not written down+---------------------------------------------------------------+This gate used to name the two TypeScript facts it cared about: the union in+``packages/types``. It never opened ``apps/web``, where the playbook editor+declared a nine-member union of its own under a header comment claiming it+mirrored the engine's twenty-two. Keying its form registry+``Record<StepType, StepSchema>`` on that local union meant exhaustiveness was+satisfied with thirteen forms missing, so the compiler was quiet and the gate+was looking somewhere else. The one step type an operator could actually+click was the one nothing checked.++Naming ``apps/web/.../stepSchemas.ts`` here would fix that file and leave the+next one free. So the TypeScript half is a **scan**: every ``.ts``/``.tsx``+file in the tree is parsed for collections of step-type literals, and any+collection that overlaps the engine's vocabulary is required either to match+it exactly or to be a recorded subset with a reason. A sixth vocabulary is a+failing build wherever somebody puts it.++What the scan credits, and what it cannot see+---------------------------------------------+``--list`` prints every collection it found and the verdict it reached, which+is the only way to tell a gate that found nothing from one that looked+nowhere. Two limits, stated because an unstated limit is a blind spot:++* A collection overlapping the vocabulary by fewer than two members is not+ treated as a vocabulary. ``new Set<StepType>(['close_case'])`` is a+ predicate about one verb, not a restatement of the list.+* The parser reads array elements, object keys and string-literal union+ members. A vocabulary assembled at runtime — by ``.map()`` over something+ else, or spread from another module — is not a literal and is not seen.+ Deriving one from ``STEP_SCHEMAS`` is how the editor's palette and canvas+ metadata are written, and that is the shape this gate wants to encourage:+ derived lists cannot drift, so not seeing them costs nothing.+Run:python3 scripts/check_playbook_schema_parity.py+ python3 scripts/check_playbook_schema_parity.py --listpython3 scripts/check_playbook_schema_parity.py --self-test"""@@ -76,6 +111,41 @@ _EXECUTION_CLASSES = _RUNS | {"unimplemented"}#: a new label on it._GOVERNED = "governed"+#: Directories the TypeScript scan never enters. Build output and vendored+#: packages are copies of something else; grading them would report the same+#: drift twice and, worse, make the gate's verdict depend on whether somebody+#: had run a build.+_TS_SKIP_DIRS = frozenset({"node_modules", ".git", "dist", "build", ".next", ".turbo", "coverage", "storybook-static"})++#: How much of a literal collection has to be step types before the gate+#: treats it as a statement about the vocabulary. One is a predicate about one+#: verb (``new Set<StepType>(['close_case'])``); two or more is a list.+_VOCABULARY_MIN_OVERLAP = 2++#: Literal collections of step types that are deliberately partial, keyed+#: ``<path>::<symbol>`` with the reason. Shrink-only and checked in both+#: directions: an entry naming a collection that no longer exists fails, and+#: so does one that has since become complete. Empty is the goal — every entry+#: is a place a future reader has to be told "yes, on purpose".+RECORDED_TS_SUBSETS: dict[str, str] = {}+++@dataclass(frozen=True)+class TsVocabulary:+ """One literal collection of step-type names found in TypeScript."""++ path: str+ symbol: str+ line: int+ kind: str+ members: frozenset[str]+ #: ``member -> execution class`` where the collection annotates one.+ execution: dict[str, str] = field(default_factory=dict)++ @property+ def ref(self) -> str:+ return f"{self.path}::{self.symbol}"+class GateError(RuntimeError):"""The gate could not inspect what it is supposed to inspect.@@ -98,6 +168,14 @@ class Registries:response_step_types: frozenset[str]#: The ``StepType`` union published in ``packages/types``.typescript_step_types: frozenset[str]+ #: Every literal collection of step types found anywhere in TypeScript,+ #: discovered rather than listed — see the module docstring.+ ts_vocabularies: tuple[TsVocabulary, ...]+ #: How many TypeScript files the scan opened to find them, and how many it+ #: could not finish reading and proved irrelevant instead.+ ts_files_scanned: int+ #: Files the reader could not finish, each proved to hold no vocabulary.+ ts_files_skipped: tuple[str, ...]execution: dict[str, str]schema_timeout_max: intschema_timeout_min: int@@ -253,6 +331,404 @@ def _typescript_step_types(root: Path) -> frozenset[str]:return members+# ---------------------------------------------------------------------------+# TypeScript scan — find every literal collection of step types in the tree+# ---------------------------------------------------------------------------+#+# Parsed with a small hand-written reader rather than transpiled: the gate runs+# in a Python job with jsonschema, pydantic and httpx installed and nothing+# else, and requiring a Node toolchain to check a TypeScript fact would mean+# the check gets dropped from the job that can afford it.+++def _closing_quote(text: str, start: int) -> int:+ """Index of the quote closing the one at ``start``, or -1 if there is none+ before the end of the line."""+ quote = text[start]+ i, n = start + 1, len(text)+ while i < n:+ ch = text[i]+ if ch == "\\":+ i += 2+ continue+ if ch == "\n":+ return -1+ if ch == quote:+ return i+ i += 1+ return -1+++def _mask_ts(text: str) -> tuple[str, list[tuple[int, int, str]], str]:+ """Blank comments and string interiors, keeping every offset.++ Returns the masked text, ``(open_quote_index, close_quote_index, value)``+ for each quoted string literal, and a non-empty reason when the file could+ not be read to the end. Structure is read from the mask so a brace inside+ a string or a comment cannot move the depth count; values are read from+ the list so the mask can be blank.++ Template literals are tracked with a stack because they nest: a+ ``${ … }`` interpolation is code again, and that code may contain another+ template. The first version of this treated a backtick as a plain quote,+ so ``` `a ${xs.map((k) => `\\`${k}\\``)} b` ``` desynchronised it and the+ remainder of the file — including the registry the gate exists to read —+ was swallowed into an unterminated string. Nothing said so; the scan+ simply found one declaration in that file instead of two and reported+ agreement. A parser that can silently stop reading is the same defect as a+ gate that never opened the file, which is why running out of input inside+ a string is now returned as a reason and refused by the caller rather than+ tolerated.+ """+ masked = list(text)+ strings: list[tuple[int, int, str]] = []+ #: ``["tpl", start]`` inside a template literal, ``["expr", depth]``+ #: inside one of its ``${ }`` interpolations.+ stack: list[list] = []+ i, n = 0, len(text)+ while i < n:+ ch = text[i]++ if stack and stack[-1][0] == "tpl":+ if ch == "\\" and i + 1 < n:+ masked[i] = " "+ if text[i + 1] != "\n":+ masked[i + 1] = " "+ i += 2+ continue+ if ch == "$" and i + 1 < n and text[i + 1] == "{":+ stack.append(["expr", 0])+ i += 2+ continue+ if ch == "`":+ stack.pop()+ i += 1+ continue+ if ch != "\n":+ masked[i] = " "+ i += 1+ continue++ if ch == "/" and i + 1 < n and text[i + 1] == "/":+ while i < n and text[i] != "\n":+ masked[i] = " "+ i += 1+ continue+ if ch == "/" and i + 1 < n and text[i + 1] == "*":+ end = text.find("*/", i + 2)+ if end == -1:+ return "".join(masked), strings, f"unterminated block comment opened at offset {i}"+ for j in range(i, end + 2):+ if text[j] != "\n":+ masked[j] = " "+ i = end + 2+ continue+ if ch in "\"'":+ # A quoted string may not contain a raw newline, so a quote with+ # no partner before the end of the line is not opening one — it is+ # an apostrophe in JSX text, or inside a regex literal such as+ # `/couldn\'t load the alert envelope/i`. Reading those as string+ # openers desynchronised the reader and swallowed the rest of the+ # file, which is the one outcome a scanner must not have.+ #+ # JSX and regex literals are why there is no attempt to lex `/`+ # here: `</div>` and `/>` are far more common in this tree than+ # division is, and a reader that guessed would be wrong more often+ # than the thing it was trying to fix.+ closed = _closing_quote(text, i)+ if closed == -1:+ i += 1+ continue+ chars: list[str] = []+ j = i + 1+ while j < closed:+ if text[j] == "\\":+ chars.append(text[j + 1])+ masked[j] = masked[j + 1] = " "+ j += 2+ continue+ chars.append(text[j])+ masked[j] = " "+ j += 1+ strings.append((i, closed, "".join(chars)))+ i = closed + 1+ continue+ if ch == "`":+ stack.append(["tpl", i])+ i += 1+ continue+ if stack and stack[-1][0] == "expr":+ if ch == "{":+ stack[-1][1] += 1+ elif ch == "}":+ if stack[-1][1] == 0:+ stack.pop()+ i += 1+ continue+ stack[-1][1] -= 1+ i += 1++ if stack:+ return "".join(masked), strings, f"ran out of input inside a template literal opened at offset {stack[0][1]}"+ return "".join(masked), strings, ""+++_OPEN_TO_CLOSE = {"{": "}", "[": "]", "(": ")"}+++def _matching(masked: str, start: int) -> int:+ """Index of the bracket closing the one at ``start``, or -1."""+ opener = masked[start]+ closer = _OPEN_TO_CLOSE[opener]+ depth = 0+ for i in range(start, len(masked)):+ if masked[i] == opener:+ depth += 1+ elif masked[i] == closer:+ depth -= 1+ if depth == 0:+ return i+ return -1+++def _depth_map(masked: str, start: int, end: int) -> list[int]:+ """Bracket depth at each offset in ``[start, end)``, relative to ``start``."""+ depths: list[int] = []+ depth = 0+ for i in range(start, end):+ ch = masked[i]+ if ch in "{[(":+ depth += 1+ elif ch in "}])":+ depth -= 1+ depths.append(depth)+ continue+ depths.append(depth)+ return depths+++_IDENT = re.compile(r"[A-Za-z_$][\w$]*")+_DECL = re.compile(r"\b(?:export\s+)?(?:const|let|var|type)\s+([A-Za-z_$][\w$]*)")+#: Skipped between the ``=`` and the literal, so `new Set([...])`,+#: `Object.freeze({...})` and `new Map<K, V>([...])` all reach their literal.+_WRAPPERS = re.compile(r"\s*(?:new\s+)?(?:[A-Za-z_$][\w$.]*)?\s*(?:<[^<>]*>)?\s*\(\s*")+++def _literal_start(masked: str, after: int) -> int:+ """Offset of the literal a declaration is initialised with, or -1.++ Walks past the type annotation to the assignment, then past any wrapping+ call. A union has no ``=``-then-bracket shape and is handled separately.+ """+ end = min(len(masked), after + 400)+ eq = -1+ i = after+ while i < end:+ if masked[i] == "=" and masked[i : i + 2] != "=>" and masked[i : i + 2] != "==" and masked[i - 1] not in "=!<>":+ eq = i+ break+ if masked[i] == ";":+ return -1+ i += 1+ if eq == -1:+ return -1+ pos = eq + 1+ for _ in range(3): # at most a couple of nested wrappers+ while pos < len(masked) and masked[pos] in " \t\r\n":+ pos += 1+ if pos < len(masked) and masked[pos] in "{[":+ return pos+ match = _WRAPPERS.match(masked, pos)+ if not match or match.end() == pos:+ return -1+ pos = match.end()+ return -1+++def _object_entries(masked: str, strings: list[tuple[int, int, str]], start: int, end: int) -> dict[str, tuple[int, int]]:+ """Top-level ``key: value`` spans of the object literal at ``[start, end]``."""+ depths = _depth_map(masked, start, end)+ by_start = {s: (e, v) for s, e, v in strings}+ entries: dict[str, tuple[int, int]] = {}+ i = start + 1+ while i < end:+ if depths[i - start] != 1 or masked[i] in " \t\r\n,":+ i += 1+ continue+ if masked[i] in "\"'`":+ close, value = by_start.get(i, (-1, ""))+ if close == -1:+ i += 1+ continue+ key, after = value, close + 1+ else:+ match = _IDENT.match(masked, i)+ if not match:+ i += 1+ continue+ key, after = match.group(0), match.end()+ colon = after+ while colon < end and masked[colon] in " \t\r\n":+ colon += 1+ if colon >= end or masked[colon] != ":":+ i = after+ continue+ value_start = colon + 1+ while value_start < end and masked[value_start] in " \t\r\n":+ value_start += 1+ if value_start < end and masked[value_start] in "{[(":+ value_end = _matching(masked, value_start)+ if value_end == -1:+ break+ else:+ value_end = value_start+ while value_end < end and (depths[value_end - start] != 1 or masked[value_end] != ","):+ value_end += 1+ entries[key] = (value_start, value_end)+ i = value_end + 1+ return entries+++def _top_level_strings(masked: str, strings: list[tuple[int, int, str]], start: int, end: int) -> list[str]:+ """String literals sitting directly inside the bracket at ``start``."""+ depths = _depth_map(masked, start, end)+ return [value for s, _e, value in strings if start < s < end and depths[s - start] == 1]+++def _union_members(masked: str, strings: list[tuple[int, int, str]], after: int) -> list[str]:+ """Members of a ``type X = | "a" | "b";`` union declared at ``after``."""+ end = masked.find(";", after)+ if end == -1:+ return []+ span = masked[after:end]+ if "=" not in span or "|" not in span:+ return []+ return [value for s, _e, value in strings if after < s < end]+++def _execution_property(entries: dict[str, dict[str, str]]) -> str | None:+ """The property, if any, by which a registry annotates execution class.++ Found by the shape of its values rather than by its name: a property+ present on every entry whose values are all execution classes is the+ execution annotation, whatever it is called. Reading it by name would let+ a rename silently drop the check that the editor's claims match the+ schema's.+ """+ if not entries:+ return None+ common = set.intersection(*(set(props) for props in entries.values()))+ found = [name for name in sorted(common) if all(props[name] in _EXECUTION_CLASSES for props in entries.values())]+ return found[0] if len(found) == 1 else None+++#: Any bare word, used only by the fallback below. Deliberately not restricted+#: to quoted strings: the editor's registry is an object literal with bare+#: identifier keys, so a quoted-only scan would have proved a file irrelevant+#: on the strength of not looking at the shape the vocabulary is actually+#: written in. Over-counting here is harmless — it only ever turns a silent+#: skip into a loud refusal.+_ANY_WORD = re.compile(r"[A-Za-z_][\w]*")+++def _scan_ts_file(path: Path, rel: str, engine_members: frozenset[str]) -> tuple[list[TsVocabulary], str]:+ """Every literal collection of strings declared in one TypeScript file.++ Returns the collections and, when the file could not be read to the end, a+ reason. The reason is not swallowed: ``_typescript_vocabularies`` proves+ the file is irrelevant before skipping it, because a half-read file and a+ clean one both produce "no vocabulary found here".+ """+ text = path.read_text(encoding="utf-8", errors="replace")+ masked, strings, unreadable = _mask_ts(text)+ if unreadable:+ # The reader is not a JavaScript engine — JSX text with an apostrophe+ # in it is the case it cannot finish. Skipping is only safe if the+ # file provably holds no vocabulary, and a vocabulary has to contain+ # at least two step-type literals in the raw bytes. Counting those is+ # a sound over-approximation: it cannot miss one.+ literals = {m.group(0) for m in _ANY_WORD.finditer(text)} & engine_members+ if len(literals) >= _VOCABULARY_MIN_OVERLAP:+ raise GateError(+ f"{rel}: the TypeScript reader could not parse the file to the end ({unreadable}), and it "+ f"mentions {len(literals)} step-type names ({', '.join(sorted(literals))}). Anything declared after "+ f"that point is invisible, so the gate refuses to report agreement over it."+ )+ return [], unreadable+ found: list[TsVocabulary] = []+ for decl in _DECL.finditer(masked):+ symbol = decl.group(1)+ line = masked.count("\n", 0, decl.start()) + 1+ if decl.group(0).lstrip().startswith(("type", "export type")):+ members = _union_members(masked, strings, decl.end())+ if members:+ found.append(TsVocabulary(rel, symbol, line, "union", frozenset(members)))+ continue+ start = _literal_start(masked, decl.end())+ if start == -1:+ continue+ end = _matching(masked, start)+ if end == -1:+ continue+ if masked[start] == "[":+ members = _top_level_strings(masked, strings, start, end)+ if members:+ found.append(TsVocabulary(rel, symbol, line, "array", frozenset(members)))+ continue+ spans = _object_entries(masked, strings, start, end)+ if not spans:+ continue+ # Each entry's own properties, so an execution annotation can be+ # recognised by the shape of its values.+ props: dict[str, dict[str, str]] = {}+ for key, (value_start, value_end) in spans.items():+ if masked[value_start : value_start + 1] != "{":+ continue+ inner = _object_entries(masked, strings, value_start, value_end)+ by_start = {s: v for s, _e, v in strings}+ props[key] = {name: by_start[vs] for name, (vs, _ve) in inner.items() if vs in by_start}+ execution_prop = _execution_property(props) if len(props) == len(spans) else None+ execution = {key: props[key][execution_prop] for key in spans} if execution_prop else {}+ found.append(TsVocabulary(rel, symbol, line, "object", frozenset(spans), execution))+ return found, ""+++def _typescript_vocabularies(root: Path, engine_members: frozenset[str]) -> tuple[tuple[TsVocabulary, ...], int, tuple[str, ...]]:+ """Every TypeScript collection in the tree that talks about step types.++ Returns the candidates, the number of files opened and the number proved+ irrelevant after the reader could not finish them — because "found+ nothing" and "scanned nothing" print the same word, and the second is the+ state this gate was in with respect to ``apps/web``.+ """+ scanned = 0+ skipped: list[str] = []+ candidates: list[TsVocabulary] = []+ for path in sorted(root.rglob("*.ts*")):+ if path.suffix not in {".ts", ".tsx"} or any(part in _TS_SKIP_DIRS for part in path.relative_to(root).parts):+ continue+ scanned += 1+ rel = str(path.relative_to(root))+ try:+ vocabularies, unreadable = _scan_ts_file(path, rel, engine_members)+ except (OSError, RecursionError) as exc:+ raise GateError(f"could not read {rel}: {exc}") from exc+ if unreadable:+ skipped.append(f"{rel} ({unreadable})")+ for vocabulary in vocabularies:+ if len(vocabulary.members & engine_members) >= _VOCABULARY_MIN_OVERLAP:+ candidates.append(vocabulary)+ if not scanned:+ raise GateError(f"no TypeScript files under {root}; the web vocabulary cannot be compared and a pass would mean nothing")+ if not candidates:+ raise GateError(+ f"scanned {scanned} TypeScript files and found no declaration of the step vocabulary. "+ "The published union and the editor's form registry are both meant to be here; "+ "refusing to report agreement having compared nothing."+ )+ return tuple(candidates), scanned, tuple(skipped)++def _validator_triggers(root: Path) -> frozenset[str]:"""``scripts/validate_playbooks.py`` keeps its own trigger allow-list."""scripts = str(root / "scripts")@@ -285,13 +761,18 @@ def collect(root: Path) -> Registries:schema = _load_schema(root)engine_mod, models_mod, bounds_mod = _import_engine(root)s_tmax, s_tmin, s_rmax = _schema_step_bounds(schema)+ model_step_types = frozenset(st.value for st in models_mod.StepType)+ ts_vocabularies, ts_files_scanned, ts_files_skipped = _typescript_vocabularies(root, model_step_types)return Registries(schema_step_types=_schema_step_types(schema),- model_step_types=frozenset(st.value for st in models_mod.StepType),+ model_step_types=model_step_types,handler_step_types=frozenset(st.value for st in engine_mod._HANDLERS),inline_step_types=_inline_step_types(engine_mod, models_mod),response_step_types=frozenset(st.value for st in engine_mod.RESPONSE_STEP_TYPES),typescript_step_types=_typescript_step_types(root),+ ts_vocabularies=ts_vocabularies,+ ts_files_scanned=ts_files_scanned,+ ts_files_skipped=ts_files_skipped,execution=_schema_execution(schema),schema_timeout_max=s_tmax,schema_timeout_min=s_tmin,@@ -312,8 +793,15 @@ def collect(root: Path) -> Registries:# ----------------------------------------------------------------------------def compare(reg: Registries) -> list[str]:- """Every check, in both directions. Returns human-readable failures."""+def compare(reg: Registries, *, recorded_subsets: dict[str, str] | None = None) -> list[str]:+ """Every check, in both directions. Returns human-readable failures.++ ``recorded_subsets`` is a parameter rather than a read of the module+ global so the self-test drives the same value production does; a ratchet+ whose exemptions can only be exercised by editing the file is a ratchet+ nobody has seen work.+ """+ recorded_subsets = RECORDED_TS_SUBSETS if recorded_subsets is None else recorded_subsetserrors: list[str] = []if not reg.schema_step_types or not reg.model_step_types:@@ -373,6 +861,63 @@ def compare(reg: Registries) -> list[str]:f"code that type-checks against the package would be rejected by the server.")+ # 2c. every TypeScript declaration of the vocabulary <-> StepType, both+ # ways, over whatever the scan found rather than a list of files kept+ # here. The editor's nine-member union survived because this gate knew+ # the name of one TypeScript file and that was not the one an operator+ # clicked.+ if not reg.ts_vocabularies:+ return errors + ["no TypeScript declaration of the step vocabulary was found; the comparison would pass on nothing"]++ for vocabulary in reg.ts_vocabularies:+ recorded = recorded_subsets.get(vocabulary.ref)+ missing = reg.model_step_types - vocabulary.members+ invented = vocabulary.members - reg.model_step_types+ if not missing and not invented:+ if recorded:+ errors.append(+ f"a recorded subset lists {vocabulary.ref} as deliberate and it now declares the "+ f"whole vocabulary; remove the entry rather than leaving it to excuse a future gap."+ )+ continue+ if recorded and not invented:+ continue+ for member in sorted(missing):+ errors.append(+ f"{vocabulary.ref} ({vocabulary.kind}, line {vocabulary.line}) omits step type {member!r} that "+ f"`StepType` implements — a vocabulary that is a subset of the engine's is a verb the product "+ f"runs and this surface cannot express. Complete it, or record it in RECORDED_TS_SUBSETS with a reason."+ )+ for member in sorted(invented):+ errors.append(+ f"{vocabulary.ref} ({vocabulary.kind}, line {vocabulary.line}) declares step type {member!r} that "+ f"`StepType` does not implement — code written against it would be rejected by the server."+ )++ # 2d. execution classes declared in TypeScript <-> `x-aisoc-execution`,+ # both ways. A surface that tells an author a step will run when the+ # schema says it is unimplemented is the same lie in a nearer place.+ for vocabulary in reg.ts_vocabularies:+ if not vocabulary.execution:+ continue+ for member, declared in sorted(vocabulary.execution.items()):+ published = reg.execution.get(member)+ if published is None:+ errors.append(f"{vocabulary.ref} annotates {member!r} as {declared!r} and `x-aisoc-execution` does not describe it at all.")+ elif declared != published:+ errors.append(+ f"{vocabulary.ref} tells an author {member!r} is {declared!r} while `x-aisoc-execution` "+ f"says {published!r} — the surface and the contract disagree about what will happen."+ )+ for member in sorted(frozenset(reg.execution) - frozenset(vocabulary.execution)):+ errors.append(+ f"{vocabulary.ref} annotates execution for some step types and not for {member!r}, so what the "+ f"engine does with it is unstated exactly where somebody is choosing it."+ )++ for ref in sorted(set(recorded_subsets) - {v.ref for v in reg.ts_vocabularies}):+ errors.append(f"a recorded subset lists {ref!r}, which the scan did not find; remove the entry")+# 3b. `governed` claims <-> the engine's response-verb set, both ways.# A step labelled `governed` that the engine answers from inside its# own process is the exact defect this label replaced: `block_ip` used@@ -510,6 +1055,78 @@ def self_test(reg: Registries) -> list[str]:replace(reg, typescript_step_types=reg.typescript_step_types | {"create_ticket_jira"}),"which `StepType` does not implement",)++ # The scanned half. Perturbing a discovered vocabulary rather than a+ # named field is the point: these are the directions that let the+ # editor's nine-member union sit unnoticed behind a green build.+ if not reg.ts_vocabularies:+ failures.append("self-test: no TypeScript vocabulary was discovered; the scan directions cannot be tested")+ else:+ sample = reg.ts_vocabularies[0]++ def with_vocabulary(vocabulary: TsVocabulary) -> Registries:+ rest = tuple(v for v in reg.ts_vocabularies if v.ref != vocabulary.ref)+ return replace(reg, ts_vocabularies=(vocabulary, *rest))++ expect(+ # Precisely the defect: a surface declaring a subset of the+ # vocabulary, exhaustive against itself and short of the engine.+ "a scanned TypeScript surface declares fewer step types than the engine runs",+ with_vocabulary(replace(sample, members=sample.members - {victim})),+ "omits step type",+ )+ expect(+ "a scanned TypeScript surface invents a step type",+ with_vocabulary(replace(sample, members=sample.members | {absent})),+ "does not implement",+ )+ expect(+ "the scan finds no declaration at all",+ replace(reg, ts_vocabularies=()),+ "would pass on nothing",+ )+ # The recorded-subset ratchet, in both directions. Driven through+ # `compare`'s parameter rather than the module global so the test+ # perturbs the same value production reads.+ shrunk = replace(sample, members=sample.members - {victim})+ excused = compare(+ replace(reg, ts_vocabularies=(shrunk, *reg.ts_vocabularies[1:])),+ recorded_subsets={shrunk.ref: "recorded for the self-test"},+ )+ if any("omits step type" in e for e in excused):+ failures.append("self-test: a recorded subset was still reported as drift, so the exemption does nothing")+ stale = compare(reg, recorded_subsets={sample.ref: "recorded for the self-test"})+ if not any("remove the entry rather than leaving it" in e for e in stale):+ failures.append("self-test: a recorded subset that now declares the whole vocabulary was not reported as stale")+ ghost = compare(reg, recorded_subsets={"nowhere.ts::Ghost": "recorded for the self-test"})+ if not any("which the scan did not find" in e for e in ghost):+ failures.append("self-test: a recorded subset naming a collection that does not exist was not reported")++ annotated = next((v for v in reg.ts_vocabularies if v.execution), None)+ if annotated is None:+ failures.append(+ "self-test: no scanned vocabulary annotates an execution class, so the surface-vs-schema "+ "directions are untested — the editor is supposed to carry one"+ )+ else:+ member = sorted(annotated.execution)[0]+ expect(+ "a surface promises an execution the schema does not",+ with_vocabulary(replace(annotated, execution={**annotated.execution, member: "executed"}))+ if annotated.execution[member] != "executed"+ else with_vocabulary(replace(annotated, execution={**annotated.execution, member: "unimplemented"})),+ "the surface and the contract disagree",+ )+ expect(+ "a surface annotates some step types and silently omits one",+ with_vocabulary(replace(annotated, execution={k: v for k, v in annotated.execution.items() if k != member})),+ "is unstated exactly where somebody is choosing it",+ )+ expect(+ "a surface annotates a step type the schema never declared",+ with_vocabulary(replace(annotated, execution={**annotated.execution, absent: "executed"})),+ "does not describe it at all",+ )expect("declared type with no execution annotation",replace(reg, execution={k: v for k, v in reg.execution.items() if k != victim}),@@ -584,6 +1201,11 @@ def main() -> int:parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)parser.add_argument("--repo-root", default=None, help="Tree to inspect (default: the repo this script lives in)")parser.add_argument("--self-test", action="store_true", help="Prove the gate detects injected drift in each direction")+ parser.add_argument(+ "--list",+ action="store_true",+ help="Print every declaration of the vocabulary the scan credited, and what it credited it as",+ )args = parser.parse_args()try:@@ -607,8 +1229,36 @@ def main() -> int:print("execution " + " | ".join(f"{k} {v}" for k, v in counts.items()))print(f"bounds timeout {reg.schema_timeout_min}..{reg.schema_timeout_max}s | retries <={reg.schema_retry_max}")print(f"playbooks scanned {len(scanned)}")+ unreadable = len(reg.ts_files_skipped)+ annotating = sum(1 for v in reg.ts_vocabularies if v.execution)+ print(+ f"typescript {reg.ts_files_scanned} files read "+ f"({unreadable} unparseable, each proved to hold no vocabulary) | "+ f"{len(reg.ts_vocabularies)} declaration(s) of the vocabulary | "+ f"{annotating} annotating execution"+ )print()+ if args.list:+ # What it credits, not what it flags. A gate that only prints its+ # complaints cannot be told apart from one whose scan matched nothing.+ print("declarations of the step vocabulary found in TypeScript:")+ for vocabulary in sorted(reg.ts_vocabularies, key=lambda v: v.ref):+ verdict = "complete" if vocabulary.members == reg.model_step_types else "DIFFERS from StepType"+ annotation = f", execution for {len(vocabulary.execution)}" if vocabulary.execution else ""+ where = f"{vocabulary.ref} ({vocabulary.kind}, line {vocabulary.line})"+ print(f" {verdict:<22} {len(vocabulary.members):>3} members{annotation} {where}")+ print(+ f" (a collection overlapping the vocabulary by fewer than {_VOCABULARY_MIN_OVERLAP} members is "+ f"not treated as one; runtime-derived lists are not literals and are not seen)"+ )+ if reg.ts_files_skipped:+ print()+ print("files the reader could not finish, each checked for step-type literals before being skipped:")+ for note in reg.ts_files_skipped:+ print(f" {note}")+ print()+errors = compare(reg)if args.self_test:diff --git a/services/agents/app/playbook/engine.py b/services/agents/app/playbook/engine.pyindex 5b674f66f..a7c1d16eb 100644--- a/services/agents/app/playbook/engine.py+++ b/services/agents/app/playbook/engine.py@@ -560,15 +560,22 @@ async def _handle_osquery_live_query(step: PlaybookStep, context: dict[str, Any]from app.clients.osctrl_client import OsctrlClient # noqa: PLC0415from app.clients.osquery_allowlist import AllowlistError # noqa: PLC0415except ModuleNotFoundError as exc:+ # Raised, not returned. A returned dict leaves ``step_status`` at+ # SUCCESS, so every live query in the shipped agents image — where+ # these clients are always absent — was reported as a step that ran+ # while nothing had been asked of any endpoint. That is the same+ # defect the missing-handler branch above exists to remove, and it+ # became reachable from the console the moment the editor could+ # author this step type.+ #+ # Permanent because the module will not appear between attempt one+ # and attempt four: the image either ships the clients or it does not.logger.error("playbook.osquery_clients_unavailable: %s", exc)- return {- "error": (- "osquery_live_query is not executable in the agents service: the "- "osquery backend clients ship in services/actions. Run this step "- "through the actions service, or remove it from the playbook."- ),- "partial": True,- }+ raise PermanentStepFailure(+ "osquery_live_query is not executable in the agents service: the "+ "osquery backend clients ship in services/actions. Run this step "+ "through the actions service, or remove it from the playbook."+ ) from excbackend: str = step.params.get("backend", "osctrl")target_hosts: list[str] = step.params.get("target_hosts") or [context.get("host_id") or context.get("host", "")]diff --git a/tests/test_playbook_schema_parity_gate.py b/tests/test_playbook_schema_parity_gate.pyindex 6af80ec08..de35f4bbc 100644--- a/tests/test_playbook_schema_parity_gate.py+++ b/tests/test_playbook_schema_parity_gate.py@@ -164,6 +164,172 @@ def test_catches_playbook_level_key_drift_in_both_directions(registries, gate):assert any("does not declare" in e for e in gate.compare(model_only))+# ---------------------------------------------------------------------------+# The TypeScript scan: every declaration of the vocabulary, wherever it is+# ---------------------------------------------------------------------------+++def test_the_scan_finds_the_editors_registry_and_the_published_union(registries):+ """The gate used to know one TypeScript file by name and it was not the+ one an operator clicked. The scan has to reach both."""+ found = {v.path for v in registries.ts_vocabularies}+ assert "packages/types/src/playbook.ts" in found+ assert any(path.startswith("apps/web/") for path in found), (+ "no declaration of the step vocabulary was found under apps/web; the editor's form registry "+ f"is meant to be there. Found: {sorted(found)}"+ )+++def test_every_declaration_it_found_matches_the_engine(registries):+ for vocabulary in registries.ts_vocabularies:+ assert vocabulary.members == registries.model_step_types, (+ f"{vocabulary.ref} declares {len(vocabulary.members)} step types against the engine's {len(registries.model_step_types)}"+ )+++def test_the_editor_declares_an_execution_class_for_every_step_type(registries):+ """A surface that offers a step has to say what will happen when it runs,+ and say the same thing the schema does."""+ annotated = [v for v in registries.ts_vocabularies if v.execution]+ assert annotated, "no TypeScript surface annotates execution; the editor is supposed to"+ for vocabulary in annotated:+ assert vocabulary.execution == registries.execution, f"{vocabulary.ref} disagrees with `x-aisoc-execution`"+++def test_catches_a_web_surface_that_declares_fewer_step_types(registries, gate):+ """The exact defect: a nine-member union satisfying `Record<StepType, …>`+ against itself while the engine ran twenty-two."""+ sample = registries.ts_vocabularies[0]+ victim = sorted(sample.members)[0]+ shrunk = dataclasses.replace(sample, members=sample.members - {victim})+ broken = _perturb(registries, ts_vocabularies=(shrunk, *registries.ts_vocabularies[1:]))+ assert any("omits step type" in e for e in gate.compare(broken))+++def test_catches_a_web_surface_that_invents_a_step_type(registries, gate):+ sample = registries.ts_vocabularies[0]+ grown = dataclasses.replace(sample, members=sample.members | {"quarantine_mailbox"})+ broken = _perturb(registries, ts_vocabularies=(grown, *registries.ts_vocabularies[1:]))+ assert any("does not implement" in e for e in gate.compare(broken))+++def test_catches_a_surface_promising_an_execution_the_schema_denies(registries, gate):+ annotated = next(v for v in registries.ts_vocabularies if v.execution)+ member = next(k for k, v in annotated.execution.items() if v == "unimplemented")+ lying = dataclasses.replace(annotated, execution={**annotated.execution, member: "executed"})+ broken = _perturb(+ registries,+ ts_vocabularies=tuple(lying if v.ref == annotated.ref else v for v in registries.ts_vocabularies),+ )+ assert any("the surface and the contract disagree" in e for e in gate.compare(broken))+++def test_refuses_to_pass_having_found_no_declaration(registries, gate):+ """Found nothing and scanned nothing print the same word."""+ assert any("would pass on nothing" in e for e in gate.compare(_perturb(registries, ts_vocabularies=())))+++def test_the_recorded_subset_ratchet_works_in_both_directions(registries, gate):+ sample = registries.ts_vocabularies[0]+ victim = sorted(sample.members)[0]+ shrunk = dataclasses.replace(sample, members=sample.members - {victim})+ partial = _perturb(registries, ts_vocabularies=(shrunk, *registries.ts_vocabularies[1:]))++ excused = gate.compare(partial, recorded_subsets={shrunk.ref: "recorded for the test"})+ assert not any("omits step type" in e for e in excused), "a recorded subset was not excused"++ stale = gate.compare(registries, recorded_subsets={sample.ref: "recorded for the test"})+ assert any("remove the entry" in e for e in stale), "an exemption that stopped being needed was not reported"++ ghost = gate.compare(registries, recorded_subsets={"nowhere.ts::Ghost": "recorded for the test"})+ assert any("which the scan did not find" in e for e in ghost)+++def test_the_recorded_subset_list_is_empty_on_this_tree(gate):+ """Every entry is a place somebody has to be told "yes, on purpose". The+ list exists so an exception must be written down, not so it gets used."""+ assert gate.RECORDED_TS_SUBSETS == {}+++# ---------------------------------------------------------------------------+# The reader, which is where a scan silently loses a file+# ---------------------------------------------------------------------------+++def test_the_reader_survives_a_template_literal_with_nested_backticks(gate):+ """The first version of the reader treated a backtick as a plain quote, so+ an interpolation containing another template desynchronised it and every+ declaration after that point in the file was invisible. The scan reported+ agreement having never seen the registry."""+ source = "const A = ['enrich'];\nconst h = `x ${xs.map((k) => `\\`${k}\\``).join(', ')} y`;\nconst B = ['notify'];\n"+ masked, _strings, unreadable = gate._mask_ts(source)+ assert unreadable == "", unreadable+ assert "const B" in masked, "the reader stopped before the end of the file"+++ "source",+ [+ "const a = /couldn\\'t load the envelope/i;\nconst B = ['enrich', 'notify'];\n",+ "const el = <p>Don't</p>;\nconst B = ['enrich', 'notify'];\n",+ ],+ ids=["apostrophe-in-a-regex", "apostrophe-in-jsx-text"],+)+def test_a_lone_apostrophe_does_not_swallow_the_rest_of_the_file(gate, source: str):+ """A quoted string cannot contain a raw newline, so a quote with no+ partner on its line is not opening one."""+ masked, _strings, unreadable = gate._mask_ts(source)+ assert unreadable == ""+ assert "const B" in masked+++def test_a_file_the_reader_cannot_finish_is_never_silently_skipped(gate, tmp_path: Path):+ """Skipping is only safe when the file provably holds no vocabulary, and a+ vocabulary needs at least two step-type literals in the raw bytes."""+ path = tmp_path / "broken.tsx"+ path.write_text("const t = `unterminated\nconst M = { isolate_host: 1, block_ip: 2, disable_user: 3 };\n")+ with pytest.raises(gate.GateError) as exc:+ gate._scan_ts_file(path, "broken.tsx", frozenset({"isolate_host", "block_ip", "disable_user"}))+ assert "could not parse the file to the end" in str(exc.value)+++def test_a_file_the_reader_cannot_finish_and_that_mentions_nothing_is_skipped(gate, tmp_path: Path):+ path = tmp_path / "prose.tsx"+ path.write_text("const t = `unterminated\nconst greeting = 'hello';\n")+ found, unreadable = gate._scan_ts_file(path, "prose.tsx", frozenset({"isolate_host", "block_ip"}))+ assert found == []+ assert unreadable, "the skip has to be reported so it can be counted"+++def test_the_scan_reads_more_than_a_handful_of_files(registries):+ """A glob that stops matching is the cheapest way for this to go quiet."""+ assert registries.ts_files_scanned > 100, f"only {registries.ts_files_scanned} TypeScript files scanned"+ assert len(registries.ts_files_skipped) * 4 < registries.ts_files_scanned, (+ f"{len(registries.ts_files_skipped)} of {registries.ts_files_scanned} files could not be read; "+ "the reader has regressed far enough that its skips are no longer incidental"+ )+++def test_the_reader_finds_each_shape_a_vocabulary_can_take(gate, tmp_path: Path):+ """Union, array and object — plus the execution annotation, recognised by+ the shape of its values rather than by the property's name."""+ path = tmp_path / "shapes.ts"+ path.write_text(+ 'export type S = \n | "enrich"\n | "notify";\n'+ "const LIST: S[] = ['enrich', 'notify'];\n"+ "const REG = {\n"+ " enrich: { kind: 'executed', label: 'a' },\n"+ " notify: { kind: 'governed', label: 'b' },\n"+ "};\n"+ )+ found, _ = gate._scan_ts_file(path, "shapes.ts", frozenset({"enrich", "notify"}))+ by_symbol = {v.symbol: v for v in found}+ assert set(by_symbol) == {"S", "LIST", "REG"}+ assert {v.kind for v in found} == {"union", "array", "object"}+ assert by_symbol["REG"].execution == {"enrich": "executed", "notify": "governed"}+ assert by_symbol["LIST"].execution == {}++# ---------------------------------------------------------------------------# The gate's own footing# ---------------------------------------------------------------------------