# Command reference

> Command reference

Source: https://docs.sommatic.ai/en/command-center/commands/

## Read commands

### `/extract-from-insight`

`command_center.extract.from_insight`

Extract structured data from an InsightSource

#### Purpose

Extracts specific fields from a source's live data snapshot. Rather than returning the full payload (as `read.insights.snapshot` does), this command plucks only the requested fields, producing a cleaner, smaller result for the synthesis LLM.

#### When to Use

- When the LLM only needs specific fields from a source, not the full payload.
- To reduce synthesis context size when the source payload is large.
- When the user asks for a specific attribute: "What's the current project's status?" → extract `project.status` from `page-context`.

#### Arguments

| Argument | Type | Required | Description |
|----------|------|----------|-------------|
| `source_id` | `string` | Yes | The ID of the source to extract from. |
| `fields` | `string[]` | No | Dot-notation paths to extract (e.g., `["project.name", "project.status"]`). If omitted, returns all top-level keys. |

#### Return Value

```js
{
  ok: true,
  source_id: "page-context",
  data: {
    "project.name": "Development",
    "project.status": "active"
  }
}
```

If `fields` is not provided:

```js
{
  ok: true,
  source_id: "page-context",
  data: {
    context: "...",
    type: "project-detail",
    project: { /* full object */ },
    recentChats: [ /* ... */ ],
    metadata: { isLoading: false }
  }
}
```

##### Error Cases

```js
{ ok: false, error: { code: "MISSING_SOURCE_ID", message: "source_id is required" } }
{ ok: false, error: { code: "SOURCE_NOT_FOUND", message: "Source [xyz] is not registered" } }
{ ok: false, error: { code: "NO_DATA", message: "Source [page-context] has no data yet" } }
```

#### Implementation

```js
// commands/read/extractFromInsight.action.js

const getNestedValue = (obj, path) => {
  return path.split('.').reduce((acc, key) => (acc != null ? acc[key] : undefined), obj);
};

export const action = (args, registry) => {
  const { source_id, fields } = args || {};

  if (!source_id) {
    return { ok: false, error: { code: 'MISSING_SOURCE_ID', message: 'source_id is required' } };
  }

  const metadata = registry?.getSourceMetadata?.(source_id);
  if (!metadata) {
    return { ok: false, error: { code: 'SOURCE_NOT_FOUND', message: `Source [${source_id}] is not registered` } };
  }

  const snapshot = registry?.getSnapshot?.(source_id);
  if (!snapshot?.payload) {
    return { ok: false, error: { code: 'NO_DATA', message: `Source [${source_id}] has no data yet` } };
  }

  const payload = snapshot.payload;

  if (!Array.isArray(fields) || fields.length === 0) {
    return { ok: true, source_id, data: payload };
  }

  const data = {};
  for (const field of fields) {
    data[field] = getNestedValue(payload, field);
  }

  return { ok: true, source_id, data };
};
```

#### Command Definition

```js
{
  id: 'command_center.extract.from_insight',
  label: '/extract-insight',
  description: 'Extract specific fields from an InsightSource snapshot',
  schema: {
    type: 'object',
    properties: {
      source_id: {
        type: 'string',
        description: "ID of the source. Use 'page-context' for the current page."
      },
      fields: {
        type: 'array',
        items: { type: 'string' },
        description: "Dot-notation paths to extract (e.g. 'project.name', 'metadata.isLoading'). Omit for all top-level keys."
      }
    },
    required: ['source_id']
  },
  action: (args) => Read.extractFromInsight(args, registry),
}
```

#### Notes

- Dot-notation traversal supports two levels: `"project.name"` → `payload.project.name`.
- Fields that don't exist in the payload return `undefined` for that key.
- Using `fields` is highly recommended when the source payload is large, as it significantly reduces the data passed to the synthesis LLM.

### `/extract-from-targets`

`command_center.extract.from_targets`

Extract data from published targets

#### Purpose

Reads the current values from one or more UI targets (form fields, inputs, labels). This allows the LLM to inspect what values a user has typed or selected in a form without submitting it.

Optionally maps extracted values to a named schema for structured output.

#### When to Use

- When the user asks "What values are in the form right now?"
- To validate or inspect form state before calling `exec.ui.submit_form`.
- As an audit step: "Read the current filter values applied to the grid."
- To pre-populate an AI suggestion based on current form state.

#### Arguments

| Argument | Type | Required | Description |
|----------|------|----------|-------------|
| `targets` | `string[]` | Yes | Array of target references (`{surface_id}::{target_id}` format). |
| `schema` | `object` | No | Optional mapping schema. Keys are output field names; values have `source_ref` pointing to a target ref. |

#### Return Value

Without schema:

```js
{
  ok: true,
  data: [
    { ref: "create-project-form::project-name-input", label: "Project Name", type: "input", value: "My New Project" },
    { ref: "create-project-form::status-dropdown", label: "Status", type: "select", value: "active" }
  ]
}
```

With schema:

```js
// schema: { name: { source_ref: "create-project-form::project-name-input" }, status: { source_ref: "create-project-form::status-dropdown" } }
{
  ok: true,
  data: {
    name: "My New Project",
    status: "active"
  }
}
```

If some targets fail:

```js
{
  ok: false,
  data: [
    { ref: "form::input-1", label: "Name", type: "input", value: "Test" },
  ],
  errors: [
    { target_ref: "form::unknown-input", error: "Target not found" }
  ]
}
```

#### Implementation

```js
// commands/read/extractFromTargets.action.js
export const action = (args, registry) => {
  const { targets, schema } = args || {};

  if (!Array.isArray(targets) || targets.length === 0) {
    return { ok: false, error: { code: 'MISSING_TARGETS', message: 'targets array is required' } };
  }

  const extractedItems = [];
  const errors = [];

  for (const targetRef of targets) {
    const resolved = registry?.resolveTarget?.(targetRef);
    if (!resolved) {
      errors.push({ target_ref: targetRef, error: 'Target not found' });
      continue;
    }

    const { target } = resolved;
    const item = { ref: targetRef, label: target.label || '', type: target.type || 'unknown' };

    if (target.handlers?.getValue) {
      try { item.value = target.handlers.getValue(); }
      catch (err) { item.value = null; item.error = err.message; }
    } else if (target.value !== undefined) {
      item.value = target.value;
    }

    extractedItems.push(item);
  }

  // Apply schema mapping if provided
  if (schema && typeof schema === 'object' && schema.properties) {
    const mapped = {};
    for (const [key, descriptor] of Object.entries(schema.properties)) {
      const sourceRef = descriptor?.source_ref || key;
      const match = extractedItems.find((item) => item.ref === sourceRef);
      mapped[key] = match?.value ?? null;
    }
    return { ok: errors.length === 0, data: mapped, errors: errors.length > 0 ? errors : undefined };
  }

  return { ok: errors.length === 0, data: extractedItems, errors: errors.length > 0 ? errors : undefined };
};
```

#### Command Definition

```js
{
  id: 'command_center.extract.from_targets',
  label: '/extract-targets',
  description: 'Extract current values from specified UI targets',
  schema: {
    type: 'object',
    properties: {
      targets: {
        type: 'array',
        items: { type: 'string' },
        description: "Array of target references in format 'surface_id::target_id'."
      },
      schema: {
        type: 'object',
        description: 'Optional mapping schema: { properties: { fieldName: { source_ref: "surface::target" } } }'
      }
    },
    required: ['targets']
  },
  action: (args) => Read.extractFromTargets(args, registry),
}
```

#### Target Registration Requirements

Targets must expose a `getValue` handler to be extractable:

```jsx
targets: [
  {
    id: 'project-name-input',
    label: 'Project Name',
    type: 'input',
    handlers: {
      getValue: () => nameValue,      // ← Required for extraction
      fill: (v) => setNameValue(v),
    },
  },
]
```

#### Notes

- If a target has neither a `getValue` handler nor a `value` property, its extracted value will be `undefined`.
- Schema mapping is useful when you want to pass structured form data to a subsequent exec command or synthesis step.
- Use `read.ui.targets.list` first to discover available `target_ref` strings.

### `/observe-ui`

`command_center.observe.ui`

Discover candidate actions from instruction

#### Purpose

Analyzes all registered surfaces and targets to suggest UI actions relevant to a given natural language instruction. This is the "smart discovery" command — it scores each surface and target against the instruction and returns the most relevant candidates.

Unlike `read.ui.targets.list`, which returns a raw list, `observe.ui` uses semantic scoring to match the instruction to specific targets and methods.

#### When to Use

- When the user says "What can I do here?" or "How do I filter the list?"
- As the first step in a plan where the LLM needs to discover which surface/target to interact with.
- When the user's instruction is ambiguous and the LLM needs to narrow down the target.

#### Arguments

| Argument | Type | Required | Description |
|----------|------|----------|-------------|
| `instruction` | `string` | Yes | Natural language description of the desired action. |

#### Return Value

```js
{
  ok: true,
  candidates: [
    {
      surface_id: "project-list-grid",
      target_ref: "project-list-grid::applyFilter",
      label: "applyFilter",
      type: "virtual",
      method: "applyFilter",
      score: 3,
      hint: "Call 'applyFilter' on surface 'project-list-grid'"
    },
    {
      surface_id: "project-list-grid",
      target_ref: "project-list-grid::selectRows",
      label: "selectRows",
      type: "virtual",
      method: "selectRows",
      score: 2
    }
  ]
}
```

If no relevant candidates found:

```js
{ ok: true, candidates: [] }
```

#### Scoring Algorithm

Each surface is scored by `computeSurfaceScore(instruction, surface, surfaceId)`:
- +1 if instruction mentions the surface type (e.g., "grid")
- +1 per surface field match (id, label, description) against keywords in the instruction
- Minimum score 0

Each target is scored by keyword matching its label, type, and supported methods against the instruction.

**Virtual targets** (generated from handlers when `targets: []`) skip the strict `isMethodRelevant` check if the parent surface has a positive score, ensuring that general queries like "what can I do in the grid?" still return all handler-based actions.

#### Virtual Targets

When a surface has empty `targets` but exposes `handlers`, virtual targets are generated dynamically:

```js
// Surface registered with:
handlers: {
  applyFilter: (value) => setFilter(value),
  selectRows: (ids) => setSelectedRowIds(ids),
}

// Generates virtual targets:
[
  { id: "project-list-grid::applyFilter", label: "applyFilter", type: "virtual", handlers: { applyFilter: fn } },
  { id: "project-list-grid::selectRows", label: "selectRows", type: "virtual", handlers: { selectRows: fn } }
]
```

#### Implementation (Summary)

```js
// commands/read/observeUi.action.js

export const action = (args, registry) => {
  const { instruction } = args || {};

  const surfaces = registry?.getSurfaces?.() || [];
  const candidates = [];

  for (const surface of surfaces) {
    let targets = registry?.getTargets?.(surface.id) || [];
    let isVirtualSurface = false;

    // If no explicit targets, generate virtual targets from handlers
    if (targets.length === 0 && surface.handlers) {
      targets = buildVirtualTargets(surface.id, surface);
      isVirtualSurface = true;
    }

    const surfaceScore = computeSurfaceScore(instruction, surface, surface.id);

    for (const target of targets) {
      const targetScore = scoreTarget(instruction, target);

      // For virtual targets on scored surfaces, skip method relevance filtering
      if (isVirtualSurface && surfaceScore > 0) {
        candidates.push({ surface_id: surface.id, target_ref: target.id, ...target, score: surfaceScore + targetScore });
        continue;
      }

      if (targetScore > 0 || surfaceScore > 0) {
        candidates.push({ surface_id: surface.id, target_ref: target.id, ...target, score: surfaceScore + targetScore });
      }
    }
  }

  candidates.sort((a, b) => b.score - a.score);
  return { ok: true, candidates };
};
```

#### Command Definition

```js
{
  id: 'command_center.observe.ui',
  label: '/observe-ui',
  description: 'Discover UI actions relevant to a given instruction',
  schema: {
    type: 'object',
    properties: {
      instruction: {
        type: 'string',
        description: 'Natural language description of what the user wants to do.'
      }
    },
    required: ['instruction']
  },
  action: (args) => Read.observeUi(args, registry),
}
```

#### Notes

- `observe.ui` is best used when the LLM is uncertain which surface or target to target. For known surfaces, call the exec commands directly.
- The `target_ref` in each candidate is the string to pass to `exec.ui.act` or `extract.from_targets`.
- Empty candidates typically means no surfaces are registered or the instruction doesn't match any surface/target keywords.

### `/capabilities`

`command_center.read.capabilities`

See what reading/execution is enabled on host

#### Purpose

Reports everything the Command Center can currently do: all registered read commands, exec commands, available InsightSources, and registered surfaces. This is the system's self-description command.

#### When to Use

- When the user asks "What can you do?" or "What commands are available?"
- For agent self-discovery: when building multi-step plans and the LLM needs to know its own toolset.
- For debugging: to verify all commands are registered correctly.

#### Arguments

None.

#### Return Value

```js
{
  capabilities: {
    read_commands: [
      { id: "command_center.read.scope.get", label: "/get-scope", description: "Get current page context" },
      { id: "command_center.read.insights.list", label: "/list-sources", description: "List all available data sources" },
      // ... 16 more read commands
    ],
    exec_commands: [
      { id: "command_center.exec.navigate", label: "/navigate", description: "Navigate to a route" },
      { id: "command_center.exec.clipboard.copy", label: "/copy", description: "Copy text to clipboard" },
      // ... 14 more exec commands
    ],
    sources: [
      { id: "page-context", description: "Current page context." },
      { id: "org-context", description: "Organization metadata." }
    ],
    surfaces: [
      { id: "project-list-grid", type: "grid", label: "Project List" },
      { id: "create-project-form", type: "form", label: "Create Project Form" }
    ]
  }
}
```

#### Implementation

```js
// commands/read/getCapabilities.action.js
export const action = (registry) => {
  const readCommands = [];
  const execCommands = [];

  const commands = registry?.commands || [];
  for (const cmd of commands) {
    const entry = { id: cmd.id, label: cmd.label, description: cmd.description };
    if (cmd.id.includes('.read.') || cmd.id.includes('.observe.') || cmd.id.includes('.extract.')) {
      readCommands.push(entry);
    } else {
      execCommands.push(entry);
    }
  }

  const sources = registry?.listAllSources?.() || [];

  return {
    capabilities: {
      read_commands: readCommands,
      exec_commands: execCommands,
      sources,
      surfaces: registry?.getSurfaces?.() || [],
    },
  };
};
```

#### Command Definition

```js
{
  id: 'command_center.read.capabilities',
  label: '/capabilities',
  description: 'Report all available commands, sources, and surfaces',
  schema: {},
  action: () => Read.getCapabilities(registry),
}
```

#### Command Classification Logic

Commands are classified into `read_commands` or `exec_commands` based on ID segments:
- Contains `.read.`, `.observe.`, or `.extract.` → read command
- All others → exec command

This means `command_center.exec.navigate` goes to `exec_commands`, while `command_center.observe.ui` goes to `read_commands`.

#### Notes

- `sources` and `surfaces` reflect the currently mounted state — unmounted components' registrations are not included.
- The `registry.commands` getter reads from `allCommandsRef.current`, which always reflects the latest set of registered commands (including dynamically registered ones from the Navbar).
- This command is useful for bootstrapping: when the LLM starts a conversation with no prior context, it can call this first to understand its environment.

### `/context-pack`

`command_center.read.context.pack`

Pull multiple insights (Top-N or by IDs)

#### Purpose

Bundles the live data payloads of multiple InsightSources into a single aggregated object. This is useful when a user query requires context from more than one source at once.

#### When to Use

- When the LLM needs to combine data from multiple sources to answer a question.
- As a single-step alternative to multiple `read.insights.snapshot` calls.
- When building a comprehensive context package before a synthesis pass or an exec command.

#### Arguments

| Argument | Type | Required | Description |
|----------|------|----------|-------------|
| `source_ids` | `string[]` | No | Array of source IDs to include. If omitted, all registered sources are packed. |

#### Return Value

```js
{
  ok: true,
  context: {
    "page-context": {
      type: "project-detail",
      project: { id: "prj-...", name: "Development", status: "active" },
      metadata: { isLoading: false }
    },
    "org-context": {
      id: "org-232121",
      name: "Blackwood",
      plan: "enterprise"
    }
  },
  included: ["page-context", "org-context"],
  missing: []
}
```

If some sources have no data:

```js
{
  ok: true,
  context: { "page-context": { /* ... */ } },
  included: ["page-context"],
  missing: ["org-context"]   // Registered but no cached data yet
}
```

##### Error Cases

```js
{ ok: false, error: { code: "NO_SOURCES", message: "No sources available to pack" } }
```

#### Implementation

```js
// commands/read/contextPack.action.js
export const action = (args, registry) => {
  let sourceIds = args?.source_ids;

  if (!Array.isArray(sourceIds) || sourceIds.length === 0) {
    const allSources = registry?.listAllSources?.() || [];
    sourceIds = allSources.map((s) => s.id);
  }

  if (sourceIds.length === 0) {
    return { ok: false, error: { code: 'NO_SOURCES', message: 'No sources available to pack' } };
  }

  const context = {};
  const included = [];
  const missing = [];

  for (const id of sourceIds) {
    const snapshot = registry?.getSnapshot?.(id);
    if (snapshot?.payload) {
      context[id] = snapshot.payload;
      included.push(id);
    } else {
      missing.push(id);
    }
  }

  return { ok: true, context, included, missing };
};
```

#### Command Definition

```js
{
  id: 'command_center.read.context.pack',
  label: '/pack-context',
  description: 'Bundle multiple InsightSource payloads into a single context object',
  schema: {
    type: 'object',
    properties: {
      source_ids: {
        type: 'array',
        items: { type: 'string' },
        description: 'Source IDs to bundle. Omit to include all registered sources.'
      }
    }
  },
  action: (args) => Read.contextPack(args, registry),
}
```

#### Notes

- When `source_ids` is omitted, every registered source is included. This can produce very large payloads — use with caution with synthesis LLMs that have limited context windows.
- The synthesis context truncation in `CognitiveEntryManager` will trim this if needed.
- Use `read.insights.list` first to discover available source IDs, then call this command with a curated list.

### `/debug-exec-log`

`command_center.read.debug.execution_log`

View last N executions + receipts

#### Purpose

Returns the recent history of command executions — which commands were run, with what arguments, and what results they produced. This gives a complete audit trail of all actions the Command Center has taken.

#### When to Use

- When the user asks "What commands have been executed?" or "Show me the execution history."
- For debugging: to verify a previous command ran successfully and inspect its output.
- For auditing: to review all actions taken in a session.

#### Arguments

| Argument | Type | Required | Description |
|----------|------|----------|-------------|
| `limit` | `number` | No | Maximum number of entries to return. Defaults to `10`. |

#### Return Value

```js
{
  entries: [
    {
      command_id: "command_center.read.insights.describe",
      args: { source_id: "page-context" },
      status: "success",
      result: {
        ok: true,
        source: {
          id: "page-context",
          description: "Current Project Detail...",
          inferred_fields: ["context", "type", "project", "recentChats", "metadata"],
          has_data: true,
          captured_at: 1772075191118
        }
      },
      timestamp: 1772075191118
    },
    {
      command_id: "command_center.exec.clipboard.copy",
      args: { content: "hello world" },
      status: "success",
      result: { ok: true, title: "Copied to clipboard", receipt_id: "rcpt_1772075473717_byfawpr" },
      timestamp: 1772075473717
    }
  ]
}
```

#### Implementation

```js
// commands/read/debugExecutionLog.action.js
export const action = (args, registry) => {
  const limit = args?.limit || 10;
  const entries = registry?.getExecutionLog?.(limit) || [];
  return { entries };
};
```

#### Command Definition

```js
{
  id: 'command_center.read.debug.execution_log',
  label: '/execution-log',
  description: 'Show recent command execution history and results',
  schema: {
    type: 'object',
    properties: {
      limit: { type: 'number', description: 'Max entries to return (default: 10)' }
    }
  },
  action: (args) => Read.debugExecutionLog(args, registry),
}
```

#### How the Log Is Populated

Each time a command executes, `executePlan` calls:

```js
registry.pushDebugEntry('execution', {
  command_id: step.command_id,
  args: step.args,
  status: result ? 'success' : 'error',
  result,
  timestamp: Date.now(),
});
```

#### Synthesis Behavior with Large Logs

The execution log can produce very large JSON payloads (thousands of characters), especially when previous results include full source snapshots. The synthesis context pipeline handles this via:

1. **Per-result truncation:** Results over 4,000 chars are replaced with `[truncated — N chars. Summary: ...]`.
2. **Total cap:** If the combined context exceeds 12,000 chars, additional entries are dropped.

This prevents the synthesis LLM from hitting context window limits while still providing useful summaries.

#### Notes

- The log is **in-memory only** and lost on page refresh.
- The `status` field is `"success"` or `"error"`. Check `result.ok` for command-level success/failure details.
- To limit noise, use `limit: 5` or lower for synthesis calls; use higher values for manual debugging sessions.

### `/debug-router-log`

`command_center.read.debug.router_log`

View last N router decisions

#### Purpose

Returns the recent history of router LLM decisions — what plans the router generated for each user message, including the thought process, selected commands, and provider used.

This is primarily a debugging and observability tool.

#### When to Use

- When investigating why the LLM chose certain commands for a previous query.
- When the user asks "What decisions has the agent made?" or "Show me the agent's reasoning."
- For system monitoring and audit trails in development.

#### Arguments

| Argument | Type | Required | Description |
|----------|------|----------|-------------|
| `limit` | `number` | No | Maximum number of entries to return. Defaults to `10`. |

#### Return Value

```js
{
  entries: [
    {
      user_prompt: "Describe the page-context source",
      plan: [
        {
          command_id: "command_center.read.insights.describe",
          reason: "User wants to see the metadata of the page-context source.",
          args: { source_id: "page-context" }
        }
      ],
      thought: "The user requests information about 'page-context'. I will describe it using the insights.describe command.",
      provider_id: "wf-llm-provider-3be6659683c4065",
      timestamp: 1772075190507
    },
    // ... more entries
  ]
}
```

#### Implementation

```js
// commands/read/debugRouterLog.action.js
export const action = (args, registry) => {
  const limit = args?.limit || 10;
  const entries = registry?.getRouterLog?.(limit) || [];
  return { entries };
};
```

#### Command Definition

```js
{
  id: 'command_center.read.debug.router_log',
  label: '/router-log',
  description: "Show recent router LLM decisions and execution plans",
  schema: {
    type: 'object',
    properties: {
      limit: { type: 'number', description: 'Max entries to return (default: 10)' }
    }
  },
  action: (args) => Read.debugRouterLog(args, registry),
}
```

#### How the Log Is Populated

Each time a user message is processed, the `classifyIntent` function (in `useCommandCenterAgent`) calls `pushDebugEntry('router', entry)` after receiving a successful plan response:

```js
registry.pushDebugEntry('router', {
  user_prompt: userMessage,
  plan: response.execution_plan,
  thought: response.thought,
  provider_id: response.provider_id,
  timestamp: Date.now(),
});
```

The log is stored in a bounded in-memory array (typically last N entries).

#### Notes

- The log is **in-memory only** and is lost on page refresh.
- Each entry corresponds to one user message → router LLM call cycle.
- Useful for comparing how the same query was interpreted across different LLM providers.
- The `thought` field contains the LLM's chain-of-thought reasoning before generating the plan — this is the most useful debugging field.

### `/get-focus`

`command_center.read.focus.get`

Get active focus (entity/active panel)

#### Purpose

Returns the currently focused entity or active panel as reported by a host component. Focus represents "what the user is currently working on" — usually the entity displayed on a detail page.

#### When to Use

- When the LLM needs to know which specific entity is currently active.
- As a fallback when `page-context` is unavailable or doesn't expose entity IDs directly.
- When the user says "Do X on this project" — the LLM uses focus to resolve "this project" to a concrete entity ID.

#### Arguments

None.

#### Return Value

##### Entity focus (detail page)

```js
{
  focus: {
    entity_type: "project",
    entity_id: "prj-management-cc48809102397ed",
    label: "Development"
  }
}
```

##### Panel focus

```js
{
  focus: {
    type: "panel",
    panel_id: "create-project-form",
    label: "Create Project"
  }
}
```

##### No focus registered

```js
{ focus: null }
```

#### Implementation

```js
// commands/read/getFocus.action.js
export const action = (registry) => {
  if (!registry?.getFocusData) {
    return { focus: null };
  }

  const focus = registry.getFocusData();
  return { focus };
};
```

#### Command Definition

```js
{
  id: 'command_center.read.focus.get',
  label: '/get-focus',
  description: 'Get currently focused entity or active panel',
  schema: {},
  action: () => Read.getFocus(registry),
}
```

#### Reporting Focus in a Host Application

Use `useSommaticFocus` in any detail component to expose the active entity:

```jsx
import { useSommaticFocus } from 'sommatic-react-sdk';

// In a project detail component
useSommaticFocus(
  {
    entity_type: 'project',
    entity_id: project.id,
    label: project.name,
  },
  [project.id, project.name],
);
```

The hook calls `setFocusData(data)` on the registry. On unmount, it clears the focus by calling `setFocusData(null)`.

#### Focus vs. Context Source

| Feature | `useSommaticFocus` | `useSommaticContextSource` |
|---------|-------------------|--------------------------|
| Purpose | Reports current entity ID/type | Exposes full data payload |
| Access | `read.focus.get` | `read.insights.snapshot` |
| Payload | `{ entity_type, entity_id, label }` | Any shape |
| Updates | Triggers on entity change | Triggers on any data change |

Use both together for maximum discoverability: focus gives the LLM the ID, the context source gives it the full data.

#### Notes

- Only one focus entry exists globally in the registry. The last component to call `useSommaticFocus` owns it.
- On navigation away from a detail page, React's unmount lifecycle clears the focus.

### `/describe-insight`

`command_center.read.insights.describe`

View metadata + schema of an InsightSource

#### Purpose

Returns the metadata and inferred schema of a specific InsightSource — without fetching its full live payload. This gives the LLM (and the user) a structural picture of what data a source exposes, including field names, data presence indicators, and a description.

#### When to Use

- When the user asks "What fields does page-context have?" or "Describe the project source."
- As a lightweight alternative to `read.insights.snapshot` when only structure is needed, not live data.
- Before calling `extract.from_insight` to understand what fields are available.

#### Arguments

| Argument | Type | Required | Description |
|----------|------|----------|-------------|
| `source_id` | `string` | Yes | The ID of the source to describe. Use `'page-context'` for the active page. |

#### Return Value

```js
{
  ok: true,
  source: {
    id: "page-context",
    description: "Current Project Detail. Use this to know which project is active...",
    inferred_fields: ["context", "type", "project", "recentChats", "metadata"],
    has_data: true,
    captured_at: 1772075191118
  }
}
```

##### Error Cases

```js
// Missing argument
{ ok: false, error: { code: "MISSING_SOURCE_ID", message: "source_id is required" } }

// Source not registered
{ ok: false, error: { code: "SOURCE_NOT_FOUND", message: "Source [xyz] is not registered" } }
```

#### Implementation

```js
// commands/read/describeInsight.action.js
export const action = (args, registry) => {
  const { source_id } = args || {};

  if (!source_id) {
    return { ok: false, error: { code: 'MISSING_SOURCE_ID', message: 'source_id is required' } };
  }

  const metadata = registry?.getSourceMetadata?.(source_id);
  if (!metadata) {
    return { ok: false, error: { code: 'SOURCE_NOT_FOUND', message: `Source [${source_id}] is not registered` } };
  }

  const snapshot = registry?.getSnapshot?.(source_id);
  const payload = snapshot?.payload;
  const inferred_fields = payload && typeof payload === 'object' ? Object.keys(payload) : [];

  return {
    ok: true,
    source: {
      id: source_id,
      description: metadata.description,
      inferred_fields,
      has_data: !!payload,
      captured_at: snapshot?.capturedAt || null,
    },
  };
};
```

#### Command Definition

```js
{
  id: 'command_center.read.insights.describe',
  label: '/describe-insight',
  description: 'View metadata + schema of an InsightSource',
  schema: {
    type: 'object',
    properties: {
      source_id: {
        type: 'string',
        description: "ID of the InsightSource to describe. Use 'page-context' for the current page."
      }
    },
    required: ['source_id']
  },
  action: (args) => Read.describeInsight(args, registry),
}
```

#### Notes

- `inferred_fields` is derived by calling `Object.keys()` on the cached snapshot payload. It reflects the top-level keys of whatever `getData()` returned last.
- `has_data: false` means the source is registered but `getSnapshot()` has no cached value yet (e.g., component mounted but no render cycle completed).
- This command does **not** re-fetch data; it reads from the cached snapshot.

### `/list-insights`

`command_center.read.insights.list`

List available InsightSources by scope

#### Purpose

Lists all InsightSources currently registered in the Command Center, along with their IDs and descriptions. Supports optional keyword filtering.

#### When to Use

- When the user wants to know what data is available: "What sources do you have access to?"
- Before executing `read.insights.describe` or `read.insights.snapshot` to discover valid source IDs.
- As a discovery step in a multi-command plan.

#### Arguments

| Argument | Type | Required | Description |
|----------|------|----------|-------------|
| `scope_filter` | `string` | No | Keyword to filter sources by ID or description. Case-insensitive. |

#### Return Value

```js
{
  sources: [
    { id: "page-context", description: "Current page context. Use to know the active entity." },
    { id: "org-context", description: "Global organization metadata." },
    { id: "user-context", description: "Currently logged-in user profile." }
  ]
}
```

If `scope_filter` is provided:

```js
// scope_filter = "project"
{
  sources: [
    { id: "page-context", description: "Current Project Detail. Use this to know which project is active..." }
  ]
}
```

#### Implementation

```js
// commands/read/listInsights.action.js
export const action = (args, registry) => {
  if (!registry?.listAllSources) return { sources: [] };

  let sources = registry.listAllSources();

  const scopeFilter = args?.scope_filter;
  if (scopeFilter) {
    sources = sources.filter(
      (source) =>
        source.id.includes(scopeFilter) ||
        (source.description || '').toLowerCase().includes(scopeFilter.toLowerCase()),
    );
  }

  return { sources };
};
```

#### Command Definition

```js
{
  id: 'command_center.read.insights.list',
  label: '/list-sources',
  description: 'List all available data sources (InsightSources)',
  schema: {
    type: 'object',
    properties: {
      scope_filter: { type: 'string', description: 'Optional keyword filter' }
    }
  },
  action: (args) => Read.listInsights(args, registry),
}
```

#### Registering a Source in a Host Application

```jsx
import { useSommaticContextSource } from 'sommatic-react-sdk';

useSommaticContextSource(
  {
    id: 'org-context',
    description: 'Global organization metadata including name, plan, and settings.',
    getData: () => ({
      id: org.id,
      name: org.name,
      plan: org.plan,
    }),
  },
  [org],
);
```

#### Notes

- `listAllSources()` returns only sources currently registered (i.e., whose host component is currently mounted).
- Sources registered by unmounted components are automatically cleaned up via their unregister function.

### `/snapshot-insight`

`command_center.read.insights.snapshot`

Pull snapshot (respects TTL/cache)

#### Purpose

Returns the **live data payload** of a specific InsightSource. Unlike `read.insights.describe` (which only returns metadata), this command returns the actual data the component is currently exposing.

Snapshots are TTL-cached (default: 30 seconds) to avoid triggering unnecessary re-renders.

#### When to Use

- When the user asks for the actual current data from a source: "Show me the current project details."
- As a data-gathering step before synthesis or analysis.
- When the LLM needs to pass specific values (like IDs or names) to a subsequent exec command.

#### Arguments

| Argument | Type | Required | Description |
|----------|------|----------|-------------|
| `source_id` | `string` | Yes | The ID of the InsightSource to snapshot. |

#### Return Value

```js
{
  ok: true,
  source_id: "page-context",
  payload: {
    context: "This page displays the detailed view of a specific project.",
    type: "project-detail",
    project: {
      id: "prj-management-cc48809102397ed",
      name: "Development",
      status: "active",
      organization: "org-232121",
      ui: { emoji: { icon: "Code", color: "#4CAF50" }, theme: {} }
    },
    recentChats: [
      { id: "c-198763...", title: "Test chat", created: { timestamp: "1769607887018" } }
    ],
    metadata: { isLoading: false, error: false }
  },
  captured_at: 1772075191118
}
```

##### Error Cases

```js
{ ok: false, error: { code: "MISSING_SOURCE_ID", message: "source_id is required" } }
{ ok: false, error: { code: "SOURCE_NOT_FOUND", message: "Source [xyz] is not registered" } }
{ ok: false, error: { code: "NO_DATA", message: "Source [page-context] has no data yet" } }
```

#### Implementation

```js
// commands/read/snapshotInsight.action.js
export const action = (args, registry) => {
  const { source_id } = args || {};

  if (!source_id) {
    return { ok: false, error: { code: 'MISSING_SOURCE_ID', message: 'source_id is required' } };
  }

  const metadata = registry?.getSourceMetadata?.(source_id);
  if (!metadata) {
    return { ok: false, error: { code: 'SOURCE_NOT_FOUND', message: `Source [${source_id}] is not registered` } };
  }

  const snapshot = registry?.getSnapshot?.(source_id);
  if (!snapshot?.payload) {
    return { ok: false, error: { code: 'NO_DATA', message: `Source [${source_id}] has no data yet` } };
  }

  return {
    ok: true,
    source_id,
    payload: snapshot.payload,
    captured_at: snapshot.capturedAt,
  };
};
```

#### Command Definition

```js
{
  id: 'command_center.read.insights.snapshot',
  label: '/snapshot-insight',
  description: 'Retrieve live data payload from an InsightSource',
  schema: {
    type: 'object',
    properties: {
      source_id: {
        type: 'string',
        description: "ID of the source. Use 'page-context' for current page data."
      }
    },
    required: ['source_id']
  },
  action: (args) => Read.snapshotInsight(args, registry),
}
```

#### Snapshot Caching

The `getSnapshot(source_id)` call reads from a TTL cache. The cache is populated every time the host component re-renders and the `useSommaticContextSource` hook fires. This means:

- Data is always at most 30 seconds stale (configurable TTL).
- Calling this command multiple times quickly returns the same snapshot.
- No extra network calls are made — this is purely in-memory.

#### Notes

- Use `read.insights.describe` first when you only need field names, not values. It's cheaper in terms of synthesis context consumption.
- For bundling multiple snapshots into a single payload, use `read.context.pack`.

### `/page-outline`

`command_center.read.page.outline`

What's on the page using insights (non-DOM). Use when the user asks 'what can I do here?', 'qué puedo hacer aquí', 'qué hay en esta página'. Falls back to the first registered InsightSource if 'page-context' is not published.

#### Purpose

Returns a comprehensive description of the current page: the route, page context payload, and all registered InsightSources with their descriptions and payload keys. Acts as the most complete single snapshot of "where the user is and what's available."

#### When to Use

- When the user asks "What is on this page?" or "Explain what I'm looking at."
- As the first step in any multi-command plan where the LLM needs full situational awareness.
- For debugging: to see what sources are registered and whether they have data.

#### Arguments

| Argument | Type | Required | Description |
|----------|------|----------|-------------|
| `detail_level` | `string` | No | `"high"` for full payload in sources, `"low"` for keys only. Defaults to `"low"`. |

#### Return Value

```js
{
  route: "/admin/project/management/prj-management-cc48809102397ed",
  page_context: {
    context: "This page displays the detailed view of a specific project...",
    type: "project-detail",
    project: {
      id: "prj-management-cc48809102397ed",
      name: "Development",
      status: "active",
      organization: "org-232121",
      ui: { emoji: { icon: "Code", color: "#4CAF50" } }
    },
    recentChats: [ /* ... */ ],
    metadata: { isLoading: false, error: false }
  },
  sources: [
    {
      id: "page-context",
      description: "Current Project Detail...",
      has_data: true,
      payload_keys: ["context", "type", "project", "recentChats", "metadata"]
    },
    {
      id: "org-context",
      description: "Organization metadata.",
      has_data: true,
      payload_keys: ["id", "name", "plan"]
    }
  ]
}
```

#### Implementation

```js
// commands/read/getPageOutline.action.js
export const action = (args, registry) => {
  const detailLevel = args?.detail_level || 'low';
  const route = window?.location?.pathname || 'unknown';

  const pageSnapshot = registry?.getSnapshot?.('page-context');
  const pageContext = pageSnapshot?.payload || null;

  const allSources = registry?.listAllSources?.() || [];
  const sources = allSources.map((source) => {
    const snap = registry?.getSnapshot?.(source.id);
    const payload = snap?.payload;
    const entry = {
      id: source.id,
      description: source.description,
      has_data: !!payload,
    };

    if (detailLevel === 'high' && payload) {
      entry.payload = payload;
    } else if (payload) {
      entry.payload_keys = Object.keys(payload);
    }

    return entry;
  });

  return { route, page_context: pageContext, sources };
};
```

#### Command Definition

```js
{
  id: 'command_center.read.page.outline',
  label: '/page-outline',
  description: 'Describe current page route, context, and registered sources',
  schema: {
    type: 'object',
    properties: {
      detail_level: {
        type: 'string',
        enum: ['low', 'high'],
        description: "'high' includes full source payloads; 'low' includes only field names."
      }
    }
  },
  action: (args) => Read.getPageOutline(args, registry),
}
```

#### Notes

- `detail_level: "high"` can produce very large responses (all source payloads combined). If used with synthesis, the context truncation logic in `CognitiveEntryManager` will apply.
- `route` is derived from `window.location.pathname`, so it always reflects the browser's current URL at execution time.
- `sources` includes all registered sources, not just `page-context`. This gives the LLM a complete picture of available data.

### `/get-current-scope`

`command_center.read.scope.get`

Get the current scope (route, module, focus). Use this whenever the user asks 'where am I?', 'what page is this?', 'dime el nombre de la página', 'qué página es esta', or similar. Falls back to the first registered InsightSource if 'page-context' is not published.

#### Purpose

Returns the current page context snapshot. It retrieves whatever data the active page component has registered under the `page-context` InsightSource.

This is the simplest read command — it directly returns the context object without any filtering or transformation.

#### When to Use

- When the user asks "what page am I on?" or "what is the current context?"
- As a first step in a multi-command plan to establish the current scope before more specific lookups.
- When the LLM needs to know the active entity (e.g., which project is open) before executing an action.

#### Arguments

This command takes no user-facing arguments.

Internally it receives the page context object directly from `getContext('page-context')`, not from the `registry`. This is the only command that receives raw context instead of the registry.

#### Return Value

Returns whatever `getData()` returns from the `page-context` InsightSource.

```js
// Example return value on a project detail page
{
  context: "This page displays the detailed view of a specific project...",
  type: "project-detail",
  project: {
    id: "prj-management-cc48809102397ed",
    name: "Development",
    status: "active",
    organization: "org-232121"
  },
  recentChats: [
    { id: "c-198763...", title: "Test chat", created: { timestamp: "1769607887018" } }
  ],
  metadata: { isLoading: false, error: false }
}
```

On a list page:

```js
{
  type: "project-list",
  items: [
    { id: "prj-management-...", name: "MyProject", status: "active", slug: "my-project" }
  ],
  pagination: { page: 0, limit: 10, total: 42 },
  metadata: { isLoading: false }
}
```

#### Implementation

```js
// commands/read/getCurrentScope.action.js
export const action = (context) => {
  return context;
};
```

The `context` argument is injected by the command dispatcher from `getContext('page-context')` before the action is called.

#### Command Definition

```js
// commands/definitions.js
{
  id: 'command_center.read.scope.get',
  label: '/get-scope',
  description: 'Get current page context',
  schema: {},
  action: () => Read.getCurrentScope(getContext('page-context')),
}
```

#### Implementing the Context Source in a Host Application

Any page that wants to be discoverable by `read.scope.get` must register a `page-context` source:

```jsx
import { useSommaticContextSource } from 'sommatic-react-sdk';

useSommaticContextSource(
  {
    id: 'page-context',
    description: 'Current page description visible to the Command Center.',
    getData: () => ({
      type: 'my-entity-detail',
      entity: { id: entity.id, name: entity.name },
      metadata: { isLoading },
    }),
  },
  [entity, isLoading],
);
```

#### Notes

- Only one component should register `page-context` at a time. React Router's mount/unmount lifecycle naturally ensures this, since only the active route's components are mounted.
- If no component has registered `page-context`, the return value will be `null` or `undefined`.

### `/get-selection`

`command_center.read.selection.get`

Get opt-in selection (text/IDs)

#### Purpose

Returns the current user selection as reported by host components. Selection can represent selected rows in a grid, highlighted text, or any structured selection data a component chooses to expose.

#### When to Use

- When the user asks "What do I have selected?" or "Tell me about the selected items."
- Before executing a batch exec command on selected items.
- When the LLM needs to know which rows/entities to operate on without asking the user explicitly.

#### Arguments

None.

#### Return Value

##### Rows selected in a grid

```js
{
  selection: {
    type: "rows",
    ids: ["prj-management-a4b0e53a9532edd", "prj-management-f00d4ca337d8dcb"],
    source: "project-list-grid"
  }
}
```

##### Text selection

```js
{
  selection: {
    type: "text",
    value: "Hello world",
    source: "browser"
  }
}
```

##### No selection

```js
{ selection: null }
```

#### Implementation

```js
// commands/read/getSelection.action.js
export const action = (registry) => {
  if (!registry?.getSelectionData) {
    return { selection: null };
  }

  const selection = registry.getSelectionData();
  return { selection };
};
```

#### Command Definition

```js
{
  id: 'command_center.read.selection.get',
  label: '/get-selection',
  description: 'Get current user selection (rows, text, or entities)',
  schema: {},
  action: () => Read.getSelection(registry),
}
```

#### Reporting Selection in a Host Application

Components that manage selections must call `useSommaticSelection` to make them visible:

```jsx
import { useSommaticSelection } from 'sommatic-react-sdk';

// In a list component
useSommaticSelection(
  selectedRowIds.length > 0
    ? { type: 'rows', ids: selectedRowIds, source: 'project-list-grid' }
    : null,
  [selectedRowIds],
);
```

The hook calls `setSelection(data)` on the registry whenever the selection changes. Passing `null` clears the selection.

#### Integration With `exec.ui.select_rows`

When the user asks the Command Center to "select rows with slug X", `exec.ui.select_rows` updates the `selectedRowIds` state in the component. If `useSommaticSelection` is wired up, a subsequent `read.selection.get` call will return those row IDs.

This creates a full read/write cycle:
1. `exec.ui.select_rows` → sets rows visually + state
2. `useSommaticSelection` → reports new state to registry
3. `read.selection.get` → LLM can read which rows are selected

#### Notes

- Selection is stored as a single global entry in the registry. If multiple components call `setSelection`, the last one wins.
- For multi-component selection tracking, consider using distinct selection keys and returning a combined object from `getData`.

### `/task-detail`

`command_center.read.tasks.detail`

View detail + required inputs schema

#### Purpose

Returns the full details of a specific HITL task, including its status, type, outputs schema, assignments, and any history. Used before claiming or completing a task to understand what it requires.

#### When to Use

- When the user asks "Tell me about task XYZ" or "What does this task require?"
- Before calling `exec.tasks.complete` to understand the required `outputs` structure.
- After listing tasks with `read.tasks.inbox` to drill into a specific item.

#### Arguments

| Argument | Type | Required | Description |
|----------|------|----------|-------------|
| `task_id` | `string` | Yes | The ID of the task to retrieve. |

#### Return Value

```js
{
  ok: true,
  task: {
    id: "task-abc123",
    title: "Review agent configuration",
    description: "Please review and approve the attached agent configuration before deployment.",
    status: "pending",
    type: "approval",
    outputs_schema: {
      approved: { type: "boolean", required: true },
      comment: { type: "string", required: false }
    },
    assigned_to: "user-xyz",
    created_by: "system",
    created_at: "2026-02-25T20:00:00.000Z",
    updated_at: "2026-02-25T20:05:00.000Z",
    context: {
      agent_id: "agent-001",
      config_version: "v2.1"
    }
  }
}
```

##### Error Cases

```js
{ ok: false, error: { code: "MISSING_TASK_ID", message: "task_id is required" } }
{ ok: false, error: { code: "NO_TASK_SERVICE", message: "Task service is not configured" } }
{ ok: false, error: { code: "FETCH_FAILED", message: "..." } }
```

#### Implementation

```js
// commands/read/getTaskDetail.action.js
export const action = async (args, registry) => {
  const { task_id } = args || {};

  if (!task_id) {
    return { ok: false, error: { code: 'MISSING_TASK_ID', message: 'task_id is required' } };
  }

  const taskStore = registry?.taskService;
  if (!taskStore) {
    return { ok: false, error: { code: 'NO_TASK_SERVICE', message: 'Task service is not configured' } };
  }

  try {
    const response = await taskStore.get({ queryselector: 'detail', id: task_id });
    const task = response?.result || response;

    return { ok: true, task };
  } catch (err) {
    return { ok: false, error: { code: 'FETCH_FAILED', message: err.message } };
  }
};
```

#### Command Definition

```js
{
  id: 'command_center.read.tasks.detail',
  label: '/task-detail',
  description: 'Get full details of a specific HITL task',
  schema: {
    type: 'object',
    properties: {
      task_id: {
        type: 'string',
        description: 'ID of the task to retrieve.'
      }
    },
    required: ['task_id']
  },
  action: (args) => Read.getTaskDetail(args, registry),
}
```

#### Typical Multi-Command Flow

```
1. read.tasks.inbox { status: "pending" }
   → returns task list with IDs

2. read.tasks.detail { task_id: "task-abc123" }
   → returns full task with outputs_schema

3. exec.tasks.claim { task_id: "task-abc123" }
   → assigns task to current user

4. exec.tasks.complete { task_id: "task-abc123", outputs: { approved: true } }
   → marks task as complete
```

#### Notes

- The `outputs_schema` field (if present) describes what the `outputs` object must contain when calling `exec.tasks.complete`.
- The `context` field contains any additional data the workflow passed to the task — use it to understand the task's business context.

### `/tasks-inbox`

`command_center.read.tasks.inbox`

List HITL Tasks assigned to user

#### Purpose

Lists Human-in-the-Loop (HITL) tasks assigned to the current user. Queries the configured `taskService` for tasks filtered by status.

HITL tasks represent work items that require human validation, approval, or input before an automated workflow can continue.

#### When to Use

- When the user asks "What tasks do I have pending?" or "Show me my inbox."
- Before executing `exec.tasks.claim`, `exec.tasks.complete`, or `exec.tasks.comment` — to retrieve task IDs.
- For workflow automation: check pending tasks, claim one, then complete it.

#### Arguments

| Argument | Type | Required | Description |
|----------|------|----------|-------------|
| `status` | `string` | No | Filter by status: `'pending'`, `'in_progress'`, `'completed'`. If omitted, returns all statuses. |

#### Return Value

```js
{
  ok: true,
  tasks: [
    {
      id: "task-abc123",
      title: "Review agent configuration",
      status: "pending",
      type: "approval",
      created_at: "2026-02-25T20:00:00.000Z",
      assigned_to: "user-xyz"
    },
    {
      id: "task-def456",
      title: "Validate data source connection",
      status: "in_progress",
      type: "validation",
      created_at: "2026-02-25T18:30:00.000Z"
    }
  ]
}
```

If no tasks match:

```js
{ ok: true, tasks: [] }
```

##### Error Cases

```js
{ ok: false, error: { code: "NO_TASK_SERVICE", message: "Task service is not configured" } }
{ ok: false, error: { code: "FETCH_FAILED", message: "Network error: ..." } }
```

#### Implementation

```js
// commands/read/listTasksInbox.action.js
export const action = async (args, registry) => {
  const { status } = args || {};
  const taskStore = registry?.taskService;

  if (!taskStore) {
    return { ok: false, error: { code: 'NO_TASK_SERVICE', message: 'Task service is not configured' } };
  }

  try {
    const payload = { queryselector: 'list' };
    if (status) payload.status = status;

    const response = await taskStore.get(payload);
    const tasks = response?.result?.items || response?.items || [];

    return { ok: true, tasks };
  } catch (err) {
    return { ok: false, error: { code: 'FETCH_FAILED', message: err.message } };
  }
};
```

#### Command Definition

```js
{
  id: 'command_center.read.tasks.inbox',
  label: '/tasks-inbox',
  description: 'List HITL tasks assigned to the current user',
  schema: {
    type: 'object',
    properties: {
      status: {
        type: 'string',
        enum: ['pending', 'in_progress', 'completed'],
        description: 'Filter by task status. Omit for all tasks.'
      }
    }
  },
  action: (args) => Read.listTasksInbox(args, registry),
}
```

#### Task Service Configuration

Pass a `taskService` object to `CommandCenterProvider`:

```jsx
const taskService = {
  get: async ({ queryselector, status }) => {
    // Your API call
    const data = await myApi.tasks.list({ status });
    return { result: { items: data } };
  },
  update: async ({ id, action, outputs, comment }) => {
    const data = await myApi.tasks.update(id, { action, outputs, comment });
    return { result: data };
  },
};

<CommandCenterProvider taskService={taskService} ...>
```

#### Notes

- Without `taskService`, all task-related commands return `NO_TASK_SERVICE` errors.
- The response shape is normalized: the action looks for `response?.result?.items` first, then `response?.items`. Adapt your `taskService.get` method accordingly.
- Use `read.tasks.detail` to fetch the full details of a specific task before claiming or completing it.

### `/list-surfaces`

`command_center.read.ui.surfaces.list`

List published surfaces (modals, grids, forms)

#### Purpose

Lists all UI surfaces currently registered in the Command Center, including their IDs, types, labels, and descriptions. Surfaces are interactive UI elements (grids, forms, modals, panels, apps) that the Command Center can interact with programmatically.

#### When to Use

- When the user asks "What UI elements can I interact with?"
- Before calling `exec.ui.apply_filter`, `exec.ui.select_rows`, `exec.ui.submit_form`, etc., to discover valid surface IDs.
- As a discovery step in a multi-command plan.

#### Arguments

None.

#### Return Value

```js
{
  surfaces: [
    {
      id: "project-list-grid",
      type: "grid",
      label: "Project List",
      description: "Grid listing all projects with filter and row selection."
    },
    {
      id: "create-project-form",
      type: "form",
      label: "Create Project Form",
      description: "Form to create a new project."
    },
    {
      id: "agent-profile-list-grid",
      type: "grid",
      label: "Agent Profile List",
      description: "Grid of AI agent profiles."
    }
  ]
}
```

If no surfaces are registered:

```js
{ surfaces: [] }
```

#### Implementation

```js
// commands/read/listSurfaces.action.js
export const action = (registry) => {
  if (!registry?.getSurfaces) {
    return { surfaces: [] };
  }

  return { surfaces: registry.getSurfaces() };
};
```

#### Command Definition

```js
{
  id: 'command_center.read.ui.surfaces.list',
  label: '/list-surfaces',
  description: 'List all registered UI surfaces (grids, forms, modals, panels)',
  schema: {},
  action: () => Read.listSurfaces(registry),
}
```

#### Surface Registration in Host Applications

Surfaces are registered using `useSommaticSurface`:

```jsx
import { useSommaticSurface } from 'sommatic-react-sdk';

useSommaticSurface(
  {
    id: 'llm-provider-list-grid',
    type: 'grid',
    label: 'LLM Provider List',
    description: 'Grid listing all configured LLM providers.',
    handlers: {
      applyFilter: (value) => setFilter(value),
      selectRows: (ids) => setSelectedRowIds(ids),
    },
    targets: [],
  },
  [],
);
```

The returned list from `getSurfaces()` includes `id`, `type`, `label`, `description`, and optionally `targets`.

#### Related Commands

- `read.ui.targets.list` — Lists the individual UI targets within a specific surface.
- `observe.ui` — Suggests which surfaces/targets are relevant for a given natural language instruction.
- `exec.ui.open_surface`, `exec.ui.close_surface` — Open/close modal or panel surfaces.
- `exec.ui.apply_filter`, `exec.ui.select_rows` — Interact with grid surfaces.

#### Notes

- Surfaces are cleaned up automatically when their host component unmounts (via the returned unregister function from `registerSurface`).
- The `getSurfaces()` method returns only currently mounted surfaces.

### `/list-targets`

`command_center.read.ui.targets.list`

List targets of a surface

#### Purpose

Lists all actionable targets within a specific surface. A target represents an individual UI element (button, input field, dropdown, etc.) that the Command Center can interact with via the `exec.ui.act` or `extract.from_targets` commands.

#### When to Use

- Before calling `exec.ui.act` to discover valid `target_ref` values.
- When the user asks "What actions are available in this form?"
- To understand what fields are available in a form surface before `exec.ui.set_fields`.

#### Arguments

| Argument | Type | Required | Description |
|----------|------|----------|-------------|
| `surface_id` | `string` | Yes | The ID of the surface to inspect. |

#### Return Value

Each target includes **`target_ref`** in the format `surface_id::target_id`. Use this exact string in `exec.ui.act` and `extract.from_targets` (do not concatenate manually).

```js
{
  ok: true,
  surface_id: "create-project-form",
  targets: [
    {
      ref: "project-name-input",
      id: "project-name-input",
      label: "Project Name",
      type: "input",
      methods: ["getValue", "fill"],
      target_ref: "create-project-form::project-name-input"
    },
    {
      ref: "submit-btn",
      id: "submit-btn",
      label: "Submit",
      type: "button",
      methods: ["click"],
      target_ref: "create-project-form::submit-btn"
    },
    {
      ref: "status-dropdown",
      id: "status-dropdown",
      label: "Status",
      type: "select",
      methods: ["getValue", "fill"],
      target_ref: "create-project-form::status-dropdown"
    }
  ]
}
```

##### Error Cases

```js
{ ok: false, error: { code: "MISSING_SURFACE_ID", message: "surface_id is required" } }
{ ok: false, error: { code: "SURFACE_NOT_FOUND", message: "Surface [xyz] not found" } }
```

#### Implementation

```js
// commands/read/listTargets.action.js
export const action = (args, registry) => {
  const { surface_id } = args || {};

  if (!surface_id) {
    return { ok: false, error: { code: 'MISSING_SURFACE_ID', message: 'surface_id is required' } };
  }

  if (!registry?.getTargets) {
    return { surface_id, targets: [] };
  }

  const rawTargets = registry.getTargets(surface_id);
  const targets = rawTargets.map((t) => {
    const ref = t.ref || t.id || '';
    return {
      ref,
      id: ref,
      label: t.label || '',
      type: t.type || 'unknown',
      methods: t.methods || [],
      target_ref: `${surface_id}::${ref}`,
    };
  });

  return { surface_id, targets };
};
```

#### Command Definition

```js
{
  id: 'command_center.read.ui.targets.list',
  label: '/list-targets',
  description: 'List all actionable targets within a surface',
  schema: {
    type: 'object',
    properties: {
      surface_id: {
        type: 'string',
        description: 'ID of the surface to inspect.'
      }
    },
    required: ['surface_id']
  },
  action: (args) => Read.listTargets(args, registry),
}
```

#### Target Definition in Host Applications

Targets are specified in the `targets` array of a surface:

```jsx
useSommaticSurface({
  id: 'create-agent-form',
  type: 'form',
  label: 'Create Agent Form',
  targets: [
    {
      id: 'agent-name-input',
      label: 'Agent Name',
      type: 'input',
      handlers: {
        getValue: () => nameValue,
        fill: (value) => setNameValue(value),
      },
    },
    {
      id: 'submit-btn',
      label: 'Submit',
      type: 'button',
      handlers: {
        click: () => handleSubmit(),
      },
    },
  ],
  handlers: {
    setFields: (fields) => { if (fields.name) setNameValue(fields.name); },
    submit: () => handleSubmit(),
  },
}, []);
```

#### Target Reference Format

The response of `read.ui.targets.list` includes a **`target_ref`** for each target in the format `{surface_id}::{target_id}`. Use this exact string when calling `exec.ui.act` or `extract.from_targets`:

```
{surface_id}::{target_id}
```

Example (from list-targets response):
```
create-agent-form::agent-name-input
create-agent-form::submit-btn
```

`registry.resolveTarget(targetRef)` parses this format and returns `{ surface, target }`.

#### Virtual Targets

If a surface has no explicit `targets` but registers `handlers`, the `observe.ui` command generates **virtual targets** for those handlers. These won't appear in `list-targets` results because `getTargets()` only returns explicitly defined targets. Use `observe.ui` for discovering virtual targets.

#### Notes

- Empty `targets: []` is common for grids and panels that expose functionality only through handlers. Use `observe.ui` to discover their capabilities.
- The `methods` array in the response is derived from `Object.keys(target.handlers)`.

## Execution commands

### `/open-app`

`command_center.exec.app.open`

Open a Sommatic AI App in the Command Center. Semantically match the user's intent (any language, any phrasing or spelling) against `context.client.navigation.available_apps` — each entry has `slug`, `name`, `description`, `tags`, and `default_route`. Emit the matched `slug` as `app_slug`. If the matched entry has a `default_route`, use it as `route_path` unless the user explicitly asks for another route. As a last-resort fallback you may also pass `app_name` (the human-readable name) and the runtime will resolve it from the catalog.

#### Purpose

Opens a HITL (Human-in-the-Loop) App surface and waits for its outputs. Unlike `exec.ui.open_surface` (which is fire-and-forget), this command awaits the app's completion and returns the outputs produced by the user's interaction within the app.

HITL App surfaces are complex UIs (wizards, multi-step forms, embedded tools) that the agent launches to collect structured input from the user.

#### When to Use

- When a workflow requires structured human input before continuing.
- When launching a wizard or a multi-step data collection form that the agent cannot fill automatically.
- When `exec.ui.set_fields` + `exec.ui.submit_form` is not sufficient and the user needs to interact with a complex UI.

#### Arguments

| Argument | Type | Required | Description |
|----------|------|----------|-------------|
| `app_id` | `string` | Yes | The surface ID of the app to open. The surface must have type `'app'` and an `open` handler. |
| `initial_state` | `object` | No | Optional state to pre-populate the app with before showing it to the user. |

#### Return Value

```js
{
  ok: true,
  title: "Opened app [create-project-wizard]",
  outputs: {
    name: "My New Project",
    status: "active",
    organization: "org-232121",
    confirmed: true
  },
  receipt_id: "rcpt_1772075473717_abc"
}
```

If the user cancels the app:

```js
{
  ok: true,
  title: "Opened app [create-project-wizard]",
  outputs: { cancelled: true },
  receipt_id: "..."
}
```

##### Error Cases

```js
{ ok: false, error: { code: "MISSING_APP_ID", message: "app_id is required" } }
{ ok: false, error: { code: "APP_NOT_FOUND", message: "App [xyz] not found in surface registry" } }
{ ok: false, error: { code: "NO_OPEN_HANDLER", message: "App [xyz] has no open handler" } }
{ ok: false, error: { code: "APP_OPEN_FAILED", message: "App threw: ..." } }
```

#### Implementation

```js
// commands/exec/openApp.action.js
export const action = async (args, registry) => {
  const { app_id, initial_state } = args || {};

  if (!app_id) return { ok: false, error: { code: 'MISSING_APP_ID', message: 'app_id is required' } };

  const surface = registry?.getSurface?.(app_id);
  if (!surface) return { ok: false, error: { code: 'APP_NOT_FOUND', message: `App [${app_id}] not found` } };

  if (!surface.handlers?.open) {
    return { ok: false, error: { code: 'NO_OPEN_HANDLER', message: `App [${app_id}] has no open handler` } };
  }

  let outputs;
  try {
    outputs = await surface.handlers.open(initial_state);
  } catch (err) {
    return { ok: false, error: { code: 'APP_OPEN_FAILED', message: err.message } };
  }

  const receipt = registry.pushReceipt?.({
    command_id: 'command_center.exec.app.open',
    args,
    reversible: false,
    outputs,
  });

  return { ok: true, title: `Opened app [${app_id}]`, outputs, receipt_id: receipt?.id };
};
```

#### Command Definition

```js
{
  id: 'command_center.exec.app.open',
  label: '/open-app',
  description: 'Open a HITL app surface and wait for user outputs',
  schema: {
    type: 'object',
    properties: {
      app_id: { type: 'string', description: 'Surface ID of the app to open.' },
      initial_state: { type: 'object', description: 'Optional initial state to pre-populate the app.' }
    },
    required: ['app_id']
  },
  action: (args) => Exec.openApp(args, registry),
}
```

#### Implementing an App Surface

The `open` handler must return a Promise that resolves when the user completes or cancels the app:

```jsx
const [isOpen, setIsOpen] = useState(false);
const [resolveOutputs, setResolveOutputs] = useState(null);

useSommaticSurface({
  id: 'create-project-wizard',
  type: 'app',
  label: 'Create Project Wizard',
  handlers: {
    open: (initialState) => new Promise((resolve) => {
      if (initialState?.name) setPrefillName(initialState.name);
      setIsOpen(true);
      setResolveOutputs(() => resolve);  // Store resolver for later
    }),
  },
}, []);

// When user completes the wizard:
const handleComplete = (outputs) => {
  setIsOpen(false);
  resolveOutputs?.(outputs);  // Resolves the promise → command returns
};

// When user cancels:
const handleCancel = () => {
  setIsOpen(false);
  resolveOutputs?.({ cancelled: true });
};
```

#### Notes

- The `open` handler must be an async function (or return a Promise). The command `await`s it, so the Command Center will appear to "think" until the user completes the app.
- This pattern enables true Human-in-the-Loop: the agent pauses and waits for structured human input before continuing the plan.
- `outputs` shape is entirely defined by the app — the Command Center does not enforce a schema.

### `/copy`

`command_center.exec.clipboard.copy`

Copy an artifact to clipboard

#### Purpose

Copies a string of text to the user's clipboard using the browser's Clipboard API. Useful for extracting values from context and making them ready to paste.

#### When to Use

- When the user asks "Copy the project ID to clipboard."
- When a synthesis response includes a value the user wants to use elsewhere.
- As the final step in a plan: retrieve data → copy a specific field.

#### Arguments

| Argument | Type | Required | Description |
|----------|------|----------|-------------|
| `content` | `string` | Yes | The text to copy to the clipboard. |

#### Return Value

```js
{
  ok: true,
  title: "Copied to clipboard",
  receipt_id: "rcpt_1772075473717_byfawpr"
}
```

##### Error Cases

```js
{ ok: false, error: { code: "MISSING_CONTENT", message: "content is required" } }
{ ok: false, error: { code: "CLIPBOARD_UNAVAILABLE", message: "Clipboard API is not available" } }
{ ok: false, error: { code: "COPY_FAILED", message: "Permission denied" } }
```

#### Implementation

```js
// commands/exec/copyToClipboard.action.js
export const action = async (args, registry) => {
  const { content } = args || {};

  if (!content) return { ok: false, error: { code: 'MISSING_CONTENT', message: 'content is required' } };

  if (!navigator?.clipboard?.writeText) {
    return { ok: false, error: { code: 'CLIPBOARD_UNAVAILABLE', message: 'Clipboard API is not available' } };
  }

  try {
    await navigator.clipboard.writeText(content);
  } catch (err) {
    return { ok: false, error: { code: 'COPY_FAILED', message: err.message } };
  }

  const receipt = registry.pushReceipt?.({
    command_id: 'command_center.exec.clipboard.copy',
    args,
    reversible: false,
    content,
  });

  return { ok: true, title: 'Copied to clipboard', receipt_id: receipt?.id };
};
```

#### Command Definition

```js
{
  id: 'command_center.exec.clipboard.copy',
  label: '/copy',
  description: 'Copy text to the clipboard',
  schema: {
    type: 'object',
    properties: {
      content: { type: 'string', description: 'Text to copy to the clipboard.' }
    },
    required: ['content']
  },
  action: (args) => Exec.copyToClipboard(args, registry),
}
```

#### Notes

- The Clipboard API requires a secure context (HTTPS or localhost). In non-secure contexts, `navigator.clipboard` is `undefined` and the command returns `CLIPBOARD_UNAVAILABLE`.
- The `content` can be any string: an ID, a URL, a JSON snippet, or a full text block extracted from a source snapshot.
- This command is not reversible — there's no meaningful way to "undo" a clipboard copy.

### `/invoke-command`

`command_center.exec.command.invoke`

Execute semantic command published by feature

#### Purpose

Executes another registered Command Center command by ID. This is a meta-command — it allows the LLM to chain or re-execute commands programmatically, or for feature modules to publish semantic commands that other parts of the system can call.

#### When to Use

- When a feature module publishes a high-level command (e.g., `project.refresh`, `org.reload`) that another command or automation flow needs to call.
- For dynamic composition: the LLM knows a command ID from context and needs to invoke it without knowing its implementation.
- For testing: invoking a command by name from another command.

#### Arguments

| Argument | Type | Required | Description |
|----------|------|----------|-------------|
| `command_id` | `string` | Yes | The full ID of the command to invoke. |
| `args` | `object` | No | Arguments to pass to the invoked command's action. |

#### Return Value

```js
{
  ok: true,
  title: "Invoked command [command_center.read.page.outline]",
  result: { /* whatever the invoked command returned */ },
  receipt_id: "rcpt_1772075473717_abc"
}
```

##### Error Cases

```js
{ ok: false, error: { code: "MISSING_COMMAND_ID", message: "command_id is required" } }
{ ok: false, error: { code: "COMMAND_NOT_FOUND", message: "Command [xyz] not found" } }
{ ok: false, error: { code: "NO_ACTION", message: "Command [xyz] has no action defined" } }
{ ok: false, error: { code: "INVOKE_FAILED", message: "Command threw: ..." } }
```

#### Implementation

```js
// commands/exec/invokeCommand.action.js
export const action = async (args, registry) => {
  const { command_id, args: commandArgs } = args || {};

  if (!command_id) return { ok: false, error: { code: 'MISSING_COMMAND_ID', message: 'command_id is required' } };

  const commands = registry?.commands || [];
  const cmdDef = commands.find((cmd) => cmd.id === command_id);

  if (!cmdDef) return { ok: false, error: { code: 'COMMAND_NOT_FOUND', message: `Command [${command_id}] not found` } };
  if (!cmdDef.action) return { ok: false, error: { code: 'NO_ACTION', message: `Command [${command_id}] has no action` } };

  let result;
  try {
    result = await cmdDef.action(commandArgs);
  } catch (err) {
    return { ok: false, error: { code: 'INVOKE_FAILED', message: err.message } };
  }

  const receipt = registry.pushReceipt?.({
    command_id: 'command_center.exec.command.invoke',
    args,
    reversible: false,
    invoked_command: command_id,
    result,
  });

  return { ok: true, title: `Invoked command [${command_id}]`, result, receipt_id: receipt?.id };
};
```

#### Command Definition

```js
{
  id: 'command_center.exec.command.invoke',
  label: '/invoke-command',
  description: 'Execute a registered command by ID',
  schema: {
    type: 'object',
    properties: {
      command_id: {
        type: 'string',
        description: 'Full ID of the command to invoke (e.g. "command_center.read.capabilities").'
      },
      args: {
        type: 'object',
        description: 'Arguments to pass to the invoked command.'
      }
    },
    required: ['command_id']
  },
  action: (args) => Exec.invokeCommand(args, registry),
}
```

#### Notes

- This command uses `registry.commands` (which reads from `allCommandsRef.current`) to find the target command. Both static and dynamically registered commands are accessible.
- Avoid circular invocations (a command invoking itself via this mechanism).
- The invoked command's action is called directly with `commandArgs` — it does not go through the LLM routing pipeline again.

### `/navigate`

`command_center.exec.navigate`

Navigate to a page. Semantically match the user's intent (any language, any phrasing or spelling) against the pages in `context.client.navigation.available_pages`. Each entry has `path` and `description`. Pick the `path` of the best matching page and emit it exactly.

#### Purpose

Navigates the application to a specified route using React Router's `navigate` function. The command waits 1.5 seconds after navigation to allow the new page to mount before the next plan step executes.

#### When to Use

- When the user says "Go to the projects page" or "Open agent profiles."
- As the first step in a plan that needs to navigate before reading page context.
- For deep-linking: "Navigate to project XYZ's detail page."

#### Arguments

| Argument | Type | Required | Description |
|----------|------|----------|-------------|
| `route` | `string` | Yes | The absolute path to navigate to (e.g., `/admin/projects`). |

#### Return Value

```js
{
  success: true,
  message: "Navigating to /admin/project/management"
}
```

If route not provided:

```js
{ success: false, message: "Route not provided" }
```

#### Implementation

```js
// commands/exec/navigate.action.js
export const action = async ({ route }, navigate) => {
  if (route) {
    navigate(route);
    await new Promise((resolve) => setTimeout(resolve, 1500));
    return { success: true, message: `Navigating to ${route}` };
  }
  return { success: false, message: 'Route not provided' };
};
```

The `navigate` function is injected at command registration time (not via registry):

```js
// In getExecCommands({ navigate, routeMap, ... })
{
  id: 'command_center.exec.navigate',
  action: (args) => Exec.navigate(args, navigate),  // navigate is closed over
}
```

#### Command Definition

```js
{
  id: 'command_center.exec.navigate',
  label: '/navigate',
  description: 'Navigate to a specific route in the application',
  schema: {
    type: 'object',
    properties: {
      route: {
        type: 'string',
        description: "Absolute route path (e.g. '/admin/projects', '/admin/agent-profiles'). Use routeMap for known routes."
      }
    },
    required: ['route']
  },
  action: (args) => Exec.navigate(args, navigate),
}
```

#### Route Map Integration

The `routeMap` constant passed to `getExecCommands` can be included in the command's description to help the LLM know valid routes:

```js
// In definitions.js or via schema description:
description: `Navigate to a route. Known routes: ${Object.entries(ROUTE_MAP).map(([k,v]) => `${k}: ${v}`).join(', ')}`
```

#### Notes

- The 1.5-second wait after navigation is intentional — it gives the new page time to mount its `useSommaticContextSource` and `useSommaticSurface` hooks before the next command in the plan executes.
- If a subsequent plan step needs page-context data from the new page, the 1.5s delay is usually sufficient, but highly dynamic pages (e.g., those with async data fetching) may still have `isLoading: true` when snapshotted.
- This command uses `navigate` from React Router's `useNavigate` hook, which must be available in the scope where `getExecCommands` is called (i.e., a component inside `<Router>`).

### `/claim-task`

`command_center.exec.tasks.claim`

Take ownership of a HITL Task

#### Purpose

Takes ownership of a HITL task by assigning it to the current user. After claiming, the task transitions to `in_progress` status and is locked to the claiming user.

#### When to Use

- When the user says "Claim task XYZ" or "Assign this task to me."
- As the second step in a HITL workflow: list inbox → claim a task → complete it.
- Before calling `exec.tasks.complete` — only claimed tasks can be completed.

#### Arguments

| Argument | Type | Required | Description |
|----------|------|----------|-------------|
| `task_id` | `string` | Yes | The ID of the task to claim. |

#### Return Value

```js
{
  ok: true,
  title: "Claimed task [task-abc123]",
  data: {
    id: "task-abc123",
    status: "in_progress",
    assigned_to: "user-xyz",
    claimed_at: "2026-02-25T21:00:00.000Z"
  },
  receipt_id: "rcpt_1772075473717_abc"
}
```

##### Error Cases

```js
{ ok: false, error: { code: "MISSING_TASK_ID", message: "task_id is required" } }
{ ok: false, error: { code: "NO_TASK_SERVICE", message: "Task service is not configured" } }
{ ok: false, error: { code: "CLAIM_FAILED", message: "Task is already claimed by another user" } }
```

#### Implementation

```js
// commands/exec/claimTask.action.js
export const action = async (args, registry) => {
  const { task_id } = args || {};

  if (!task_id) return { ok: false, error: { code: 'MISSING_TASK_ID', message: 'task_id is required' } };

  const taskStore = registry?.taskService;
  if (!taskStore) return { ok: false, error: { code: 'NO_TASK_SERVICE', message: 'Task service is not configured' } };

  try {
    const response = await taskStore.update({ id: task_id, action: 'claim' });
    const result = response?.result || response;

    const receipt = registry.pushReceipt?.({
      command_id: 'command_center.exec.tasks.claim',
      args,
      reversible: false,
      result,
    });

    return { ok: true, title: `Claimed task [${task_id}]`, data: result, receipt_id: receipt?.id };
  } catch (err) {
    return { ok: false, error: { code: 'CLAIM_FAILED', message: err.message } };
  }
};
```

#### Command Definition

```js
{
  id: 'command_center.exec.tasks.claim',
  label: '/claim-task',
  description: 'Claim a HITL task and assign it to the current user',
  schema: {
    type: 'object',
    properties: {
      task_id: { type: 'string', description: 'ID of the task to claim.' }
    },
    required: ['task_id']
  },
  action: (args) => Exec.claimTask(args, registry),
}
```

#### Task Service Contract

The `taskService.update` method receives:

```js
{ id: "task-abc123", action: "claim" }
```

It should return:

```js
{ result: { id, status, assigned_to, ... } }
// or directly: { id, status, assigned_to, ... }
```

#### Notes

- Claiming is irreversible in most workflows — there is no undo for a task claim.
- If the task service returns an error (e.g., task already claimed), the error message is surfaced as `CLAIM_FAILED`.

### `/comment-task`

`command_center.exec.tasks.comment`

Add comment to task

#### Purpose

Adds a text comment to a HITL task without changing its status. Comments provide a lightweight audit trail and allow users to document their reasoning, ask questions, or leave notes for other reviewers.

#### When to Use

- When the user wants to annotate a task: "Add a note to task XYZ saying 'Needs review from legal.'"
- For async collaboration: leaving feedback on a task before handing it off.
- As an alternative to completing a task when the user needs more information first.

#### Arguments

| Argument | Type | Required | Description |
|----------|------|----------|-------------|
| `task_id` | `string` | Yes | The ID of the task to comment on. |
| `comment` | `string` | Yes | The comment text. Must be non-empty. |

#### Return Value

```js
{
  ok: true,
  title: "Added comment to task [task-abc123]",
  data: {
    id: "task-abc123",
    comment_id: "comment-xyz",
    text: "Needs review from legal team.",
    created_at: "2026-02-25T22:30:00.000Z",
    created_by: "user-xyz"
  },
  receipt_id: "rcpt_1772075473717_abc"
}
```

##### Error Cases

```js
{ ok: false, error: { code: "MISSING_TASK_ID", message: "task_id is required" } }
{ ok: false, error: { code: "MISSING_COMMENT", message: "A non-empty comment is required" } }
{ ok: false, error: { code: "NO_TASK_SERVICE", message: "Task service is not configured" } }
{ ok: false, error: { code: "COMMENT_FAILED", message: "..." } }
```

#### Implementation

```js
// commands/exec/commentTask.action.js
export const action = async (args, registry) => {
  const { task_id, comment } = args || {};

  if (!task_id) return { ok: false, error: { code: 'MISSING_TASK_ID', message: 'task_id is required' } };

  if (!comment || typeof comment !== 'string' || comment.trim().length === 0) {
    return { ok: false, error: { code: 'MISSING_COMMENT', message: 'A non-empty comment is required' } };
  }

  const taskStore = registry?.taskService;
  if (!taskStore) return { ok: false, error: { code: 'NO_TASK_SERVICE', message: 'Task service is not configured' } };

  try {
    const response = await taskStore.update({ id: task_id, action: 'comment', comment: comment.trim() });
    const result = response?.result || response;

    const receipt = registry.pushReceipt?.({
      command_id: 'command_center.exec.tasks.comment',
      args: { task_id, comment: comment.trim() },
      reversible: false,
      result,
    });

    return { ok: true, title: `Added comment to task [${task_id}]`, data: result, receipt_id: receipt?.id };
  } catch (err) {
    return { ok: false, error: { code: 'COMMENT_FAILED', message: err.message } };
  }
};
```

#### Command Definition

```js
{
  id: 'command_center.exec.tasks.comment',
  label: '/comment-task',
  description: 'Add a comment to a HITL task',
  schema: {
    type: 'object',
    properties: {
      task_id: { type: 'string', description: 'ID of the task to comment on.' },
      comment: { type: 'string', description: 'Comment text to add. Must be non-empty.' }
    },
    required: ['task_id', 'comment']
  },
  action: (args) => Exec.commentTask(args, registry),
}
```

#### Task Service Contract

The `taskService.update` method receives:

```js
{ id: "task-abc123", action: "comment", comment: "Needs review from legal team." }
```

#### Notes

- Comments do not change task status. A task can be commented on regardless of whether it's `pending`, `in_progress`, or `completed`.
- The comment is trimmed of leading/trailing whitespace before being sent to the service.
- This command is not reversible — comments cannot be deleted via the Command Center.

### `/complete-task`

`command_center.exec.tasks.complete`

Complete task with validated outputs

#### Purpose

Completes a HITL task by submitting the required outputs. The task transitions to `completed` status and the automated workflow that created it can continue.

#### When to Use

- When the user has reviewed a task and wants to submit their decision/output.
- As the final step in a HITL workflow: list → claim → complete.
- When the user says "Complete task XYZ with approved: true."

#### Arguments

| Argument | Type | Required | Description |
|----------|------|----------|-------------|
| `task_id` | `string` | Yes | The ID of the task to complete. |
| `outputs` | `object` | Yes | The structured outputs required by the task. Shape defined by `task.outputs_schema`. |

#### Return Value

```js
{
  ok: true,
  title: "Completed task [task-abc123]",
  data: {
    id: "task-abc123",
    status: "completed",
    outputs: { approved: true, comment: "Looks good." },
    completed_at: "2026-02-25T22:00:00.000Z"
  },
  receipt_id: "rcpt_1772075473717_abc"
}
```

##### Error Cases

```js
{ ok: false, error: { code: "MISSING_TASK_ID", message: "task_id is required" } }
{ ok: false, error: { code: "MISSING_OUTPUTS", message: "outputs are required to complete a task" } }
{ ok: false, error: { code: "NO_TASK_SERVICE", message: "Task service is not configured" } }
{ ok: false, error: { code: "COMPLETE_FAILED", message: "Task is not in a completable state" } }
```

#### Implementation

```js
// commands/exec/completeTask.action.js
export const action = async (args, registry) => {
  const { task_id, outputs } = args || {};

  if (!task_id) return { ok: false, error: { code: 'MISSING_TASK_ID', message: 'task_id is required' } };
  if (!outputs) return { ok: false, error: { code: 'MISSING_OUTPUTS', message: 'outputs are required to complete a task' } };

  const taskStore = registry?.taskService;
  if (!taskStore) return { ok: false, error: { code: 'NO_TASK_SERVICE', message: 'Task service is not configured' } };

  try {
    const response = await taskStore.update({ id: task_id, action: 'complete', outputs });
    const result = response?.result || response;

    const receipt = registry.pushReceipt?.({
      command_id: 'command_center.exec.tasks.complete',
      args,
      reversible: false,
      result,
    });

    return { ok: true, title: `Completed task [${task_id}]`, data: result, receipt_id: receipt?.id };
  } catch (err) {
    return { ok: false, error: { code: 'COMPLETE_FAILED', message: err.message } };
  }
};
```

#### Command Definition

```js
{
  id: 'command_center.exec.tasks.complete',
  label: '/complete-task',
  description: 'Complete a HITL task with the provided outputs',
  schema: {
    type: 'object',
    properties: {
      task_id: { type: 'string', description: 'ID of the task to complete.' },
      outputs: {
        type: 'object',
        description: 'Task outputs. Structure defined by task outputs_schema. Use read.tasks.detail to inspect requirements.'
      }
    },
    required: ['task_id', 'outputs']
  },
  action: (args) => Exec.completeTask(args, registry),
}
```

#### Task Service Contract

The `taskService.update` method receives:

```js
{ id: "task-abc123", action: "complete", outputs: { approved: true } }
```

#### Typical Full HITL Flow

```
1. read.tasks.inbox { status: "pending" }
   → [{ id: "task-abc123", title: "Review agent config" }]

2. read.tasks.detail { task_id: "task-abc123" }
   → { outputs_schema: { approved: { type: "boolean" } } }

3. exec.tasks.claim { task_id: "task-abc123" }

4. exec.tasks.complete { task_id: "task-abc123", outputs: { approved: true, comment: "OK" } }
```

### `/create-task`

`command_center.exec.tasks.create`

Create a new HITL Task

#### Purpose

Creates a brand new Human-in-the-Loop task. Use this when an agent or operator needs to delegate a contractual decision (approval, data completion, review, resolution, delegation) to a person or group.

Tasks created here behave like any other HITL task: they appear in `/tasks-inbox`, can be claimed, commented on, transitioned, and completed.

#### When to Use

- When the user wants to formally hand off work that requires human judgment.
- When the user says "create a task to approve this", "delegate this to ops", "queue a review for finance".
- As the spawn step in a workflow that needs a human gate before proceeding.

Do NOT use this for transient notifications or for self-assigned reminders that don't need an audit trail — tasks are contractual, not casual.

#### Arguments

| Argument | Type | Required | Description |
|----------|------|----------|-------------|
| `title` | `string` | Yes | Short task title (the goal). Shown in inboxes and notifications. |
| `type` | `object` | Yes | Task type with `id` and `name`. One of: `approval`, `data_completion`, `review`, `resolution`, `delegation`. |
| `priority` | `object` | Yes | Priority with `id` and `name`. One of: `low`, `medium`, `high`, `critical`. |
| `required_output` | `object` | Yes | Definition of what the human must produce. Has a JSON `schema` and an optional `ui_hint`. |
| `assignee` | `object` | No | Assignee with `assignee_type: 'user' \| 'group'` and the matching `user` or `group` reference. Omitted assignee means an unclaimed task. |
| `sla` | `object` | No | SLA with `due_at` (Unix-ms timestamp string) and `sla_ms` (duration in ms). |
| `payload` | `object` | No | Context payload with `summary`, `evidence[]`, and `linked_entities[]` to give the assignee enough information to act. |

#### Return Value

```js
{
  ok: true,
  title: "Created task [task-abc123]",
  data: {
    id: "task-abc123",
    title: "Review onboarding evidence",
    status: "pending",
    type: { id: "review", name: "Review" },
    priority: { id: "high", name: "High" },
    organization_id: "org-xyz",
    created_at: "2026-05-01T10:00:00.000Z"
  },
  receipt_id: "rcpt_1772075473717_create"
}
```

##### Error Cases

```js
{ ok: false, error: { code: "MISSING_ARGS", message: "title, type, priority and required_output are required" } }
{ ok: false, error: { code: "NO_TASK_SERVICE", message: "Task service is not configured" } }
{ ok: false, error: { code: "CREATE_FAILED", message: "<service error>" } }
```

The receipt is **not** reversible — you cannot `/undo` a task creation. Cancel via `/task-transition { transition_name: 'invalidate' }` if needed.

#### Implementation

```js
// commands/exec/createTask.action.js
export const action = async (args, registry) => {
  const { title, type, priority, required_output, assignee, sla, payload } = args || {};

  if (!title || !type || !priority || !required_output) {
    return { ok: false, error: { code: 'MISSING_ARGS', message: 'title, type, priority and required_output are required' } };
  }

  const taskStore = registry?.taskService;
  if (!taskStore) {
    return { ok: false, error: { code: 'NO_TASK_SERVICE', message: 'Task service is not configured' } };
  }

  try {
    const organization_id = registry?.currentUser?.payload?.organization_id || '';
    const response = await taskStore.create({ title, type, priority, required_output, assignee, sla, payload, organization_id });
    const result = response?.result || response;

    const receipt = registry.pushReceipt?.({
      command_id: 'command_center.exec.tasks.create',
      args,
      reversible: false,
      result,
    });

    return { ok: true, title: `Created task [${result?.id}]`, data: result, receipt_id: receipt?.id };
  } catch (err) {
    return { ok: false, error: { code: 'CREATE_FAILED', message: err.message } };
  }
};
```

#### Command Definition

```js
{
  id: 'command_center.exec.tasks.create',
  label: '/create-task',
  description: 'Create a new HITL Task',
  schema: {
    type: 'object',
    properties: {
      title: { type: 'string', description: 'Short task title (the goal).' },
      type: { type: 'object', description: 'Task type object with id and name (approval, data_completion, review, resolution, delegation).' },
      priority: { type: 'object', description: 'Task priority object with id and name (low, medium, high, critical).' },
      required_output: { type: 'object', description: 'Required output definition with schema and optional ui_hint.' },
      assignee: { type: 'object', description: 'Optional. Assignee object with assignee_type (user|group) and user or group reference.' },
      sla: { type: 'object', description: 'Optional. SLA object with due_at (Unix ms string) and sla_ms (duration in ms).' },
      payload: { type: 'object', description: 'Optional. Context payload with summary, evidence[] and linked_entities[].' }
    },
    required: ['title', 'type', 'priority', 'required_output']
  },
  action: (args) => Exec.createTask(args, registry),
}
```

#### Task Service Contract

The `taskService.create` method receives:

```js
{
  title: "Review onboarding evidence",
  type: { id: "review", name: "Review" },
  priority: { id: "high", name: "High" },
  required_output: {
    schema: { type: 'object', properties: { approved: { type: 'boolean' } }, required: ['approved'] },
    ui_hint: 'checkbox',
  },
  assignee: { assignee_type: 'user', user: { id: 'user-12345' } },
  sla: { due_at: '1772075473717', sla_ms: 86400000 },
  payload: {
    summary: 'Review the latest onboarding evidence batch',
    evidence: [{ url: '...', kind: 'document' }],
    linked_entities: [{ type: 'organization', id: 'org-xyz' }],
  },
  organization_id: "org-xyz",
}
```

The `organization_id` is auto-attached from `registry.currentUser.payload.organization_id` — do not require the LLM to provide it.

#### Typical Flow

```
1. exec.tasks.create {
     title: "Approve refund #4421",
     type: { id: "approval", name: "Approval" },
     priority: { id: "high", name: "High" },
     required_output: { schema: { type: 'object', properties: { approved: { type: 'boolean' } } } },
     assignee: { assignee_type: 'group', group: { id: 'finance-leads' } }
   }
   → { id: "task-9988", status: "pending" }

2. (later) read.tasks.inbox { status: "pending" }
   → [{ id: "task-9988", title: "Approve refund #4421" }]

3. exec.tasks.claim { task_id: "task-9988" }

4. exec.tasks.complete { task_id: "task-9988", outputs: { approved: true } }
```

#### See Also

- `read.tasks.inbox.md` — list assigned tasks
- `read.tasks.detail.md` — inspect required-output schema
- `exec.tasks.claim.md` — take ownership
- `exec.tasks.complete.md` — submit outputs
- `exec.tasks.transition.md` — apply lifecycle transitions
- [docs/command-center/changelog-recent.en.md](../../../../../docs/command-center/changelog-recent.en.md) — full HITL command set overview

### `/task-transition`

`command_center.exec.tasks.transition`

Apply a lifecycle transition to a Task (assign, claim, start, complete, reject, invalidate, expire)

#### Purpose

Applies a lifecycle transition to a HITL task: `assign`, `claim`, `start`, `complete`, `reject`, `invalidate` or `expire`. It is the generic form of `exec.tasks.claim` and `exec.tasks.complete`, and the only command that can reject, invalidate or expire a task.

#### When to Use

- "Reject task XYZ because the document is illegible."
- "Assign task XYZ to Ana."
- Any transition that has no dedicated command.

Prefer `exec.tasks.claim` and `exec.tasks.complete` when they apply.

#### Arguments

| Argument | Type | Required | Description |
|----------|------|----------|-------------|
| `task_id` | `string` | Yes | ID of the task to transition. |
| `transition_name` | `string` | Yes | One of `assign`, `claim`, `start`, `complete`, `reject`, `invalidate`, `expire`. |
| `payload` | `object` | No | Extra data for the transition, e.g. `assignee`, `outputs`, `claimed_by`, `reason`. |

The action does not validate `transition_name` or `payload` itself: the backend decides whether the transition is allowed from the task's current state.

#### Return Value

```js
{
  ok: true,
  title: "Transition 'reject' applied to task [task-abc123]",
  data: { id: 'task-abc123', status: '<status after the transition>' /* task as returned by the backend */ },
  receipt_id: 'rcpt_1772075473717_abc'
}
```

`data` is `response.result` when present, otherwise the raw response.

##### Error Cases

```js
{ ok: false, error: { code: 'MISSING_ARGS', message: 'task_id and transition_name are required' } }
{ ok: false, error: { code: 'NO_TASK_SERVICE', message: 'Task service is not configured' } }
{ ok: false, error: { code: 'TRANSITION_FAILED', message: '<backend error message>' } }
```

#### Implementation

```js
// commands/exec/taskTransition.action.js
export const action = async (args, registry) => {
  const { task_id, transition_name, payload } = args || {};

  if (!task_id || !transition_name) {
    return { ok: false, error: { code: 'MISSING_ARGS', message: 'task_id and transition_name are required' } };
  }

  const taskStore = registry?.taskService;
  if (!taskStore) {
    return { ok: false, error: { code: 'NO_TASK_SERVICE', message: 'Task service is not configured' } };
  }

  try {
    const response = await taskStore.transition({ id: task_id, transition_name, payload });
    const result = response?.result || response;

    const receipt = registry.pushReceipt?.({
      command_id: 'command_center.exec.tasks.transition',
      args,
      reversible: false,
      result,
    });

    return { ok: true, title: `Transition '${transition_name}' applied to task [${task_id}]`, data: result, receipt_id: receipt?.id };
  } catch (err) {
    return { ok: false, error: { code: 'TRANSITION_FAILED', message: err.message } };
  }
};
```

#### Command Definition

```js
{
  id: 'command_center.exec.tasks.transition',
  label: '/task-transition',
  description: 'Apply a lifecycle transition to a Task (assign, claim, start, complete, reject, invalidate, expire)',
  isPriority: true,
  schema: {
    type: 'object',
    properties: {
      task_id: { type: 'string', description: 'ID of the task to transition.' },
      transition_name: {
        type: 'string',
        enum: ['assign', 'claim', 'start', 'complete', 'reject', 'invalidate', 'expire'],
        description: 'Transition to apply.'
      },
      payload: { type: 'object', nullable: true, description: 'Extra data for the transition (e.g. assignee, outputs, claimed_by).' }
    },
    required: ['task_id', 'transition_name']
  },
  action: (args) => Exec.taskTransition(args, registry),
}
```

#### Task Service Contract

`registry.taskService.transition(data)` receives:

```js
{ id: 'task-abc123', transition_name: 'reject', payload: { reason: 'Illegible document' } }
```

With the SDK's `WorkManagementTaskService`, this is a `PATCH` to `/work-management/task/transition/`.

### `/act-ui`

`command_center.exec.ui.act`

Execute deterministic action on a target

#### Purpose

Triggers a single action on a registered UI target — the most granular UI interaction command. It resolves a target reference and calls one of its registered handler methods.

#### When to Use

- When the LLM needs to click a button, fill an input, or trigger any specific target handler.
- For single, precise interactions (vs `exec.ui.act_batch` for multiple steps).
- After discovering available targets via `observe.ui` or `read.ui.targets.list`.

#### Arguments

| Argument | Type | Required | Description |
|----------|------|----------|-------------|
| `target_ref` | `string` | Yes | Target reference in format `{surface_id}::{target_id}`. |
| `method` | `string` | Yes | Handler method to call (e.g., `click`, `fill`, `getValue`, `select`). |
| `arguments` | `any[]` | No | Arguments to pass to the handler method. |

#### Return Value

```js
{
  ok: true,
  title: "Executed [click] on [create-project-form::submit-btn]",
  result: { /* whatever the handler returned */ },
  receipt_id: "rcpt_1772075473717_abc123"
}
```

##### Error Cases

```js
{ ok: false, error: { code: "MISSING_TARGET_REF", message: "target_ref is required" } }
{ ok: false, error: { code: "MISSING_METHOD", message: "method is required" } }
{ ok: false, error: { code: "TARGET_NOT_FOUND", message: "Target [xyz::btn] not found" } }
{ ok: false, error: { code: "METHOD_NOT_FOUND", message: "Method [click] not supported on target [xyz::btn]" } }
{ ok: false, error: { code: "ACTION_FAILED", message: "Handler threw: ..." } }
```

#### Implementation

```js
// commands/exec/actUi.action.js
export const action = async (args, registry) => {
  const { target_ref, method, arguments: methodArgs } = args || {};

  if (!target_ref) return { ok: false, error: { code: 'MISSING_TARGET_REF', message: 'target_ref is required' } };
  if (!method) return { ok: false, error: { code: 'MISSING_METHOD', message: 'method is required' } };

  const resolved = registry?.resolveTarget?.(target_ref);
  if (!resolved) return { ok: false, error: { code: 'TARGET_NOT_FOUND', message: `Target [${target_ref}] not found` } };

  const handler = resolved.target.handlers?.[method];
  if (!handler) return { ok: false, error: { code: 'METHOD_NOT_FOUND', message: `Method [${method}] not supported` } };

  let result;
  try {
    result = await handler(...(methodArgs || []));
  } catch (err) {
    return { ok: false, error: { code: 'ACTION_FAILED', message: err.message } };
  }

  const receipt = registry.pushReceipt?.({
    command_id: 'command_center.exec.ui.act',
    args,
    reversible: false,
    result,
  });

  return { ok: true, title: `Executed [${method}] on [${target_ref}]`, result, receipt_id: receipt?.id };
};
```

#### Command Definition

```js
{
  id: 'command_center.exec.ui.act',
  label: '/act',
  description: 'Trigger a single UI action on a registered target',
  schema: {
    type: 'object',
    properties: {
      target_ref: {
        type: 'string',
        description: "Target reference: 'surface_id::target_id' (e.g. 'create-project-form::submit-btn')"
      },
      method: {
        type: 'string',
        description: "Handler method to call (e.g. 'click', 'fill', 'select')"
      },
      arguments: {
        type: 'array',
        description: "Optional arguments to pass to the handler"
      }
    },
    required: ['target_ref', 'method']
  },
  action: (args) => Exec.actUi(args, registry),
}
```

#### Example Usages

```js
// Click a button
{ target_ref: "create-project-form::submit-btn", method: "click" }

// Fill an input
{ target_ref: "create-project-form::name-input", method: "fill", arguments: ["My New Project"] }

// Select an option
{ target_ref: "create-project-form::status-dropdown", method: "select", arguments: ["active"] }
```

#### Notes

- `resolveTarget(targetRef)` parses the `::` separator to find the surface and target.
- The `receipt` is always `reversible: false` because individual UI actions generally can't be trivially undone.
- For sequential multi-step UI interactions, prefer `exec.ui.act_batch`.

### `/act-batch-ui`

`command_center.exec.ui.act_batch`

Execute sequence of UI actions

#### Purpose

Executes a sequence of UI actions on registered targets, one step at a time. Useful when the user wants to fill multiple form fields or interact with several targets in a single command.

All steps are attempted sequentially. If a step fails, execution continues for independent steps but the overall result will report `ok: false`.

#### When to Use

- When a form requires multiple fields to be filled before submission.
- When the LLM generates a plan that involves clicking several targets.
- For batch automation: "Fill in name, status, and organization, then click submit."

#### Arguments

| Argument | Type | Required | Description |
|----------|------|----------|-------------|
| `steps` | `object[]` | Yes | Array of action steps. |
| `steps[].target_ref` | `string` | Yes | Target reference (`surface_id::target_id`). |
| `steps[].method` | `string` | Yes | Handler method to call. |
| `steps[].arguments` | `any[]` | No | Arguments for the method. |

#### Return Value

```js
{
  ok: true,
  title: "Executed 3/3 steps",
  step_results: [
    { target_ref: "create-form::name-input", method: "fill", ok: true, result: undefined },
    { target_ref: "create-form::status-select", method: "fill", ok: true, result: undefined },
    { target_ref: "create-form::submit-btn", method: "click", ok: true, result: { submitted: true } }
  ],
  receipt_id: "rcpt_1772075473717_xyz"
}
```

With partial failure:

```js
{
  ok: false,
  title: "Executed 2/3 steps",
  step_results: [
    { target_ref: "form::name-input", method: "fill", ok: true, result: undefined },
    { target_ref: "form::unknown-btn", method: "click", ok: false, error: "Target [form::unknown-btn] not found" },
    { target_ref: "form::submit-btn", method: "click", ok: true, result: { submitted: true } }
  ],
  receipt_id: "..."
}
```

##### Error Cases

```js
{ ok: false, error: { code: "MISSING_STEPS", message: "steps array is required and must not be empty" } }
```

#### Implementation

```js
// commands/exec/actBatchUi.action.js
export const action = async (args, registry) => {
  const { steps } = args || {};

  if (!Array.isArray(steps) || steps.length === 0) {
    return { ok: false, error: { code: 'MISSING_STEPS', message: 'steps array is required and must not be empty' } };
  }

  const stepResults = [];
  let hasError = false;

  for (const step of steps) {
    const { target_ref, method, arguments: methodArgs } = step;

    if (!target_ref || !method) {
      stepResults.push({ target_ref, method, ok: false, error: 'Missing target_ref or method' });
      hasError = true;
      continue;
    }

    const resolved = registry?.resolveTarget?.(target_ref);
    if (!resolved) {
      stepResults.push({ target_ref, method, ok: false, error: `Target [${target_ref}] not found` });
      hasError = true;
      continue;
    }

    const handler = resolved.target.handlers?.[method];
    if (!handler) {
      stepResults.push({ target_ref, method, ok: false, error: `Method [${method}] not supported` });
      hasError = true;
      continue;
    }

    try {
      const result = await handler(...(methodArgs || []));
      stepResults.push({ target_ref, method, ok: true, result });
    } catch (err) {
      stepResults.push({ target_ref, method, ok: false, error: err.message });
      hasError = true;
    }
  }

  const receipt = registry?.pushReceipt?.({
    command_id: 'command_center.exec.ui.act_batch',
    args,
    reversible: false,
    step_count: steps.length,
    success_count: stepResults.filter((r) => r.ok).length,
  });

  return {
    ok: !hasError,
    title: `Executed ${stepResults.filter((r) => r.ok).length}/${steps.length} steps`,
    step_results: stepResults,
    receipt_id: receipt?.id,
  };
};
```

#### Command Definition

```js
{
  id: 'command_center.exec.ui.act_batch',
  label: '/act-batch',
  description: 'Execute multiple UI actions sequentially',
  schema: {
    type: 'object',
    properties: {
      steps: {
        type: 'array',
        items: {
          type: 'object',
          properties: {
            target_ref: { type: 'string' },
            method: { type: 'string' },
            arguments: { type: 'array' }
          },
          required: ['target_ref', 'method']
        }
      }
    },
    required: ['steps']
  },
  action: (args) => Exec.actBatchUi(args, registry),
}
```

#### Notes

- Execution does **not** halt on failure — all steps are attempted regardless of errors.
- The `ok` field in the top-level response is `false` if **any** step failed.
- For independent steps, errors in one step do not affect subsequent steps.
- Steps requiring data from a previous step's result are not supported (use multiple single `exec.ui.act` commands in a plan instead).

### `/apply-filter`

`command_center.exec.ui.apply_filter`

Apply filters on Grid/List surface

#### Purpose

Applies a text filter to a registered grid or list surface. Calls the surface's `applyFilter` handler with the provided filter value, updating what is displayed in the grid.

#### When to Use

- When the user says "Filter the projects list by 'active'" or "Show only agents with name 'Test'."
- To narrow down a list before using `exec.ui.select_rows`.
- For quick search: "Find the project named 'Development'."

#### Arguments

| Argument | Type | Required | Description |
|----------|------|----------|-------------|
| `surface_id` | `string` | Yes | The ID of the grid/list surface to filter. |
| `filter` | `string` | Yes | The filter string to apply. Pass an empty string to clear the filter. |

#### Return Value

```js
{
  ok: true,
  title: "Applied filter 'active' to [project-list-grid]",
  receipt_id: "rcpt_1772075473717_abc"
}
```

##### Error Cases

```js
{ ok: false, error: { code: "MISSING_SURFACE_ID", message: "surface_id is required" } }
{ ok: false, error: { code: "MISSING_FILTER", message: "filter is required" } }
{ ok: false, error: { code: "SURFACE_NOT_FOUND", message: "Surface [xyz] not found" } }
{ ok: false, error: { code: "NO_FILTER_HANDLER", message: "Surface [xyz] has no applyFilter handler" } }
{ ok: false, error: { code: "FILTER_FAILED", message: "Handler threw: ..." } }
```

#### Implementation

```js
// commands/exec/applyFilter.action.js
export const action = async (args, registry) => {
  const { surface_id, filter } = args || {};

  if (!surface_id) return { ok: false, error: { code: 'MISSING_SURFACE_ID', message: 'surface_id is required' } };
  if (filter === undefined || filter === null) {
    return { ok: false, error: { code: 'MISSING_FILTER', message: 'filter is required' } };
  }

  const surface = registry?.getSurface?.(surface_id);
  if (!surface) return { ok: false, error: { code: 'SURFACE_NOT_FOUND', message: `Surface [${surface_id}] not found` } };

  if (!surface.handlers?.applyFilter) {
    return { ok: false, error: { code: 'NO_FILTER_HANDLER', message: `Surface [${surface_id}] has no applyFilter handler` } };
  }

  try {
    await surface.handlers.applyFilter(filter);
  } catch (err) {
    return { ok: false, error: { code: 'FILTER_FAILED', message: err.message } };
  }

  const receipt = registry.pushReceipt?.({
    command_id: 'command_center.exec.ui.apply_filter',
    args,
    reversible: true,
    undo: async () => surface.handlers.applyFilter(''),
  });

  return { ok: true, title: `Applied filter '${filter}' to [${surface_id}]`, receipt_id: receipt?.id };
};
```

#### Command Definition

```js
{
  id: 'command_center.exec.ui.apply_filter',
  label: '/apply-filter',
  description: 'Apply a text filter to a grid or list surface',
  schema: {
    type: 'object',
    properties: {
      surface_id: {
        type: 'string',
        description: "ID of the grid surface. Known surfaces: 'project-list-grid', 'agent-profile-list-grid', 'llm-provider-list-grid', 'cognitive-tool-list-grid', 'prompt-template-list-grid', 'external-datasource-list-grid'."
      },
      filter: {
        type: 'string',
        description: "Text to filter by. Pass empty string '' to clear the filter."
      }
    },
    required: ['surface_id', 'filter']
  },
  action: (args) => Exec.applyFilter(args, registry),
}
```

#### Registering a Filterable Grid

```jsx
const [filter, setFilter] = useState('');

useSommaticSurface({
  id: 'project-list-grid',
  type: 'grid',
  label: 'Project List',
  handlers: {
    applyFilter: (value) => setFilter(value),
    selectRows: (ids) => setSelectedRowIds(ids),
  },
}, []);

// In the DataGrid:
rows={projects.filter(p => p.name.toLowerCase().includes(filter.toLowerCase()))}
```

#### Notes

- `applyFilter` is `reversible: true` in the receipt — the undo handler calls `applyFilter('')` to clear the filter.
- The filter logic is implemented by the host component — the command just calls the handler with the string. Server-side filtering is also possible if the handler triggers an API call.
- To clear a filter, call `exec.ui.apply_filter` with `filter: ""`.

### `/close-surface`

`command_center.exec.ui.close_surface`

Close surface

#### Purpose

Closes a registered surface — a modal, drawer, or side panel — by calling its `close` handler.

#### When to Use

- After completing or canceling a form inside a modal.
- When the user says "close this" or "dismiss this panel."
- As a cleanup step after `exec.ui.submit_form`.

#### Arguments

| Argument | Type | Required | Description |
|----------|------|----------|-------------|
| `surface_id` | `string` | Yes | The ID of the surface to close. |

#### Return Value

```js
{
  ok: true,
  title: "Closed surface [create-project-modal]",
  receipt_id: "rcpt_1772075473717_xyz"
}
```

##### Error Cases

```js
{ ok: false, error: { code: "MISSING_SURFACE_ID", message: "surface_id is required" } }
{ ok: false, error: { code: "SURFACE_NOT_FOUND", message: "Surface [xyz] not found" } }
{ ok: false, error: { code: "NO_CLOSE_HANDLER", message: "Surface [xyz] has no close handler" } }
{ ok: false, error: { code: "CLOSE_FAILED", message: "Handler threw: ..." } }
```

#### Implementation

```js
// commands/exec/closeSurface.action.js
export const action = async (args, registry) => {
  const { surface_id } = args || {};

  if (!surface_id) return { ok: false, error: { code: 'MISSING_SURFACE_ID', message: 'surface_id is required' } };

  const surface = registry?.getSurface?.(surface_id);
  if (!surface) return { ok: false, error: { code: 'SURFACE_NOT_FOUND', message: `Surface [${surface_id}] not found` } };

  if (!surface.handlers?.close) {
    return { ok: false, error: { code: 'NO_CLOSE_HANDLER', message: `Surface [${surface_id}] has no close handler` } };
  }

  try {
    await surface.handlers.close();
  } catch (err) {
    return { ok: false, error: { code: 'CLOSE_FAILED', message: err.message } };
  }

  const receipt = registry.pushReceipt?.({
    command_id: 'command_center.exec.ui.close_surface',
    args,
    reversible: false,
  });

  return { ok: true, title: `Closed surface [${surface_id}]`, receipt_id: receipt?.id };
};
```

#### Command Definition

```js
{
  id: 'command_center.exec.ui.close_surface',
  label: '/close-surface',
  description: 'Close a modal, drawer, or panel surface',
  schema: {
    type: 'object',
    properties: {
      surface_id: { type: 'string', description: 'ID of the surface to close.' }
    },
    required: ['surface_id']
  },
  action: (args) => Exec.closeSurface(args, registry),
}
```

#### Notes

- The surface must be registered with a `close` handler. If the surface controls its own visibility via a `useState` setter, the handler should call it.
- After closing, the surface remains registered in the Command Center until its host component unmounts. The `getSurface(id)` call will still return the surface object.

### `/open-surface`

`command_center.exec.ui.open_surface`

Open a published surface

#### Purpose

Opens a registered surface — typically a modal, drawer, or side panel — by calling its `open` handler. The surface must be registered with an `open` handler that controls its visibility.

#### When to Use

- When the user asks to open a form, modal, or panel: "Open the create project form."
- As a prerequisite to `exec.ui.set_fields` or `exec.ui.submit_form` when the form lives inside a modal.
- For HITL app surfaces, prefer `exec.app.open` which supports async outputs.

#### Arguments

| Argument | Type | Required | Description |
|----------|------|----------|-------------|
| `surface_id` | `string` | Yes | The ID of the surface to open. |
| `params` | `object` | No | Optional parameters to pass to the `open` handler (e.g., initial form values). |

#### Return Value

```js
{
  ok: true,
  title: "Opened surface [create-project-form]",
  receipt_id: "rcpt_1772075473717_abc"
}
```

##### Error Cases

```js
{ ok: false, error: { code: "MISSING_SURFACE_ID", message: "surface_id is required" } }
{ ok: false, error: { code: "SURFACE_NOT_FOUND", message: "Surface [xyz] not found" } }
{ ok: false, error: { code: "NO_OPEN_HANDLER", message: "Surface [xyz] has no open handler" } }
{ ok: false, error: { code: "OPEN_FAILED", message: "Handler threw: ..." } }
```

#### Implementation

```js
// commands/exec/openSurface.action.js
export const action = async (args, registry) => {
  const { surface_id, params } = args || {};

  if (!surface_id) return { ok: false, error: { code: 'MISSING_SURFACE_ID', message: 'surface_id is required' } };

  const surface = registry?.getSurface?.(surface_id);
  if (!surface) return { ok: false, error: { code: 'SURFACE_NOT_FOUND', message: `Surface [${surface_id}] not found` } };

  if (!surface.handlers?.open) {
    return { ok: false, error: { code: 'NO_OPEN_HANDLER', message: `Surface [${surface_id}] has no open handler` } };
  }

  try {
    await surface.handlers.open(params);
  } catch (err) {
    return { ok: false, error: { code: 'OPEN_FAILED', message: err.message } };
  }

  const receipt = registry.pushReceipt?.({
    command_id: 'command_center.exec.ui.open_surface',
    args,
    reversible: false,
  });

  return { ok: true, title: `Opened surface [${surface_id}]`, receipt_id: receipt?.id };
};
```

#### Command Definition

```js
{
  id: 'command_center.exec.ui.open_surface',
  label: '/open-surface',
  description: 'Open a modal, drawer, or panel surface',
  schema: {
    type: 'object',
    properties: {
      surface_id: { type: 'string', description: 'ID of the surface to open.' },
      params: { type: 'object', description: 'Optional parameters to pass to the open handler.' }
    },
    required: ['surface_id']
  },
  action: (args) => Exec.openSurface(args, registry),
}
```

#### Registering an Openable Surface

```jsx
const [isOpen, setIsOpen] = useState(false);

useSommaticSurface({
  id: 'create-project-modal',
  type: 'modal',
  label: 'Create Project',
  handlers: {
    open: (params) => {
      if (params?.initialName) setProjectName(params.initialName);
      setIsOpen(true);
    },
    close: () => setIsOpen(false),
    submit: () => handleSubmit(),
  },
}, []);
```

#### Typical Chained Flow

```
1. exec.ui.open_surface { surface_id: "create-project-modal" }
2. exec.ui.set_fields { surface_id: "create-project-modal", fields: { name: "New Project", status: "active" } }
3. exec.ui.submit_form { surface_id: "create-project-modal" }
```

### `/select-rows`

`command_center.exec.ui.select_rows`

Select rows/items

#### Purpose

Selects rows in a registered grid surface. Supports two selection modes:
1. **By direct row IDs** — when the exact IDs are known.
2. **By identifiers + field matching** — when IDs are unknown but values like slugs or names are known. Uses the `page-context` snapshot to resolve identifiers to IDs.

After execution, rows are visually highlighted in the grid and the selection is reported to `useSommaticSelection`, making it accessible via `read.selection.get`.

#### When to Use

- When the user says "Select the row with slug 'my-project'."
- Before performing a batch operation on selected rows.
- When the LLM resolves entity names to IDs using page context.

#### Arguments

| Argument | Type | Required | Description |
|----------|------|----------|-------------|
| `surface_id` | `string` | Yes | The ID of the grid surface. |
| `row_ids` | `string[]` | No | Array of exact row IDs to select. |
| `identifiers` | `string[]` | No | Values to match (e.g., slugs or names) when exact IDs are unknown. Requires `match_field`. |
| `match_field` | `string` | No | Field in the page-context `items` array to match `identifiers` against (e.g., `'slug'`, `'name'`). Defaults to `'id'`. |

At least one of `row_ids` or `identifiers` must be provided.

#### Return Value

```js
{
  ok: true,
  title: "Selected 2 rows in [project-list-grid]",
  selected_count: 2,
  selected_ids: ["prj-management-a4b0e53a9532edd", "prj-management-f00d4ca337d8dcb"],
  receipt_id: "rcpt_1772112464496_2kolnjx"
}
```

##### Error Cases

```js
{ ok: false, error: { code: "MISSING_SURFACE_ID", message: "surface_id is required" } }
{ ok: false, error: { code: "MISSING_ROW_IDS", message: "Either row_ids or identifiers must be provided" } }
{ ok: false, error: { code: "NO_SELECTION_HANDLER", message: "Surface [xyz] has no selectRows handler" } }
{ ok: false, error: { code: "NO_PAGE_CONTEXT", message: "page-context snapshot unavailable for identifier resolution" } }
{ ok: false, error: { code: "NO_ITEMS_IN_CONTEXT", message: "page-context snapshot has no 'items' array" } }
{ ok: false, error: { code: "NO_MATCHES", message: "No items matched the provided identifiers" } }
```

#### Implementation

```js
// commands/exec/selectRows.action.js
export const action = async (args, registry) => {
  const { surface_id, row_ids, identifiers, match_field = 'id' } = args || {};

  if (!surface_id) return { ok: false, error: { code: 'MISSING_SURFACE_ID', message: 'surface_id is required' } };

  const surface = registry?.getSurface?.(surface_id);
  if (!surface) return { ok: false, error: { code: 'SURFACE_NOT_FOUND', message: `Surface [${surface_id}] not found` } };

  if (!surface.handlers?.selectRows) {
    return { ok: false, error: { code: 'NO_SELECTION_HANDLER', message: `Surface [${surface_id}] has no selectRows handler` } };
  }

  let resolvedIds = Array.isArray(row_ids) ? [...row_ids] : [];

  // Resolve identifiers to IDs using page-context snapshot
  if (Array.isArray(identifiers) && identifiers.length > 0 && match_field !== 'id') {
    const snapshot = registry?.getSnapshot?.('page-context');
    const items = snapshot?.payload?.items;

    if (!items) return { ok: false, error: { code: 'NO_PAGE_CONTEXT', message: 'page-context snapshot unavailable' } };
    if (!Array.isArray(items)) return { ok: false, error: { code: 'NO_ITEMS_IN_CONTEXT', message: 'page-context has no items array' } };

    const normalized = identifiers.map((v) => String(v).toLowerCase());
    const matched = items.filter((item) =>
      normalized.includes(String(item[match_field] ?? '').toLowerCase())
    );

    if (matched.length === 0) {
      return { ok: false, error: { code: 'NO_MATCHES', message: `No items matched identifiers via field '${match_field}'` } };
    }

    resolvedIds = [...resolvedIds, ...matched.map((item) => item.id)];
  }

  if (resolvedIds.length === 0 && (!Array.isArray(identifiers) || identifiers.length === 0)) {
    return { ok: false, error: { code: 'MISSING_ROW_IDS', message: 'Either row_ids or identifiers must be provided' } };
  }

  await surface.handlers.selectRows(resolvedIds);

  const receipt = registry.pushReceipt?.({
    command_id: 'command_center.exec.ui.select_rows',
    args,
    reversible: true,
    undo: async () => surface.handlers.selectRows([]),
  });

  return {
    ok: true,
    title: `Selected ${resolvedIds.length} rows in [${surface_id}]`,
    selected_count: resolvedIds.length,
    selected_ids: resolvedIds,
    receipt_id: receipt?.id,
  };
};
```

#### Command Definition

```js
{
  id: 'command_center.exec.ui.select_rows',
  label: '/select-rows',
  description: 'Select rows in a grid by IDs or by matching field values',
  schema: {
    type: 'object',
    properties: {
      surface_id: {
        type: 'string',
        description: "ID of the grid surface. Known surfaces: 'project-list-grid', etc."
      },
      row_ids: {
        type: 'array',
        items: { type: 'string' },
        description: 'Array of exact row IDs to select.'
      },
      identifiers: {
        type: 'array',
        items: { type: 'string' },
        description: "Values to match when IDs are unknown (e.g., slugs or names). Use with match_field."
      },
      match_field: {
        type: 'string',
        description: "Field to match identifiers against (e.g. 'slug', 'name'). Requires page-context items array."
      }
    },
    required: ['surface_id']
  },
  action: (args) => Exec.selectRows(args, registry),
}
```

#### Visual Feedback Requirements

For rows to appear visually selected in MUI DataGrid, the host component must:

```jsx
const [selectedRowIds, setSelectedRowIds] = useState([]);

// In the surface handler:
handlers: {
  selectRows: (ids) => setSelectedRowIds(ids),
}

// In the DataGrid:
<DataGrid
  checkboxSelection
  rowSelectionModel={selectedRowIds}
  onRowSelectionModelChange={(ids) => setSelectedRowIds(ids)}
  disableRowSelectionOnClick={true}
/>
```

Without `rowSelectionModel` bound to state, the command will update state internally but rows won't appear visually highlighted.

#### Notes

- Identifier-to-ID resolution requires `page-context` to have an `items` array in its payload. The host component's `getData()` must include this array.
- The receipt is `reversible: true`. The undo operation calls `selectRows([])` to clear the selection.
- After selecting rows, `read.selection.get` will return the selected IDs if `useSommaticSelection` is wired up.

### `/set-fields`

`command_center.exec.ui.set_fields`

Set multiple fields in a FormSurface

#### Purpose

Fills one or more form fields by calling a surface's `setFields` handler with a key-value map. This is a high-level alternative to calling `exec.ui.act` on individual targets, designed for form surfaces that expose a batch-set API.

#### When to Use

- When the user asks to pre-fill a form: "Fill in the form with name 'Test Project' and status 'active'."
- As part of a flow: open modal → set fields → submit form.
- When a form surface is registered with a `setFields` handler that accepts a `fields` object.

#### Arguments

| Argument | Type | Required | Description |
|----------|------|----------|-------------|
| `surface_id` | `string` | Yes | The ID of the form surface. |
| `fields` | `object` | Yes | Key-value map of field names to values. |

#### Return Value

```js
{
  ok: true,
  title: "Set fields on [create-project-form]",
  fields_set: ["name", "status", "organization"],
  receipt_id: "rcpt_1772075473717_abc"
}
```

##### Error Cases

```js
{ ok: false, error: { code: "MISSING_SURFACE_ID", message: "surface_id is required" } }
{ ok: false, error: { code: "MISSING_FIELDS", message: "fields object is required" } }
{ ok: false, error: { code: "SURFACE_NOT_FOUND", message: "Surface [xyz] not found" } }
{ ok: false, error: { code: "NO_SET_FIELDS_HANDLER", message: "Surface [xyz] has no setFields handler" } }
{ ok: false, error: { code: "SET_FIELDS_FAILED", message: "Handler threw: ..." } }
```

#### Implementation

```js
// commands/exec/setFields.action.js
export const action = async (args, registry) => {
  const { surface_id, fields } = args || {};

  if (!surface_id) return { ok: false, error: { code: 'MISSING_SURFACE_ID', message: 'surface_id is required' } };
  if (!fields || typeof fields !== 'object') {
    return { ok: false, error: { code: 'MISSING_FIELDS', message: 'fields object is required' } };
  }

  const surface = registry?.getSurface?.(surface_id);
  if (!surface) return { ok: false, error: { code: 'SURFACE_NOT_FOUND', message: `Surface [${surface_id}] not found` } };

  if (!surface.handlers?.setFields) {
    return { ok: false, error: { code: 'NO_SET_FIELDS_HANDLER', message: `Surface [${surface_id}] has no setFields handler` } };
  }

  try {
    await surface.handlers.setFields(fields);
  } catch (err) {
    return { ok: false, error: { code: 'SET_FIELDS_FAILED', message: err.message } };
  }

  const receipt = registry.pushReceipt?.({
    command_id: 'command_center.exec.ui.set_fields',
    args,
    reversible: false,
    fields_set: Object.keys(fields),
  });

  return {
    ok: true,
    title: `Set fields on [${surface_id}]`,
    fields_set: Object.keys(fields),
    receipt_id: receipt?.id,
  };
};
```

#### Command Definition

```js
{
  id: 'command_center.exec.ui.set_fields',
  label: '/set-fields',
  description: 'Fill form fields with a key-value map',
  schema: {
    type: 'object',
    properties: {
      surface_id: { type: 'string', description: 'ID of the form surface.' },
      fields: {
        type: 'object',
        description: 'Key-value map of fields to fill (e.g. { "name": "My Project", "status": "active" }).'
      }
    },
    required: ['surface_id', 'fields']
  },
  action: (args) => Exec.setFields(args, registry),
}
```

#### Registering a Form With `setFields`

```jsx
const [name, setName] = useState('');
const [status, setStatus] = useState('active');

useSommaticSurface({
  id: 'create-project-form',
  type: 'form',
  label: 'Create Project Form',
  handlers: {
    setFields: (fields) => {
      if (fields.name !== undefined) setName(fields.name);
      if (fields.status !== undefined) setStatus(fields.status);
    },
    submit: () => handleSubmit(),
  },
}, []);
```

#### Notes

- `setFields` is a surface-level batch setter. Individual target-level setters are handled via `exec.ui.act` with method `fill`.
- The `setFields` handler in the surface is responsible for deciding which fields to update — unknown keys can be silently ignored.
- After calling `set_fields`, you can validate the values with `extract.from_targets` before submitting.

### `/submit-form`

`command_center.exec.ui.submit_form`

Submit published form

#### Purpose

Submits a registered form surface programmatically by calling its `submit` handler. The surface handles all validation and submission logic internally.

#### When to Use

- As the final step after filling a form with `exec.ui.set_fields`.
- When the user says "Submit the form" or "Save this."
- In automated flows: open modal → set fields → submit.

#### Arguments

| Argument | Type | Required | Description |
|----------|------|----------|-------------|
| `surface_id` | `string` | Yes | The ID of the form surface to submit. |

#### Return Value

```js
{
  ok: true,
  title: "Submitted form [create-project-form]",
  data: { /* whatever the submit handler returned */ },
  receipt_id: "rcpt_1772075473717_abc"
}
```

##### Error Cases

```js
{ ok: false, error: { code: "MISSING_SURFACE_ID", message: "surface_id is required" } }
{ ok: false, error: { code: "SURFACE_NOT_FOUND", message: "Surface [xyz] not found" } }
{ ok: false, error: { code: "NO_SUBMIT_HANDLER", message: "Surface [xyz] has no submit handler" } }
{ ok: false, error: { code: "SUBMIT_FAILED", message: "Handler threw: Validation error: name is required" } }
```

#### Implementation

```js
// commands/exec/submitForm.action.js
export const action = async (args, registry) => {
  const { surface_id } = args || {};

  if (!surface_id) return { ok: false, error: { code: 'MISSING_SURFACE_ID', message: 'surface_id is required' } };

  const surface = registry?.getSurface?.(surface_id);
  if (!surface) return { ok: false, error: { code: 'SURFACE_NOT_FOUND', message: `Surface [${surface_id}] not found` } };

  if (!surface.handlers?.submit) {
    return { ok: false, error: { code: 'NO_SUBMIT_HANDLER', message: `Surface [${surface_id}] has no submit handler` } };
  }

  let result;
  try {
    result = await surface.handlers.submit();
  } catch (err) {
    return { ok: false, error: { code: 'SUBMIT_FAILED', message: err.message } };
  }

  const receipt = registry.pushReceipt?.({
    command_id: 'command_center.exec.ui.submit_form',
    args,
    reversible: false,
    result,
  });

  return { ok: true, title: `Submitted form [${surface_id}]`, data: result, receipt_id: receipt?.id };
};
```

#### Command Definition

```js
{
  id: 'command_center.exec.ui.submit_form',
  label: '/submit-form',
  description: 'Submit a registered form surface',
  schema: {
    type: 'object',
    properties: {
      surface_id: { type: 'string', description: 'ID of the form surface to submit.' }
    },
    required: ['surface_id']
  },
  action: (args) => Exec.submitForm(args, registry),
}
```

#### Registering a Form With a Submit Handler

```jsx
const handleSubmit = async () => {
  try {
    await createProject({ name, status, organizationId });
    setIsOpen(false);
    return { success: true };
  } catch (err) {
    throw new Error(`Validation error: ${err.message}`);
  }
};

useSommaticSurface({
  id: 'create-project-form',
  type: 'form',
  label: 'Create Project Form',
  handlers: {
    submit: handleSubmit,
    setFields: (f) => { /* ... */ },
  },
}, []);
```

#### Notes

- The `submit` handler should throw if validation fails — the error message will be returned as `SUBMIT_FAILED`.
- If the form submits successfully and closes a modal, register the `close` handler separately and call `exec.ui.close_surface` as a follow-up if needed.
- `data` in the success response is whatever `submit()` returns — useful for getting created entity IDs in follow-up steps.

### `/undo`

`command_center.exec.undo`

Attempt to revert an action

#### Purpose

Reverses the last reversible action in the receipt stack. Looks for the most recent receipt where `reversible: true` and calls its `undo` handler.

#### When to Use

- When the user says "Undo that" or "Revert the last action."
- After accidentally applying a filter or selecting rows the user didn't intend.
- For quick rollback in automated flows.

#### Arguments

None.

#### Return Value

```js
{
  ok: true,
  title: "Undone: exec.ui.apply_filter",
  undone_receipt_id: "rcpt_1772075473717_abc",
  receipt_id: "rcpt_1772075480000_undo"
}
```

If no reversible action exists:

```js
{
  ok: false,
  error: { code: "NOTHING_TO_UNDO", message: "No reversible action found in receipt stack" }
}
```

If undo fails:

```js
{
  ok: false,
  error: { code: "UNDO_FAILED", message: "Undo handler threw: ..." }
}
```

#### Implementation

```js
// commands/exec/undo.action.js
export const action = async (args, registry) => {
  const stack = registry?.getReceiptStack?.() || [];

  const reversibleReceipt = stack.find((receipt) => receipt.reversible && receipt.undo);

  if (!reversibleReceipt) {
    return { ok: false, error: { code: 'NOTHING_TO_UNDO', message: 'No reversible action found in receipt stack' } };
  }

  try {
    await reversibleReceipt.undo();
  } catch (err) {
    return { ok: false, error: { code: 'UNDO_FAILED', message: err.message } };
  }

  // Remove the undone receipt from the stack
  registry?.removeReceipt?.(reversibleReceipt.id);

  const receipt = registry.pushReceipt?.({
    command_id: 'command_center.exec.undo',
    args: {},
    reversible: false,
    undone_command: reversibleReceipt.command_id,
  });

  return {
    ok: true,
    title: `Undone: ${reversibleReceipt.command_id}`,
    undone_receipt_id: reversibleReceipt.id,
    receipt_id: receipt?.id,
  };
};
```

#### Command Definition

```js
{
  id: 'command_center.exec.undo',
  label: '/undo',
  description: 'Undo the last reversible action',
  schema: {},
  action: () => Exec.undo(registry),
}
```

#### Which Commands Are Reversible?

| Command | Reversible | Undo Action |
|---------|-----------|-------------|
| `exec.ui.apply_filter` | Yes | `applyFilter('')` (clear filter) |
| `exec.ui.select_rows` | Yes | `selectRows([])` (clear selection) |
| `exec.ui.act` | No | — |
| `exec.ui.act_batch` | No | — |
| `exec.ui.open_surface` | No | — |
| `exec.ui.close_surface` | No | — |
| `exec.ui.set_fields` | No | — |
| `exec.ui.submit_form` | No | — |
| `exec.navigate` | No | — |
| `exec.clipboard.copy` | No | — |
| `exec.app.open` | No | — |
| `exec.command.invoke` | No | — |
| `exec.tasks.*` | No | — |

#### Making a Command Reversible

When implementing an exec command, pass `reversible: true` and an `undo` function to `pushReceipt`:

```js
const receipt = registry.pushReceipt?.({
  command_id: 'command_center.exec.ui.apply_filter',
  args,
  reversible: true,
  undo: async () => {
    await surface.handlers.applyFilter('');
  },
});
```

The `undo` function must be a closure that captures everything needed to reverse the action.

#### Notes

- The receipt stack is searched from most recent to oldest for the first `reversible: true` entry.
- The `exec.undo` receipt itself is not reversible (you can't "undo an undo").
- The undo stack is in-memory only — it is lost on page refresh.
- Complex state mutations (API calls, database changes) should not be marked as reversible unless a true rollback mechanism exists on the backend.

### `/run-workflow`

`command_center.exec.workflow.run`

Run a workflow by intent (e.g. 'ejecuta este workflow' or 'ejecuta el workflow de recomendaciones mascotas'). This hands the workflow to the Workflow Navigator app, which executes it, shows live per-node progress, and returns the result to continue the plan. You do NOT need an id: when a workflow is open on screen it resolves from the active page context automatically; otherwise pass `workflow_name` with the name the user referenced and it is resolved within your organization. Pass `input` describing what the user asked when relevant (e.g. set input.text to the pet description the user gave); if you omit it the run uses the workflow's example input. Provide `flow_version_id` to force the published version or `flow_definition_id` to force a specific draft.

#### Purpose

Resolves a workflow by intent and hands it to the **Workflow Navigator** app (`sommatic-workflow-navigator`), opened in `command-center` launch mode. The command does **not** execute the workflow itself: the app runs it, shows live per-node progress and returns the result through `sdk.submitOutput()`, so the execution plan can continue (for example, chaining into another app).

No pre-defined Trigger artifact is required. The run is attributed through an `execution_source` stamped on the descriptor.

#### When to Use

- "Run this workflow" while a workflow is open on screen.
- "Run the pet recommendations workflow" from any screen: the workflow is resolved by name within the organization.
- As a step of an execution plan that needs a workflow result before continuing.

#### Arguments

| Argument | Type | Required | Description |
|----------|------|----------|-------------|
| `workflow_name` | `string` | No | Name the user referenced. Used only when no id is given and no runnable workflow is open on screen. |
| `flow_definition_id` | `string` | No | Definition (draft) to run in test mode. |
| `flow_version_id` | `string` | No | Compiled version to run in production mode. Takes priority over `flow_definition_id`. |
| `input` | `object` | No | Input payload. Merged field by field over the trigger's example payload. |

At least one of the three resolution paths must succeed (see below); otherwise the command returns `MISSING_FLOW_ID`.

#### Resolution Cascade

Explicit arguments always win:

1. **`flow_definition_id` / `flow_version_id`** from the arguments.
2. **The workflow open on screen:** the `page-context` snapshot's `payload.run` descriptor, when `run.runnable` is true. It also provides the run name and the trigger's `input_example`.
3. **`workflow_name`:** searched in the organization through `WorkflowOrchestrationFlowDefinitionService.getByParameters({ queryselector: 'search', search, organization_id, exclude_status: 'deleted', pageSize: 1 })`. The first match is used; its trigger node's `config.payload_template` becomes the example input.

#### Input Binding

The run input is `{ ...inputExample, ...args.input }`. Then, only for keys the trigger payload already declares:

| Key | Bound to, when empty |
|-----|----------------------|
| `source_url` | URL of the latest file attached in the Command Center (`registry.getActiveAttachments()`), unless the caller passed `input.source_url`. |
| `assignee` | The current user's identity. |
| `organization_id` | The current user's organization. |

#### Return Value

An `app-embed` descriptor that opens the Navigator:

```js
{
  ok: true,
  type: 'app-embed',
  title: 'Running workflow "Pet recommendations"',
  app_embed: {
    app_slug: 'sommatic-workflow-navigator',
    route_path: '/run',
    launch_mode: 'command-center',
    input_payload: {
      run: {
        flow_definition_id: 'flow-def-abc123',
        flow_version_id: null,
        input: { text: 'Small dog, lives in an apartment' },
        organization_id: 'org-xyz',
        user_identity: 'user-123',
        execution_source: {
          source: 'command-center',
          app_slug: 'sommatic-workflow-navigator',
          actor: 'user-123',
          intent_text: 'pet recommendations'
        },
        name: 'Pet recommendations'
      }
    }
  },
  receipt_id: 'rcpt_1772075473717_abc'
}
```

##### Error Cases

```js
{ ok: false, error: { code: 'MISSING_FLOW_ID', message: 'No workflow could be resolved. Provide flow_definition_id, flow_version_id, or a workflow_name that matches one in your organization.' } }
```

A failed name lookup is not an error by itself: it falls through to `MISSING_FLOW_ID`.

#### Command Definition

```js
{
  id: 'command_center.exec.workflow.run',
  label: '/run-workflow',
  description: 'Run a workflow by intent. Hands the workflow to the Workflow Navigator app, which executes it, shows live per-node progress, and returns the result to continue the plan...',
  isPriority: true,
  schema: {
    type: 'object',
    properties: {
      workflow_name: { type: 'string' },
      flow_definition_id: { type: 'string' },
      flow_version_id: { type: 'string' },
      input: { type: 'object' }
    }
  },
  action: (args) => Exec.runWorkflow(args, registry),
}
```

The full description text lives in `commands/definitions.js`.

#### Receipt

A receipt is pushed with `command_id: 'command_center.exec.workflow.run'` and `reversible: false`. A started run cannot be undone with `exec.undo`.
