Step 1.2 feat: add protobuf v1 event envelope and payload schema. Also format and linter checked

This commit is contained in:
Ilgiz Kalmetyev 2026-04-15 10:01:49 +05:00
parent 845f08bc58
commit 0ddc7e8bc3
25 changed files with 200 additions and 76 deletions

View File

@ -2,16 +2,6 @@ syntax = "proto3";
package agent.proto.v1;
import "google/protobuf/struct.proto";
message StringList {
repeated string values = 1;
}
message AttributeMap {
map<string, string> labels = 1;
}
enum EventKind {
EVENT_KIND_UNSPECIFIED = 0;
EVENT_KIND_RAW = 1;
@ -38,38 +28,10 @@ enum Severity {
SEVERITY_CRITICAL = 6;
}
message EventFlags {
bool cache_enabled = 1;
bool outbox_enabled = 2;
uint32 priority = 3;
repeated string workflow_tags = 4;
message StringList {
repeated string values = 1;
}
message EventIdentity {
string id = 1;
string source = 2;
string type = 3;
string subject = 4;
}
message TraceContext {
string correlation_id = 1;
string causation_id = 2;
repeated string parent_event_ids = 3;
repeated string workflow_tags = 4;
}
message HostContext {
string host_id = 1;
string hostname = 2;
}
message NetworkContext {
string interface_name = 1;
string phy_name = 2;
string regulatory_domain = 3;
}
message AttributeDetails {
google.protobuf.Struct values = 1;
message AttributeMap {
map<string, string> labels = 1;
}

131
proto/events.proto Normal file
View File

@ -0,0 +1,131 @@
syntax = "proto3";
package agent.proto.v1;
import "google/protobuf/struct.proto";
import "google/protobuf/timestamp.proto";
import "proto/common.proto";
message TraceContext {
string correlation_id = 1;
string causation_id = 2;
repeated string parent_event_ids = 3;
repeated string workflow_tags = 4;
}
message HostContext {
string host_id = 1;
string hostname = 2;
}
message NetworkContext {
string interface_name = 1;
string phy_name = 2;
string regulatory_domain = 3;
}
message RoutingDirectives {
bool cache_enabled = 1;
bool outbox_enabled = 2;
uint32 priority = 3;
string partition_key = 4;
}
message EventEnvelope {
string id = 1;
string source = 2;
string type = 3;
string subject = 4;
google.protobuf.Timestamp time = 5;
string dataschema = 6;
string datacontenttype = 7;
string specversion = 8;
EventKind event_kind = 20;
SourceKind source_kind = 21;
Severity severity = 22;
uint32 schema_version = 23;
HostContext host = 30;
NetworkContext network = 31;
TraceContext trace = 32;
RoutingDirectives routing = 33;
AttributeMap attributes = 34;
string normalized_ssid = 40;
string normalized_bssid = 41;
uint32 normalized_freq_mhz = 42;
sint32 normalized_rssi_dbm = 43;
string normalized_event_code = 44;
string normalized_reason = 45;
oneof payload {
RawJournalPayload raw_journal = 100;
RawDbusPayload raw_dbus = 101;
RawWpaPayload raw_wpa = 102;
NavigationPayload navigation = 103;
DerivedEventPayload derived = 104;
CommandResultPayload command_result = 105;
}
}
message RawJournalPayload {
string cursor = 1;
string message = 2;
string unit = 3;
string comm = 4;
string exe = 5;
map<string, string> fields = 10;
}
message RawDbusPayload {
string bus_type = 1;
string bus_name = 2;
string object_path = 3;
string interface = 4;
string member = 5;
map<string, string> headers = 10;
repeated string args_json = 11;
}
message RawWpaPayload {
string interface_name = 1;
string event_line = 2;
string event_name = 3;
map<string, string> key_values = 10;
}
message NavigationPayload {
string robot_id = 1;
string mission_id = 2;
double x = 3;
double y = 4;
double z = 5;
double yaw = 6;
string frame_id = 7;
}
message DerivedEventPayload {
string derivation_name = 1;
string workflow_name = 2;
string summary = 3;
double confidence = 4;
google.protobuf.Struct details = 10;
}
message CommandResultPayload {
string command_id = 1;
string command_type = 2;
string origin_kind = 3;
string target_kind = 4;
string target_id = 5;
string result_state = 6;
string message = 7;
google.protobuf.Struct details = 10;
}
message BatchEnvelope {
string batch_id = 1;
google.protobuf.Timestamp created_at = 2;
repeated EventEnvelope events = 10;
}

View File

@ -1,2 +1 @@
"""wf-agent2 application package."""

View File

@ -1,2 +1 @@
"""In-memory cache core."""

View File

@ -25,8 +25,12 @@ def build_parser() -> argparse.ArgumentParser:
run_parser.set_defaults(handler=_handle_run)
config_parser = subparsers.add_parser("config", help="configuration operations")
config_subparsers = config_parser.add_subparsers(dest="config_command", required=True)
config_check_parser = config_subparsers.add_parser("check", help="validate configuration loading")
config_subparsers = config_parser.add_subparsers(
dest="config_command", required=True
)
config_check_parser = config_subparsers.add_parser(
"check", help="validate configuration loading"
)
config_check_parser.set_defaults(handler=_handle_config_check)
status_parser = subparsers.add_parser("status", help="show bootstrap status")
@ -49,8 +53,12 @@ def main(argv: Sequence[str] | None = None) -> int:
def _add_bootstrap_options(parser: argparse.ArgumentParser) -> None:
parser.add_argument("--config", dest="config_path", type=Path, help="TOML config file path")
parser.add_argument("--env-file", dest="env_file", type=Path, help="dotenv file path")
parser.add_argument(
"--config", dest="config_path", type=Path, help="TOML config file path"
)
parser.add_argument(
"--env-file", dest="env_file", type=Path, help="dotenv file path"
)
parser.add_argument(
"--no-env-file",
action="store_true",

View File

@ -1,2 +1 @@
"""Collector abstractions and implementations."""

View File

@ -1,2 +1 @@
"""Command models and coordination."""

View File

@ -1,2 +1 @@
"""Core primitives."""

View File

@ -1,2 +1 @@
"""Derivation workers and workflows."""

View File

@ -1,2 +1 @@
"""Event routing director."""

View File

@ -40,7 +40,9 @@ def load_dotenv(
dotenv_path = _resolve_dotenv_path(path)
if dotenv_path is None or not dotenv_path.exists():
return DotenvLoadResult(path=dotenv_path, exists=False, loaded_keys=(), skipped_keys=())
return DotenvLoadResult(
path=dotenv_path, exists=False, loaded_keys=(), skipped_keys=()
)
loaded: list[str] = []
skipped: list[str] = []

View File

@ -1,2 +1 @@
"""Command executors."""

View File

@ -1,2 +1 @@
"""Logging, metrics, and health reporting."""

View File

@ -1,2 +1 @@
"""Generated protobuf Python package."""

View File

@ -1,2 +1 @@
"""Scheduled task coordination."""

View File

@ -1,2 +1 @@
"""Outbox draining and transport sender logic."""

View File

@ -1,2 +1 @@
"""Outbound transport backends."""

View File

@ -15,7 +15,9 @@ except ModuleNotFoundError: # pragma: no cover - fallback for alternative runti
_ENV_PATTERN = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}")
def load_toml(path: str | Path, *, env: Mapping[str, str] | None = None) -> dict[str, Any]:
def load_toml(
path: str | Path, *, env: Mapping[str, str] | None = None
) -> dict[str, Any]:
"""Load TOML from *path* and expand ``${VAR}`` placeholders in strings."""
source = Path(path)
@ -40,7 +42,9 @@ def expand_env(value: Any, *, env: Mapping[str, str] | None = None) -> Any:
def _expand_value(value: Any, env: Mapping[str, str]) -> Any:
if isinstance(value, str):
return _ENV_PATTERN.sub(lambda match: env.get(match.group(1), match.group(0)), value)
return _ENV_PATTERN.sub(
lambda match: env.get(match.group(1), match.group(0)), value
)
if isinstance(value, list):
return [_expand_value(item, env) for item in value]
if isinstance(value, tuple):

View File

@ -7,7 +7,6 @@ from pathlib import Path
from agent.cli import main
ROOT = Path(__file__).resolve().parents[2]
TEMP_ROOT = ROOT / ".tmp-tests"
TEMP_ROOT.mkdir(exist_ok=True)
@ -33,7 +32,9 @@ def test_config_check_reports_success() -> None:
encoding="utf-8",
)
code, stdout, stderr = _run_cli(["--config", str(config_file), "--no-env-file", "config", "check"])
code, stdout, stderr = _run_cli(
["--config", str(config_file), "--no-env-file", "config", "check"]
)
assert code == 0
assert stderr == ""
@ -54,7 +55,9 @@ def test_status_reports_bootstrap_summary() -> None:
encoding="utf-8",
)
code, stdout, stderr = _run_cli(["--config", str(config_file), "--no-env-file", "status"])
code, stdout, stderr = _run_cli(
["--config", str(config_file), "--no-env-file", "status"]
)
assert code == 0
assert stderr == ""
@ -76,7 +79,9 @@ def test_stats_reports_zero_counters() -> None:
encoding="utf-8",
)
code, stdout, stderr = _run_cli(["--config", str(config_file), "--no-env-file", "stats"])
code, stdout, stderr = _run_cli(
["--config", str(config_file), "--no-env-file", "stats"]
)
assert code == 0
assert stderr == ""
@ -97,7 +102,9 @@ def test_run_reports_bootstrap_ok() -> None:
encoding="utf-8",
)
code, stdout, stderr = _run_cli(["--config", str(config_file), "--no-env-file", "run"])
code, stdout, stderr = _run_cli(
["--config", str(config_file), "--no-env-file", "run"]
)
assert code == 0
assert stderr == ""

View File

@ -7,12 +7,12 @@ def test_common_proto_contains_required_primitives() -> None:
proto_path = Path(__file__).resolve().parents[2] / "proto" / "common.proto"
content = proto_path.read_text(encoding="utf-8")
assert "syntax = \"proto3\";" in content
assert 'syntax = "proto3";' in content
assert "package agent.proto.v1;" in content
assert "message StringList" in content
assert "message AttributeMap" in content
assert "enum EventKind" in content
assert "enum SourceKind" in content
assert "enum Severity" in content
assert "message EventFlags" in content
assert "message EventIdentity" in content
assert "message EventFlags" not in content
assert "message EventIdentity" not in content

View File

@ -5,7 +5,6 @@ from pathlib import Path
from agent.env import load_dotenv
ROOT = Path(__file__).resolve().parents[2]
TEMP_ROOT = ROOT / ".tmp-tests"
TEMP_ROOT.mkdir(exist_ok=True)

View File

@ -0,0 +1,21 @@
from __future__ import annotations
from pathlib import Path
def test_events_proto_contains_required_messages() -> None:
proto_path = Path(__file__).resolve().parents[2] / "proto" / "events.proto"
content = proto_path.read_text(encoding="utf-8")
assert 'syntax = "proto3";' in content
assert "package agent.proto.v1;" in content
assert 'import "proto/common.proto";' in content
assert "message EventEnvelope" in content
assert "message RawJournalPayload" in content
assert "message RawDbusPayload" in content
assert "message RawWpaPayload" in content
assert "message NavigationPayload" in content
assert "message DerivedEventPayload" in content
assert "message CommandResultPayload" in content
assert "message BatchEnvelope" in content
assert "oneof payload" in content

View File

@ -19,5 +19,5 @@ def test_main_prints_scaffold_plan(capsys) -> None:
assert code == 0
assert "source_dir=proto" in output
assert "output_dir=src/agent/proto_generated" in output
assert "files=common.proto" in output
assert "files=common.proto,events.proto" in output
assert "mode=dry-run" in output

View File

@ -5,7 +5,6 @@ from pathlib import Path
from agent.settings import load_settings
ROOT = Path(__file__).resolve().parents[2]
TEMP_ROOT = ROOT / ".tmp-tests"
TEMP_ROOT.mkdir(exist_ok=True)

View File

@ -21,8 +21,12 @@ class ProtoGenerationPlan:
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description="Generate protobuf Python stubs")
parser.add_argument("--source-dir", type=Path, default=Path("proto"))
parser.add_argument("--output-dir", type=Path, default=Path("src/agent/proto_generated"))
parser.add_argument("--dry-run", action="store_true", help="print the planned generation only")
parser.add_argument(
"--output-dir", type=Path, default=Path("src/agent/proto_generated")
)
parser.add_argument(
"--dry-run", action="store_true", help="print the planned generation only"
)
return parser
@ -37,7 +41,7 @@ def main(argv: Sequence[str] | None = None) -> int:
print(f"source_dir={plan.source_dir.as_posix()}")
print(f"output_dir={plan.output_dir.as_posix()}")
print("files=common.proto")
print("files=common.proto,events.proto")
if args.dry_run:
print("mode=dry-run")
return 0