2 Commits
Author SHA1 Message Date
jpmschweitzerandClaude 498bbc1205 add typed IPC command-schema framework (T-120)
test / unit + widget + golden + a11y (push) Failing after 28s
test / integration_test (xvfb) (push) Has been skipped
test / bundle smoke (xvfb 5s) (push) Has been skipped
test / daemon subprocess + web WASM smoke (push) Has been skipped
test / dart doc (lib API) (push) Failing after 23s
Per D-74: commands register an argument schema beside their handler
instead of hand-validating args inline. DaemonDispatcher accumulates a
cmd->schema registry and, before invoking a handler, normalises the
argv-translator shape ({positional, flags}) into named args, coerces
types, and checks per-arg constraints (charset/pattern, leading-dash
rejection, numeric range, list caps). Violations return userError so no
handler sees malformed input. Schema adoption is opt-in per command —
unschema'd commands dispatch unchanged.

panel.resize adopts a schema (dropping the _ResizeArgs hand-lift from
T-119); git.checkout and git.push gain schemas that reject leading-dash
refs at the dispatcher and, via positional ordering, fix the C-client
CLI path — `clide git checkout <branch>` now reaches the handler, where
the positional token previously never mapped to `branch`. The T-104
validateGitRef + count/path caps stay in place as defense-in-depth
because the git client is reachable directly from the UI, not only
through the dispatcher.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-05-20 18:02:30 +02:00
jpmschweitzerandClaude 97c83b8fc9 record D-74: co-registered IPC command schema
Captures the T-120 design decision: the typed argument schema travels
with each command (built-in modules and extension contributions both
register their own) rather than living in a central static map, which
would be blind to extension-contributed commands and fight the plugin
model (D-46). The dispatcher accumulates a cmd->schema registry and
validates req.args before invoking the handler. The T-104 git
validators stay as defense-in-depth because the git client is also
reachable directly from the UI. MCP tools/list generation deferred to
the T-130 track.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-05-20 17:54:47 +02:00
12 changed files with 568 additions and 71 deletions
+34
View File
@@ -1892,3 +1892,37 @@ Source: consultants.md "Security — Findings — [Major]" item 1.', NULL, '2026
INSERT INTO ticket_history (ticket_id, field, old_value, new_value, changed_by, changed_at, created_at, updated_at, deleted_at, hash, canonical_version) VALUES ('T-99', 'status', 'backlog', 'done', NULL, '2026-05-19 13:14:41', '2026-05-19 13:14:41', '2026-05-19 13:14:41', NULL, '5ff47ab0fc7fb8cb8e9e039be48ada2a', 1) ON CONFLICT(hash) DO NOTHING;
INSERT INTO ticket_history (ticket_id, field, old_value, new_value, changed_by, changed_at, created_at, updated_at, deleted_at, hash, canonical_version) VALUES ('T-131', 'status', 'in_progress', 'done', NULL, '2026-05-19 13:14:41', '2026-05-19 13:14:41', '2026-05-19 13:14:41', NULL, 'a57b3fbe4e6815fcbb28691a08130801', 1) ON CONFLICT(hash) DO NOTHING;
INSERT INTO ticket_history (ticket_id, field, old_value, new_value, changed_by, changed_at, created_at, updated_at, deleted_at, hash, canonical_version) VALUES ('T-119', 'status', 'ready', 'in_progress', NULL, '2026-05-19 14:44:43', '2026-05-19 14:44:43', '2026-05-19 14:44:43', NULL, '1d5048cf9a031c504aa3df570a7b0cae', 1) ON CONFLICT(hash) DO NOTHING;
INSERT INTO ticket_history (ticket_id, field, old_value, new_value, changed_by, changed_at, created_at, updated_at, deleted_at, hash, canonical_version) VALUES ('T-119', 'status', 'in_progress', 'done', NULL, '2026-05-20 07:00:06', '2026-05-20 07:00:06', '2026-05-20 07:00:06', NULL, '1f2c2bcc722417d8f4c5bfa27faf0c93', 1) ON CONFLICT(hash) DO NOTHING;
INSERT INTO ticket_history (ticket_id, field, old_value, new_value, changed_by, changed_at, created_at, updated_at, deleted_at, hash, canonical_version) VALUES ('T-120', 'description', 'T-104 covered the spot-fixes (argv-injection rejection, size/count caps on specific commands). What remains is the framework piece: a typed schema per IPC command — branch/remote/path/etc. with regex/charset constraints — applied at DaemonDispatcher dispatch time rather than scattered through individual handlers.
Re-scope (2026-05-19, post T-99): the wire contract is now real — IpcRequest envelopes flow over the unix socket (per D-70/71/72) and through the C clide client which serialises raw argv under the `_argv` sentinel (per D-72/D-6). The argv parser (lib/src/cli/argv_to_request.dart) is the de-facto schema today; T-120 should formalise it by:
- Lifting the per-cmd grammar from argv_to_request.dart into a typed registry keyed by cmd, sharing it with both the argv parser and the dispatcher.
- Using the same registry to validate inbound IpcRequests at dispatch time (regex/charset constraints on branch/remote/path args).
- Exposing the registry to the MCP server (T-130) so the `tools/list` payload is generated rather than hand-rolled.
Design still open:
- Where the schema lives (per-handler? central registry?).
- Whether it generates handler boilerplate or wraps existing handlers.
Source: consultants.md "Security — Findings — [Major]" item 1.', 'T-104 covered the spot-fixes (argv-injection rejection, size/count caps on specific commands). What remains is the framework piece: a typed schema per IPC command — branch/remote/path/etc. with regex/charset constraints — applied at DaemonDispatcher dispatch time rather than scattered through individual handlers.
---
Design resolved 2026-05-20 (see D-74). Co-registration model, NOT a central map:
- The argv parser (lib/src/cli/argv_to_request.dart) only knows syntactic shape (identifier/flag charset, -- terminator); it has NO per-command argument knowledge. So this is build-fresh, not a lift — each handler currently hand-reads its own keys.
- Extend the DaemonDispatcher registration API to carry an optional typed schema per command. The dispatcher accumulates a cmd->schema registry as commands register (built-in register*Commands modules supply theirs; extension CommandContributions carry their own — central static map rejected because it cannot see extension-contributed commands, D-46).
- DaemonDispatcher.dispatch validates req.args against schema[cmd] BEFORE invoking the handler (hook at dispatcher.dart line 39, the `return h(req)` call). Violation -> userError (sysexit 64). Commands with no schema dispatch unvalidated (opt-in per command) until migrated.
- Constraint vocabulary is hand-rolled (prefer-zero-deps): per-arg required/optional, kind, charset/regex, numeric range. Collapses the _ResizeArgs-style hand-lifts (panel_commands.dart, T-119) into schema.
- KEEP existing T-104 checks as defense-in-depth: validateGitRef (lib/src/git/operations.dart:46) and the count/path caps (lib/src/daemon/git_commands.dart:18,23). The git client is callable directly from the Flutter UI, not only via the dispatcher — do not remove them.
- OUT OF SCOPE: MCP tools/list generation from the registry — deferred to the T-130 track.
Acceptance:
1. Dispatcher validates req.args against a registered per-command schema before the handler runs; violations return userError.
2. At least the security-relevant commands (git ref/remote/path args, panel.resize) carry schemas; argv-injection + caps still enforced (no regression vs T-104).
3. validateGitRef + git caps retained as defense-in-depth.
4. No third-party validation dep; no lint suppressions.
5. Tests cover: schema accept/reject per constraint kind, dispatcher-level rejection, and that an unschema-d command still dispatches.
Source: consultants.md "Security — Findings — [Major]" item 1. Decision: D-74.', NULL, '2026-05-20 15:54:35', '2026-05-20 15:54:35', '2026-05-20 15:54:35', NULL, '7f972739c82134897869432a3978d6ec', 1) ON CONFLICT(hash) DO NOTHING;
INSERT INTO ticket_history (ticket_id, field, old_value, new_value, changed_by, changed_at, created_at, updated_at, deleted_at, hash, canonical_version) VALUES ('T-120', 'status', 'backlog', 'in_progress', NULL, '2026-05-20 15:54:38', '2026-05-20 15:54:38', '2026-05-20 15:54:38', NULL, 'fa11190ac1bd9cd8f67e3041a8ca7236', 1) ON CONFLICT(hash) DO NOTHING;
+21
View File
@@ -2219,3 +2219,24 @@ INSERT INTO tickets (id, type, parent_id, title, description, status, priority,
Source: consultants.md "Architecture — Findings — [Critical] No IPC socket server exists".', 'done', 'high', NULL, NULL, NULL, '2026-05-17 18:47:18', '2026-05-19 13:14:41', NULL, '2ad1fbf0b1b6f5b9e46d4a31d1ad830c', 1) ON CONFLICT(id) DO UPDATE SET type=excluded.type, parent_id=excluded.parent_id, title=excluded.title, description=excluded.description, status=excluded.status, priority=excluded.priority, assigned_to=excluded.assigned_to, team=excluded.team, decision_ref=excluded.decision_ref, updated_at=excluded.updated_at, deleted_at=excluded.deleted_at, hash=excluded.hash, canonical_version=excluded.canonical_version WHERE excluded.updated_at > tickets.updated_at OR (excluded.updated_at = tickets.updated_at AND excluded.hash > tickets.hash);
INSERT INTO tickets (id, type, parent_id, title, description, status, priority, assigned_to, team, decision_ref, created_at, updated_at, deleted_at, hash, canonical_version) VALUES ('T-119', 'task', 'T-99', 'clide panel resize CLI verb (split from T-111)', 'Once T-99 lands an IPC dispatch path, register a ''panel.resize'' command that takes <slot> and <delta-or-absolute> args and calls LayoutArrangement.setSize / setEditorRatio. Keyboard parity already landed in T-111; this completes user/Claude parity per D-6.', 'in_progress', 'low', NULL, NULL, NULL, '2026-05-18 07:43:50', '2026-05-19 14:44:43', NULL, 'ac4c7a1d76836e546dac66e77ed4cb67', 1) ON CONFLICT(id) DO UPDATE SET type=excluded.type, parent_id=excluded.parent_id, title=excluded.title, description=excluded.description, status=excluded.status, priority=excluded.priority, assigned_to=excluded.assigned_to, team=excluded.team, decision_ref=excluded.decision_ref, updated_at=excluded.updated_at, deleted_at=excluded.deleted_at, hash=excluded.hash, canonical_version=excluded.canonical_version WHERE excluded.updated_at > tickets.updated_at OR (excluded.updated_at = tickets.updated_at AND excluded.hash > tickets.hash);
INSERT INTO tickets (id, type, parent_id, title, description, status, priority, assigned_to, team, decision_ref, created_at, updated_at, deleted_at, hash, canonical_version) VALUES ('T-119', 'task', 'T-99', 'clide panel resize CLI verb (split from T-111)', 'Once T-99 lands an IPC dispatch path, register a ''panel.resize'' command that takes <slot> and <delta-or-absolute> args and calls LayoutArrangement.setSize / setEditorRatio. Keyboard parity already landed in T-111; this completes user/Claude parity per D-6.', 'done', 'low', NULL, NULL, NULL, '2026-05-18 07:43:50', '2026-05-20 07:00:06', NULL, 'ba93872d695800697af1654a8bfd6e93', 1) ON CONFLICT(id) DO UPDATE SET type=excluded.type, parent_id=excluded.parent_id, title=excluded.title, description=excluded.description, status=excluded.status, priority=excluded.priority, assigned_to=excluded.assigned_to, team=excluded.team, decision_ref=excluded.decision_ref, updated_at=excluded.updated_at, deleted_at=excluded.deleted_at, hash=excluded.hash, canonical_version=excluded.canonical_version WHERE excluded.updated_at > tickets.updated_at OR (excluded.updated_at = tickets.updated_at AND excluded.hash > tickets.hash);
INSERT INTO tickets (id, type, parent_id, title, description, status, priority, assigned_to, team, decision_ref, created_at, updated_at, deleted_at, hash, canonical_version) VALUES ('T-120', 'task', 'T-97', 'typed IPC command schema framework (split from T-104)', 'T-104 covered the spot-fixes (argv-injection rejection, size/count caps on specific commands). What remains is the framework piece: a typed schema per IPC command — branch/remote/path/etc. with regex/charset constraints — applied at DaemonDispatcher dispatch time rather than scattered through individual handlers.
---
Design resolved 2026-05-20 (see D-74). Co-registration model, NOT a central map:
- The argv parser (lib/src/cli/argv_to_request.dart) only knows syntactic shape (identifier/flag charset, -- terminator); it has NO per-command argument knowledge. So this is build-fresh, not a lift — each handler currently hand-reads its own keys.
- Extend the DaemonDispatcher registration API to carry an optional typed schema per command. The dispatcher accumulates a cmd->schema registry as commands register (built-in register*Commands modules supply theirs; extension CommandContributions carry their own — central static map rejected because it cannot see extension-contributed commands, D-46).
- DaemonDispatcher.dispatch validates req.args against schema[cmd] BEFORE invoking the handler (hook at dispatcher.dart line 39, the `return h(req)` call). Violation -> userError (sysexit 64). Commands with no schema dispatch unvalidated (opt-in per command) until migrated.
- Constraint vocabulary is hand-rolled (prefer-zero-deps): per-arg required/optional, kind, charset/regex, numeric range. Collapses the _ResizeArgs-style hand-lifts (panel_commands.dart, T-119) into schema.
- KEEP existing T-104 checks as defense-in-depth: validateGitRef (lib/src/git/operations.dart:46) and the count/path caps (lib/src/daemon/git_commands.dart:18,23). The git client is callable directly from the Flutter UI, not only via the dispatcher — do not remove them.
- OUT OF SCOPE: MCP tools/list generation from the registry — deferred to the T-130 track.
Acceptance:
1. Dispatcher validates req.args against a registered per-command schema before the handler runs; violations return userError.
2. At least the security-relevant commands (git ref/remote/path args, panel.resize) carry schemas; argv-injection + caps still enforced (no regression vs T-104).
3. validateGitRef + git caps retained as defense-in-depth.
4. No third-party validation dep; no lint suppressions.
5. Tests cover: schema accept/reject per constraint kind, dispatcher-level rejection, and that an unschema-d command still dispatches.
Source: consultants.md "Security — Findings — [Major]" item 1. Decision: D-74.', 'in_progress', 'medium', NULL, NULL, NULL, '2026-05-18 07:53:08', '2026-05-20 15:54:38', NULL, '3c33fccd4b7442444ca598d430fab7f8', 1) ON CONFLICT(id) DO UPDATE SET type=excluded.type, parent_id=excluded.parent_id, title=excluded.title, description=excluded.description, status=excluded.status, priority=excluded.priority, assigned_to=excluded.assigned_to, team=excluded.team, decision_ref=excluded.decision_ref, updated_at=excluded.updated_at, deleted_at=excluded.deleted_at, hash=excluded.hash, canonical_version=excluded.canonical_version WHERE excluded.updated_at > tickets.updated_at OR (excluded.updated_at = tickets.updated_at AND excluded.hash > tickets.hash);
+4
View File
@@ -18,6 +18,10 @@ heading, and (b) bumping `pubspec.yaml` `version:` in the same commit.
### Added
- Typed IPC command-schema framework (T-119/T-120, D-74) — commands
register an argument schema beside their handler; the dispatcher
normalises argv into named args, coerces types, and validates
(charset, leading-dash, ranges, caps) before the handler runs.
- `clide panel resize <slot>` CLI verb (T-119) — set an absolute size
with `--to` or nudge with `--by`; `editor` targets the split ratio.
Completes user/Claude parity (D-6) with T-111's keyboard resize.
+1
View File
@@ -115,6 +115,7 @@ You might also want, project-permitting:
- [D-71: IPC socket access gated by chmod 0600 on socket + parent](decisions/architecture.md#d-71-ipc-socket-access-gated-by-chmod-0600-on-socket--parent) — _architecture_
- [D-72: IPC server is multi-connection with serial dispatch on the main isolate](decisions/architecture.md#d-72-ipc-server-is-multi-connection-with-serial-dispatch-on-the-main-isolate) — _architecture_
- [D-73: MCP transport for /ide is SSE over HTTP](decisions/architecture.md#d-73-mcp-transport-for-ide-is-sse-over-http) — _architecture_
- [D-74: IPC command schema is co-registered with the handler, validated at dispatch](decisions/architecture.md#d-74-ipc-command-schema-is-co-registered-with-the-handler-validated-at-dispatch) — _architecture_
## Open questions
+8
View File
@@ -289,4 +289,12 @@ Core, rendering, IPC, kernel, panel manager.
- **Cross-reference:** [D-68](#d-68-dual-integration-surface--bash-cli-primary-mcp-secondary), [D-72](#d-72-ipc-server-is-multi-connection-with-serial-dispatch-on-the-main-isolate), `lib/src/ipc/mcp_server.dart` (this transport's implementation lands in T-130).
- **Raised by:** 2026-05-19 — T-130 design pass; user picked SSE over HTTP after weighing against WebSocket and stdio.
### D-74: IPC command schema is co-registered with the handler, validated at dispatch
- **Date:** 2026-05-20
- **Decision:** Each IPC command may declare a **typed argument schema** (per-arg charset/regex/range constraints, required/optional, kind). The schema is **registered alongside the handler**, not authored in a central file: the `DaemonDispatcher` registration API carries an optional schema per command, and the dispatcher accumulates a `cmd → schema` registry as commands register. `DaemonDispatcher.dispatch` validates `req.args` against the command's schema **before** invoking the handler (`lib/src/daemon/dispatcher.dart`), returning a `userError` (sysexit 64) on violation so no handler sees malformed input. Built-in command modules (`registerPaneCommands`, `registerGitCommands`, …) supply their schemas at registration; extension-contributed commands ([`CommandContribution`](../../lib/extension/src/contribution.dart), Tier 6 / [D-46](tooling.md)) carry their own. The pre-existing T-104 spot-checks — `validateGitRef` in `lib/src/git/operations.dart` and the count/path caps in `lib/src/daemon/git_commands.dart` — stay in place as **defense-in-depth** below the dispatcher, because the git client is also callable directly from the Flutter UI (not only through the dispatcher). MCP `tools/list` generation from this registry is **out of scope** here — deferred to the T-130 track.
- **Rationale:** clide's command surface is open, not fixed: every `register*Commands()` module already contributes a *set* of commands, and the extension framework lets plugins contribute more at runtime. A central static schema map (`command_schema.dart` keyed by every known cmd) cannot see extension-contributed commands and would fight the plugin model — it was considered and rejected for exactly that reason. Co-registration keeps the schema next to the code that owns the command's meaning, supports any number of independent registrants (the normal case, not an edge case), and still yields a single validation lookup at dispatch time. Validating at the dispatcher (rather than per-handler) is what makes the constraint a contract instead of a convention: a new command can't forget to validate, and the `_ResizeArgs`-style hand-lifts scattered through handlers (see `panel_commands.dart`, T-119) collapse into the schema. No third-party validation library — the constraint vocabulary is hand-rolled per the prefer-zero-deps guardrail.
- **Cost:** A schema must be authored for each command (build-fresh — the argv parser at `lib/src/cli/argv_to_request.dart` only knows syntactic shape, never per-command argument names, so there is nothing to "lift"). Keeping `validateGitRef` + caps as well as the schema is deliberate redundancy on the git path; the alternative (single gate at the dispatcher) would leave the UI→client call path unvalidated. Until every command has a schema, validation is opt-in per command — commands with no registered schema dispatch unvalidated, same as today.
- **Cross-reference:** [D-6](#d-6-cli-and-event-surface-contract) (CLI/Claude parity the schema enforces), [D-68](#d-68-dual-integration-surface--bash-cli-primary-mcp-secondary) / [D-72](#d-72-ipc-server-is-multi-connection-with-serial-dispatch-on-the-main-isolate) (the dispatch path being gated), [D-46](tooling.md) (extension model the central-map alternative would have broken), `lib/src/daemon/dispatcher.dart` (the validation hook), `lib/src/git/operations.dart` + `lib/src/daemon/git_commands.dart` (the T-104 checks kept as defense-in-depth).
- **Raised by:** 2026-05-20 — T-120 design pass; user rejected the central registry as misaligned with the extensions/plugins model and confirmed co-registration with multiple command-set registrants.
---
+22 -2
View File
@@ -1,4 +1,5 @@
import 'package:clide/clide.dart' show clideVersion;
import 'package:clide/src/ipc/command_schema.dart';
import 'package:clide/src/ipc/envelope.dart';
import 'package:clide/src/ipc/schema_v1.dart';
@@ -12,13 +13,26 @@ class DaemonDispatcher {
final Map<String, CommandHandler> _handlers = {};
void register(String cmd, CommandHandler handler) {
/// Per-command argument schemas (T-120 / D-74). Populated alongside
/// handlers by registrants. A command with no entry dispatches
/// unvalidated — schema adoption is opt-in per command.
final Map<String, CommandSchema> _schemas = {};
/// Register [handler] for [cmd]. Pass [schema] to have the dispatcher
/// normalise + validate `req.args` before the handler runs (D-74).
void register(String cmd, CommandHandler handler, {CommandSchema? schema}) {
_handlers[cmd] = handler;
if (schema != null) {
_schemas[cmd] = schema;
} else {
_schemas.remove(cmd);
}
}
/// Remove all registered handlers except ping/version.
void clear() {
_handlers.removeWhere((k, _) => k != 'ping' && k != 'version');
_schemas.removeWhere((k, _) => k != 'ping' && k != 'version');
}
bool get isEmpty => _handlers.length <= 2; // only ping + version
@@ -36,7 +50,13 @@ class DaemonDispatcher {
),
);
}
return h(req);
final schema = _schemas[req.cmd];
if (schema == null) return h(req);
final result = schema.validate(schema.normalize(req.args));
if (!result.isOk) {
return schemaError(req.id, result.error!);
}
return h(IpcRequest(id: req.id, cmd: req.cmd, args: result.values!));
}
Future<IpcResponse> _ping(IpcRequest req) async => IpcResponse.ok(
+27 -2
View File
@@ -7,6 +7,7 @@ library;
import '../git/client.dart';
import '../git/operations.dart' show GitException;
import '../ipc/command_schema.dart';
import '../ipc/envelope.dart';
import '../ipc/schema_v1.dart';
import '../panes/event_sink.dart';
@@ -22,6 +23,30 @@ const int _gitLogMaxCount = 1000;
/// arguments.
const int _gitPathsMaxCount = 256;
/// Schema for `git.checkout` (D-74). `positional[0]` → `branch`, so
/// `clide git checkout <branch>` from the C client now reaches the
/// handler; the leading-dash guard stops argv injection at the
/// dispatcher (mirrors [validateGitRef], kept below as
/// defense-in-depth since the git client is also UI-reachable).
const CommandSchema _checkoutSchema = CommandSchema(
positional: ['branch'],
args: {
'branch': ArgSpec(required: true, rejectLeadingDash: true),
},
);
/// Schema for `git.push` (D-74). `clide git push <remote> <branch>`.
/// Both refs optional (bare `git.push` is valid); leading-dash
/// rejected on each.
const CommandSchema _pushSchema = CommandSchema(
positional: ['remote', 'branch'],
args: {
'remote': ArgSpec(rejectLeadingDash: true),
'branch': ArgSpec(rejectLeadingDash: true),
'setUpstream': ArgSpec(type: ArgType.boolean),
},
);
void registerGitCommands(
DaemonDispatcher d,
GitClient git,
@@ -245,7 +270,7 @@ void registerGitCommands(
} on GitException catch (e) {
return _gitError(req.id, e);
}
});
}, schema: _pushSchema);
d.register('git.branches', (req) async {
try {
@@ -279,7 +304,7 @@ void registerGitCommands(
} on GitException catch (e) {
return _gitError(req.id, e);
}
});
}, schema: _checkoutSchema);
}
List<String> _pathList(Object? raw) {
+26 -66
View File
@@ -13,6 +13,7 @@
/// `lib/src/daemon/panel_resizer_kernel.dart`.
library;
import '../ipc/command_schema.dart';
import '../ipc/envelope.dart';
import '../ipc/schema_v1.dart';
import 'dispatcher.dart';
@@ -47,29 +48,40 @@ abstract class PanelResizer {
/// [PanelResizer.bumpEditorRatio] instead of [PanelResizer.setSlotSize].
const String editorSplitSlot = 'editor';
/// Schema for `panel.resize` (D-74). The dispatcher normalises the
/// argv shape (`positional[0]` → `slot`, `--to/--by` flags) and
/// coerces `to`/`by` to numbers before the handler runs. The
/// "exactly one of to/by" rule is cross-argument semantics, so it
/// stays in the handler.
const CommandSchema _resizeSchema = CommandSchema(
positional: ['slot'],
args: {
'slot': ArgSpec(required: true),
'to': ArgSpec(type: ArgType.number),
'by': ArgSpec(type: ArgType.number),
},
);
void registerPanelCommands(DaemonDispatcher d, PanelResizer resizer) {
d.register('panel.resize', (req) => _resize(req, resizer));
d.register('panel.resize', (req) => _resize(req, resizer), schema: _resizeSchema);
}
Future<IpcResponse> _resize(IpcRequest req, PanelResizer r) async {
final view = _ResizeArgs.from(req.args);
if (view.slot == null || view.slot!.isEmpty) {
return _userErr(req.id, 'slot is required (e.g. "sidebar", "context", "$editorSplitSlot")');
}
if (!view.hasTo && !view.hasBy) {
// Args are schema-normalised + coerced by the dispatcher: `slot` is a
// non-empty string, `to`/`by` are num? when present.
final slot = req.args['slot'] as String;
final hasTo = req.args['to'] != null;
final hasBy = req.args['by'] != null;
if (!hasTo && !hasBy) {
return _userErr(req.id, 'one of `to` (absolute) or `by` (delta) is required');
}
if (view.hasTo && view.hasBy) {
if (hasTo && hasBy) {
return _userErr(req.id, 'pass only one of `to` and `by`');
}
final value = view.value;
if (value == null) {
return _userErr(req.id, '${view.hasTo ? "to" : "by"} must be numeric');
}
final slot = view.slot!;
final value = ((hasTo ? req.args['to'] : req.args['by']) as num).toDouble();
if (slot == editorSplitSlot) {
if (view.hasTo) {
if (hasTo) {
r.setEditorRatio(value);
} else {
r.bumpEditorRatio(value);
@@ -80,7 +92,7 @@ Future<IpcResponse> _resize(IpcRequest req, PanelResizer r) async {
});
}
final ok = view.hasTo ? r.setSlotSize(slot, value) : r.bumpSlotSize(slot, value);
final ok = hasTo ? r.setSlotSize(slot, value) : r.bumpSlotSize(slot, value);
if (!ok) {
return _notFound(req.id, 'no such slot: $slot');
}
@@ -90,58 +102,6 @@ Future<IpcResponse> _resize(IpcRequest req, PanelResizer r) async {
});
}
/// Tiny adapter that lifts `panel.resize` arguments out of either
/// the direct call shape (`{slot: ..., to: ...}`) or the argv-
/// translator shape (`{positional: [slot], flags: {to: '...'}}`).
/// Until T-120 formalises a shared schema, individual commands carry
/// the lift themselves.
class _ResizeArgs {
_ResizeArgs._({
required this.slot,
required this.hasTo,
required this.hasBy,
required this.value,
});
final String? slot;
final bool hasTo;
final bool hasBy;
final double? value;
factory _ResizeArgs.from(Map<String, Object?> args) {
String? slot;
final rawSlot = args['slot'];
if (rawSlot is String) slot = rawSlot;
final positional = args['positional'];
if (slot == null && positional is List && positional.isNotEmpty) {
slot = positional.first.toString();
}
final flags = args['flags'];
final flagsMap = flags is Map ? flags : const <Object?, Object?>{};
final hasTo = args.containsKey('to') || flagsMap.containsKey('to');
final hasBy = args.containsKey('by') || flagsMap.containsKey('by');
final raw = args.containsKey('to')
? args['to']
: args.containsKey('by')
? args['by']
: flagsMap.containsKey('to')
? flagsMap['to']
: flagsMap['by'];
return _ResizeArgs._(
slot: slot,
hasTo: hasTo,
hasBy: hasBy,
value: _coerceNum(raw),
);
}
static double? _coerceNum(Object? v) {
if (v is num) return v.toDouble();
if (v is String) return double.tryParse(v);
return null;
}
}
IpcResponse _userErr(String id, String message, {String? hint}) => IpcResponse.err(
id: id,
error: IpcError(
+220
View File
@@ -0,0 +1,220 @@
/// Typed argument schema for IPC commands (T-120, per D-74).
///
/// A [CommandSchema] declares the arguments a command accepts — their
/// types, whether they're required, and per-argument constraints
/// (charset/pattern, leading-dash rejection, numeric range, list
/// caps). Schemas are registered alongside their handlers on the
/// `DaemonDispatcher`; the dispatcher normalises + validates
/// `req.args` against the registered schema *before* invoking the
/// handler, so a command can never see malformed input and no handler
/// has to hand-roll its own argument checks.
///
/// Two call shapes reach a command (see T-119): the direct shape
/// (`{branch: "main"}`, from the in-process `DaemonClient` / UI) and
/// the argv-translator shape (`{positional: [...], flags: {...}}`,
/// from the C `clide` client). [CommandSchema.normalize] folds the
/// argv shape into named arguments using the schema's positional
/// ordering, so handlers only ever read flat named keys.
///
/// Flutter-free by construction — lives under `lib/src/ipc/` and
/// imports nothing from the kernel. The constraint vocabulary is
/// hand-rolled per the prefer-zero-deps guardrail.
library;
import 'envelope.dart';
import 'schema_v1.dart';
/// Coarse type of an argument value after coercion.
enum ArgType { string, number, boolean, stringList }
/// Constraints on a single argument.
class ArgSpec {
const ArgSpec({
this.type = ArgType.string,
this.required = false,
this.pattern,
this.rejectLeadingDash = false,
this.min,
this.max,
this.maxItems,
this.allowed,
});
final ArgType type;
final bool required;
/// String only — the value must fully match this pattern.
final RegExp? pattern;
/// String / stringList — reject any value (or element) starting with
/// `-`. This is the argv-injection guard T-104 introduced for git
/// refs; the schema makes it declarative.
final bool rejectLeadingDash;
/// Number only — inclusive bounds.
final num? min;
final num? max;
/// stringList only — maximum element count.
final int? maxItems;
/// String only — closed set of accepted values.
final Set<String>? allowed;
/// Coerce [raw] to this spec's [type]. Returns the typed value, or a
/// [_CoerceError] when the raw value can't be represented as the
/// declared type. Flag values arrive as strings from the argv
/// translator, so numeric/boolean args parse from text here.
Object? _coerce(Object? raw, void Function(String) fail) {
switch (type) {
case ArgType.string:
if (raw is String) return raw;
fail('expected a string');
return null;
case ArgType.number:
if (raw is num) return raw;
if (raw is String) {
final n = num.tryParse(raw);
if (n != null) return n;
}
fail('expected a number');
return null;
case ArgType.boolean:
if (raw is bool) return raw;
if (raw == 'true') return true;
if (raw == 'false') return false;
fail('expected a boolean');
return null;
case ArgType.stringList:
if (raw is List) {
return raw.map((e) => '$e').toList();
}
if (raw is String) return [raw];
fail('expected a list');
return null;
}
}
/// Apply value constraints to an already-coerced [value]. Returns
/// null when valid, else a human-readable reason.
String? _check(Object? value) {
switch (type) {
case ArgType.string:
final s = value as String;
if (rejectLeadingDash && s.startsWith('-')) {
return 'must not start with "-"';
}
if (allowed != null && !allowed!.contains(s)) {
return 'must be one of ${allowed!.join(", ")}';
}
if (pattern != null && !pattern!.hasMatch(s)) {
return 'does not match ${pattern!.pattern}';
}
return null;
case ArgType.number:
final n = value as num;
if (min != null && n < min!) return 'must be >= $min';
if (max != null && n > max!) return 'must be <= $max';
return null;
case ArgType.boolean:
return null;
case ArgType.stringList:
final list = (value as List).cast<String>();
if (maxItems != null && list.length > maxItems!) {
return 'has ${list.length} items; cap is $maxItems';
}
if (rejectLeadingDash) {
for (final e in list) {
if (e.startsWith('-')) return 'element "$e" must not start with "-"';
}
}
return null;
}
}
}
/// The argument contract for one command.
class CommandSchema {
const CommandSchema({this.positional = const [], this.args = const {}});
/// Names for positional argv tokens, in order. `positional[i]` in the
/// argv-translator shape maps to the argument named `positional[i]`.
final List<String> positional;
/// Argument name → spec. Includes the positional names.
final Map<String, ArgSpec> args;
/// Reserved keys the argv translator emits — never argument names.
static const _argvKeys = {'positional', 'flags', 'passthrough'};
/// Fold the argv-translator shape (`{positional, flags}`) into flat
/// named arguments using [positional] ordering. The direct call
/// shape (already flat named keys) is returned unchanged.
Map<String, Object?> normalize(Map<String, Object?> raw) {
final looksLikeArgv = raw.keys.any(_argvKeys.contains);
if (!looksLikeArgv) return raw;
final out = <String, Object?>{};
final pos = raw['positional'];
if (pos is List) {
for (var i = 0; i < pos.length && i < positional.length; i++) {
out[positional[i]] = pos[i];
}
}
final flags = raw['flags'];
if (flags is Map) {
for (final e in flags.entries) {
out['${e.key}'] = e.value;
}
}
if (raw.containsKey('passthrough')) out['passthrough'] = raw['passthrough'];
return out;
}
/// Validate [normalized] (post-[normalize]) against every declared
/// arg. Returns a [SchemaResult] carrying either the coerced argument
/// map (declared args replaced with their typed values; undeclared
/// keys preserved untouched) or the first violation message.
SchemaResult validate(Map<String, Object?> normalized) {
final out = Map<String, Object?>.from(normalized);
for (final entry in args.entries) {
final name = entry.key;
final spec = entry.value;
final present = normalized.containsKey(name) && normalized[name] != null;
if (!present) {
if (spec.required) return SchemaResult.err('$name is required');
continue;
}
String? coerceFailure;
final coerced = spec._coerce(normalized[name], (m) => coerceFailure = m);
if (coerceFailure != null) return SchemaResult.err('$name: $coerceFailure');
final reason = spec._check(coerced);
if (reason != null) return SchemaResult.err('$name $reason');
out[name] = coerced;
}
return SchemaResult.ok(out);
}
}
/// Outcome of [CommandSchema.validate].
class SchemaResult {
const SchemaResult.ok(this.values) : error = null;
const SchemaResult.err(this.error) : values = null;
/// Coerced argument map on success; null on failure.
final Map<String, Object?>? values;
/// Violation message on failure; null on success.
final String? error;
bool get isOk => error == null;
}
/// Build the standard `userError` response for a schema violation.
IpcResponse schemaError(String id, String message) => IpcResponse.err(
id: id,
error: IpcError(
code: IpcExitCode.userError,
kind: IpcErrorKind.userError,
message: message,
),
);
+11
View File
@@ -252,6 +252,17 @@ void main() {
expect(r.data['branch'], 'next');
});
test('git.checkout via argv positional reaches the handler (D-74)', () async {
// `clide git checkout next` → {positional: ['next']}; the schema's
// positional ordering maps it to `branch` at the dispatcher.
await Process.run('git', ['branch', 'next'], workingDirectory: sandbox.path);
final r = await call('git.checkout', {
'positional': ['next'],
});
expect(r.ok, isTrue, reason: r.error?.message);
expect(r.data['branch'], 'next');
});
test('git.checkout to an unknown branch surfaces a tool error', () async {
final r = await call('git.checkout', {'branch': 'no-such-branch'});
expect(r.ok, isFalse);
+1 -1
View File
@@ -55,7 +55,7 @@ void main() {
final r = await call(const {'slot': 'sidebar', 'to': 'lots'});
expect(r.ok, isFalse);
expect(r.error!.kind, 'user_error');
expect(r.error!.message, contains('numeric'));
expect(r.error!.message, contains('number'));
});
test('rejects an unknown slot with not-found', () async {
+193
View File
@@ -0,0 +1,193 @@
/// Tests for the typed command-schema framework (T-120 / D-74):
/// argument coercion, per-constraint validation, the argv-shape
/// normaliser, and the dispatcher-level validation hook.
library;
import 'package:clide/src/daemon/dispatcher.dart';
import 'package:clide/src/ipc/command_schema.dart';
import 'package:clide/src/ipc/envelope.dart';
import 'package:clide/src/ipc/schema_v1.dart';
import 'package:test/test.dart';
void main() {
group('ArgSpec coercion + constraints', () {
SchemaResult run(ArgSpec spec, Object? value, {bool required = false}) {
final schema = CommandSchema(args: {'x': spec});
return schema.validate({'x': value});
}
test('string passes through; non-string rejected', () {
expect(run(const ArgSpec(), 'hi').isOk, isTrue);
final bad = run(const ArgSpec(), 42);
expect(bad.isOk, isFalse);
expect(bad.error, contains('expected a string'));
});
test('number coerces from a numeric string', () {
final r = run(const ArgSpec(type: ArgType.number), '3.5');
expect(r.isOk, isTrue);
expect(r.values!['x'], 3.5);
});
test('number rejects non-numeric text', () {
final r = run(const ArgSpec(type: ArgType.number), 'abc');
expect(r.isOk, isFalse);
expect(r.error, contains('expected a number'));
});
test('number honours min/max bounds', () {
expect(run(const ArgSpec(type: ArgType.number, min: 0, max: 1), 0.5).isOk, isTrue);
expect(run(const ArgSpec(type: ArgType.number, min: 0), -1).error, contains('>= 0'));
expect(run(const ArgSpec(type: ArgType.number, max: 1), 2).error, contains('<= 1'));
});
test('boolean coerces from "true"/"false" strings', () {
expect(run(const ArgSpec(type: ArgType.boolean), 'true').values!['x'], true);
expect(run(const ArgSpec(type: ArgType.boolean), 'false').values!['x'], false);
expect(run(const ArgSpec(type: ArgType.boolean), 'maybe').isOk, isFalse);
});
test('rejectLeadingDash blocks an argv-injection value', () {
final r = run(const ArgSpec(rejectLeadingDash: true), '--upload-pack=evil');
expect(r.isOk, isFalse);
expect(r.error, contains('must not start with "-"'));
});
test('allowed enforces a closed set', () {
final spec = ArgSpec(allowed: {'a', 'b'});
expect(run(spec, 'a').isOk, isTrue);
expect(run(spec, 'z').error, contains('one of'));
});
test('pattern must fully match', () {
final spec = ArgSpec(pattern: RegExp(r'^[0-9]+$'));
expect(run(spec, '123').isOk, isTrue);
expect(run(spec, '12a').error, contains('does not match'));
});
test('stringList coerces a scalar + caps element count', () {
final r = run(const ArgSpec(type: ArgType.stringList), 'solo');
expect(r.values!['x'], ['solo']);
final capped = run(const ArgSpec(type: ArgType.stringList, maxItems: 2), ['a', 'b', 'c']);
expect(capped.error, contains('cap is 2'));
});
test('stringList rejectLeadingDash inspects every element', () {
final r = run(const ArgSpec(type: ArgType.stringList, rejectLeadingDash: true), ['ok', '-bad']);
expect(r.isOk, isFalse);
expect(r.error, contains('-bad'));
});
test('stringList rejects a value that is neither list nor string', () {
final r = run(const ArgSpec(type: ArgType.stringList), 42);
expect(r.isOk, isFalse);
expect(r.error, contains('expected a list'));
});
});
group('required + unknown handling', () {
test('missing required arg fails', () {
final s = CommandSchema(args: {'name': const ArgSpec(required: true)});
final r = s.validate(const {});
expect(r.isOk, isFalse);
expect(r.error, contains('name is required'));
});
test('missing optional arg is fine', () {
final s = CommandSchema(args: {'name': const ArgSpec()});
expect(s.validate(const {}).isOk, isTrue);
});
test('undeclared keys are preserved untouched', () {
final s = CommandSchema(args: {'a': const ArgSpec()});
final r = s.validate(const {'a': 'x', 'extra': 99});
expect(r.isOk, isTrue);
expect(r.values!['extra'], 99);
});
});
group('normalize (argv shape → named args)', () {
const schema = CommandSchema(
positional: ['slot'],
args: {'slot': ArgSpec(), 'to': ArgSpec(type: ArgType.number)},
);
test('positional[i] maps to the i-th declared name', () {
final out = schema.normalize(const {
'positional': ['sidebar'],
'flags': {'to': '300'},
});
expect(out['slot'], 'sidebar');
expect(out['to'], '300');
});
test('passthrough is carried over', () {
final out = schema.normalize(const {
'positional': ['x'],
'passthrough': ['--', 'raw'],
});
expect(out['passthrough'], ['--', 'raw']);
});
test('direct (already-named) shape is returned unchanged', () {
final input = {'slot': 'context', 'to': 240};
expect(identical(schema.normalize(input), input), isTrue);
});
test('extra positionals beyond the declared names are dropped', () {
final out = schema.normalize(const {
'positional': ['a', 'b', 'c'],
});
expect(out['slot'], 'a');
expect(out.containsKey('b'), isFalse);
});
});
group('DaemonDispatcher schema gate', () {
test('validates + coerces before the handler runs', () async {
final d = DaemonDispatcher();
Object? seen;
d.register('demo.cmd', (req) async {
seen = req.args['n'];
return IpcResponse.ok(id: req.id, data: const {});
}, schema: const CommandSchema(args: {'n': ArgSpec(type: ArgType.number)}));
final r = await d.dispatch(IpcRequest(id: '1', cmd: 'demo.cmd', args: const {'n': '7'}));
expect(r.ok, isTrue);
expect(seen, 7); // coerced from the string "7"
});
test('rejects a violation with userError before the handler runs', () async {
final d = DaemonDispatcher();
var handlerRan = false;
d.register('demo.cmd', (req) async {
handlerRan = true;
return IpcResponse.ok(id: req.id, data: const {});
}, schema: const CommandSchema(args: {'ref': ArgSpec(rejectLeadingDash: true, required: true)}));
final r = await d.dispatch(IpcRequest(id: '1', cmd: 'demo.cmd', args: const {'ref': '-rf'}));
expect(r.ok, isFalse);
expect(r.error!.kind, IpcErrorKind.userError);
expect(handlerRan, isFalse);
});
test('a command with no schema dispatches unvalidated', () async {
final d = DaemonDispatcher();
d.register('demo.bare', (req) async {
return IpcResponse.ok(id: req.id, data: {'echo': req.args['anything']});
});
final r = await d.dispatch(IpcRequest(id: '1', cmd: 'demo.bare', args: const {'anything': '-not-checked'}));
expect(r.ok, isTrue);
expect(r.data['echo'], '-not-checked');
});
test('re-registering a command without a schema clears its old schema', () async {
final d = DaemonDispatcher();
handler(IpcRequest req) async => IpcResponse.ok(id: req.id, data: const {});
d.register('demo.cmd', handler, schema: const CommandSchema(args: {'r': ArgSpec(required: true)}));
d.register('demo.cmd', handler); // no schema this time
final r = await d.dispatch(IpcRequest(id: '1', cmd: 'demo.cmd', args: const {}));
expect(r.ok, isTrue); // required check no longer applies
});
});
}