feed-the-machine 1.1.0 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/generate-manifest.mjs +253 -0
- package/bin/install.mjs +372 -26
- package/docs/INBOX.md +233 -0
- package/ftm/SKILL.md +34 -0
- package/ftm-audit/SKILL.md +69 -0
- package/ftm-brainstorm/SKILL.md +51 -0
- package/ftm-browse/SKILL.md +39 -0
- package/ftm-capture/SKILL.md +370 -0
- package/ftm-capture.yml +4 -0
- package/ftm-codex-gate/SKILL.md +59 -0
- package/ftm-config/SKILL.md +35 -0
- package/ftm-council/SKILL.md +56 -0
- package/ftm-dashboard/SKILL.md +34 -0
- package/ftm-debug/SKILL.md +84 -0
- package/ftm-diagram/SKILL.md +44 -0
- package/ftm-executor/SKILL.md +97 -0
- package/ftm-git/SKILL.md +60 -0
- package/ftm-inbox/backend/__init__.py +0 -0
- package/ftm-inbox/backend/adapters/__init__.py +0 -0
- package/ftm-inbox/backend/adapters/_retry.py +64 -0
- package/ftm-inbox/backend/adapters/base.py +230 -0
- package/ftm-inbox/backend/adapters/freshservice.py +104 -0
- package/ftm-inbox/backend/adapters/gmail.py +125 -0
- package/ftm-inbox/backend/adapters/jira.py +136 -0
- package/ftm-inbox/backend/adapters/registry.py +192 -0
- package/ftm-inbox/backend/adapters/slack.py +110 -0
- package/ftm-inbox/backend/db/__init__.py +0 -0
- package/ftm-inbox/backend/db/connection.py +54 -0
- package/ftm-inbox/backend/db/schema.py +78 -0
- package/ftm-inbox/backend/executor/__init__.py +7 -0
- package/ftm-inbox/backend/executor/engine.py +149 -0
- package/ftm-inbox/backend/executor/step_runner.py +98 -0
- package/ftm-inbox/backend/main.py +103 -0
- package/ftm-inbox/backend/models/__init__.py +1 -0
- package/ftm-inbox/backend/models/unified_task.py +36 -0
- package/ftm-inbox/backend/planner/__init__.py +6 -0
- package/ftm-inbox/backend/planner/generator.py +127 -0
- package/ftm-inbox/backend/planner/schema.py +34 -0
- package/ftm-inbox/backend/requirements.txt +5 -0
- package/ftm-inbox/backend/routes/__init__.py +0 -0
- package/ftm-inbox/backend/routes/execute.py +186 -0
- package/ftm-inbox/backend/routes/health.py +52 -0
- package/ftm-inbox/backend/routes/inbox.py +68 -0
- package/ftm-inbox/backend/routes/plan.py +271 -0
- package/ftm-inbox/bin/launchagent.mjs +91 -0
- package/ftm-inbox/bin/setup.mjs +188 -0
- package/ftm-inbox/bin/start.sh +10 -0
- package/ftm-inbox/bin/status.sh +17 -0
- package/ftm-inbox/bin/stop.sh +8 -0
- package/ftm-inbox/config.example.yml +55 -0
- package/ftm-inbox/package-lock.json +2898 -0
- package/ftm-inbox/package.json +26 -0
- package/ftm-inbox/postcss.config.js +6 -0
- package/ftm-inbox/src/app.css +199 -0
- package/ftm-inbox/src/app.html +18 -0
- package/ftm-inbox/src/lib/api.ts +166 -0
- package/ftm-inbox/src/lib/components/ExecutionLog.svelte +81 -0
- package/ftm-inbox/src/lib/components/InboxFeed.svelte +143 -0
- package/ftm-inbox/src/lib/components/PlanStep.svelte +271 -0
- package/ftm-inbox/src/lib/components/PlanView.svelte +206 -0
- package/ftm-inbox/src/lib/components/StreamPanel.svelte +99 -0
- package/ftm-inbox/src/lib/components/TaskCard.svelte +190 -0
- package/ftm-inbox/src/lib/components/ui/EmptyState.svelte +63 -0
- package/ftm-inbox/src/lib/components/ui/KawaiiCard.svelte +86 -0
- package/ftm-inbox/src/lib/components/ui/PillButton.svelte +106 -0
- package/ftm-inbox/src/lib/components/ui/StatusBadge.svelte +67 -0
- package/ftm-inbox/src/lib/components/ui/StreamDrawer.svelte +149 -0
- package/ftm-inbox/src/lib/components/ui/ThemeToggle.svelte +80 -0
- package/ftm-inbox/src/lib/theme.ts +47 -0
- package/ftm-inbox/src/routes/+layout.svelte +76 -0
- package/ftm-inbox/src/routes/+page.svelte +401 -0
- package/ftm-inbox/static/favicon.png +0 -0
- package/ftm-inbox/svelte.config.js +12 -0
- package/ftm-inbox/tailwind.config.ts +63 -0
- package/ftm-inbox/tsconfig.json +13 -0
- package/ftm-inbox/vite.config.ts +6 -0
- package/ftm-intent/SKILL.md +44 -0
- package/ftm-manifest.json +3794 -0
- package/ftm-map/SKILL.md +50 -0
- package/ftm-mind/SKILL.md +173 -66
- package/ftm-pause/SKILL.md +43 -0
- package/ftm-researcher/SKILL.md +55 -0
- package/ftm-resume/SKILL.md +47 -0
- package/ftm-retro/SKILL.md +54 -0
- package/ftm-routine/SKILL.md +36 -0
- package/ftm-state/blackboard/capabilities.json +5 -0
- package/ftm-state/blackboard/capabilities.schema.json +27 -0
- package/ftm-upgrade/SKILL.md +41 -0
- package/hooks/ftm-blackboard-enforcer.sh +28 -27
- package/hooks/ftm-plan-gate.sh +21 -25
- package/install.sh +238 -111
- package/package.json +6 -2
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
"""
|
|
2
|
+
AdapterRegistry — loads and manages poller adapters from config.yml.
|
|
3
|
+
|
|
4
|
+
Config format (see config.example.yml):
|
|
5
|
+
|
|
6
|
+
adapters:
|
|
7
|
+
- name: jira
|
|
8
|
+
class: ftm_inbox.adapters.jira.JiraAdapter
|
|
9
|
+
interval_seconds: 60
|
|
10
|
+
credentials:
|
|
11
|
+
api_token: "..."
|
|
12
|
+
email: "..."
|
|
13
|
+
config:
|
|
14
|
+
base_url: "https://myorg.atlassian.net"
|
|
15
|
+
project_key: "OPS"
|
|
16
|
+
|
|
17
|
+
The registry uses importlib to load adapter classes by dotted module path,
|
|
18
|
+
validates that each class is a subclass of BaseAdapter, and confirms that
|
|
19
|
+
credentials are present (non-empty) before registering the adapter.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
import importlib
|
|
23
|
+
import logging
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
from typing import Any
|
|
26
|
+
|
|
27
|
+
import yaml
|
|
28
|
+
|
|
29
|
+
from .base import BaseAdapter
|
|
30
|
+
|
|
31
|
+
logger = logging.getLogger(__name__)
|
|
32
|
+
|
|
33
|
+
_DEFAULT_CONFIG_PATH = (
|
|
34
|
+
Path(__file__).resolve().parent.parent.parent / "config.yml"
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class AdapterRegistryError(Exception):
|
|
39
|
+
"""Raised when an adapter cannot be loaded or validated."""
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class AdapterRegistry:
|
|
43
|
+
"""
|
|
44
|
+
Loads adapter definitions from config.yml and instantiates each one.
|
|
45
|
+
|
|
46
|
+
Usage:
|
|
47
|
+
registry = AdapterRegistry.from_config()
|
|
48
|
+
for adapter in registry.adapters:
|
|
49
|
+
adapter.run_cycle(conn)
|
|
50
|
+
"""
|
|
51
|
+
|
|
52
|
+
def __init__(self) -> None:
|
|
53
|
+
self._adapters: list[BaseAdapter] = []
|
|
54
|
+
|
|
55
|
+
@property
|
|
56
|
+
def adapters(self) -> list[BaseAdapter]:
|
|
57
|
+
return list(self._adapters)
|
|
58
|
+
|
|
59
|
+
@classmethod
|
|
60
|
+
def from_config(
|
|
61
|
+
cls, config_path: Path | None = None
|
|
62
|
+
) -> "AdapterRegistry":
|
|
63
|
+
"""
|
|
64
|
+
Build a registry from a YAML config file.
|
|
65
|
+
|
|
66
|
+
Args:
|
|
67
|
+
config_path: Path to config.yml. Defaults to <project_root>/config.yml.
|
|
68
|
+
|
|
69
|
+
Returns:
|
|
70
|
+
Populated AdapterRegistry.
|
|
71
|
+
|
|
72
|
+
Raises:
|
|
73
|
+
AdapterRegistryError: If the config file is missing or an adapter
|
|
74
|
+
fails validation.
|
|
75
|
+
"""
|
|
76
|
+
path = config_path or _DEFAULT_CONFIG_PATH
|
|
77
|
+
|
|
78
|
+
if not path.exists():
|
|
79
|
+
logger.warning(
|
|
80
|
+
"config.yml not found at %s — no adapters registered.", path
|
|
81
|
+
)
|
|
82
|
+
return cls()
|
|
83
|
+
|
|
84
|
+
with path.open() as fh:
|
|
85
|
+
raw = yaml.safe_load(fh) or {}
|
|
86
|
+
|
|
87
|
+
adapter_defs: list[dict[str, Any]] = raw.get("adapters", [])
|
|
88
|
+
registry = cls()
|
|
89
|
+
|
|
90
|
+
for definition in adapter_defs:
|
|
91
|
+
try:
|
|
92
|
+
adapter = _load_adapter(definition)
|
|
93
|
+
registry._adapters.append(adapter)
|
|
94
|
+
logger.info(
|
|
95
|
+
"Registered adapter '%s' (%s)",
|
|
96
|
+
definition.get("name"),
|
|
97
|
+
definition.get("class"),
|
|
98
|
+
)
|
|
99
|
+
except AdapterRegistryError as exc:
|
|
100
|
+
logger.error("Skipping adapter '%s': %s", definition.get("name"), exc)
|
|
101
|
+
|
|
102
|
+
return registry
|
|
103
|
+
|
|
104
|
+
def get(self, name: str) -> BaseAdapter | None:
|
|
105
|
+
"""Return a registered adapter by name, or None."""
|
|
106
|
+
for adapter in self._adapters:
|
|
107
|
+
if adapter.source_name == name:
|
|
108
|
+
return adapter
|
|
109
|
+
return None
|
|
110
|
+
|
|
111
|
+
def __len__(self) -> int:
|
|
112
|
+
return len(self._adapters)
|
|
113
|
+
|
|
114
|
+
def __repr__(self) -> str:
|
|
115
|
+
names = [a.source_name for a in self._adapters]
|
|
116
|
+
return f"AdapterRegistry(adapters={names})"
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _load_adapter(definition: dict[str, Any]) -> BaseAdapter:
|
|
120
|
+
"""
|
|
121
|
+
Instantiate a single adapter from its config definition.
|
|
122
|
+
|
|
123
|
+
Validates:
|
|
124
|
+
- 'class' key is present and is a valid dotted path
|
|
125
|
+
- The resolved class is a subclass of BaseAdapter
|
|
126
|
+
- Required credentials keys are present and non-empty
|
|
127
|
+
|
|
128
|
+
Raises:
|
|
129
|
+
AdapterRegistryError on any validation failure.
|
|
130
|
+
"""
|
|
131
|
+
dotted_path: str = definition.get("class", "")
|
|
132
|
+
if not dotted_path:
|
|
133
|
+
raise AdapterRegistryError("Missing 'class' key in adapter definition.")
|
|
134
|
+
|
|
135
|
+
module_path, _, class_name = dotted_path.rpartition(".")
|
|
136
|
+
if not module_path:
|
|
137
|
+
raise AdapterRegistryError(
|
|
138
|
+
f"'class' must be a dotted path (got '{dotted_path}')."
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
try:
|
|
142
|
+
module = importlib.import_module(module_path)
|
|
143
|
+
except ImportError as exc:
|
|
144
|
+
raise AdapterRegistryError(
|
|
145
|
+
f"Cannot import module '{module_path}': {exc}"
|
|
146
|
+
) from exc
|
|
147
|
+
|
|
148
|
+
klass = getattr(module, class_name, None)
|
|
149
|
+
if klass is None:
|
|
150
|
+
raise AdapterRegistryError(
|
|
151
|
+
f"Class '{class_name}' not found in module '{module_path}'."
|
|
152
|
+
)
|
|
153
|
+
|
|
154
|
+
if not (isinstance(klass, type) and issubclass(klass, BaseAdapter)):
|
|
155
|
+
raise AdapterRegistryError(
|
|
156
|
+
f"'{dotted_path}' is not a subclass of BaseAdapter."
|
|
157
|
+
)
|
|
158
|
+
|
|
159
|
+
credentials: dict[str, Any] = definition.get("credentials", {}) or {}
|
|
160
|
+
config: dict[str, Any] = definition.get("config", {}) or {}
|
|
161
|
+
|
|
162
|
+
_validate_credentials(definition.get("name", dotted_path), credentials, klass)
|
|
163
|
+
|
|
164
|
+
instance = klass(credentials=credentials, config=config)
|
|
165
|
+
# Allow the class to declare its source_name via class attribute;
|
|
166
|
+
# fall back to the 'name' key in the config definition.
|
|
167
|
+
if not instance.source_name:
|
|
168
|
+
instance.source_name = definition.get("name", class_name.lower())
|
|
169
|
+
|
|
170
|
+
return instance
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _validate_credentials(
|
|
174
|
+
adapter_name: str,
|
|
175
|
+
credentials: dict[str, Any],
|
|
176
|
+
klass: type,
|
|
177
|
+
) -> None:
|
|
178
|
+
"""
|
|
179
|
+
Check that all keys declared in klass.required_credentials are present
|
|
180
|
+
and non-empty in the credentials dict.
|
|
181
|
+
|
|
182
|
+
Adapters opt into this by setting a class-level list:
|
|
183
|
+
required_credentials = ["api_token", "email"]
|
|
184
|
+
|
|
185
|
+
If the class doesn't declare required_credentials, skip validation.
|
|
186
|
+
"""
|
|
187
|
+
required: list[str] = getattr(klass, "required_credentials", [])
|
|
188
|
+
missing = [key for key in required if not credentials.get(key)]
|
|
189
|
+
if missing:
|
|
190
|
+
raise AdapterRegistryError(
|
|
191
|
+
f"Adapter '{adapter_name}' missing required credentials: {missing}"
|
|
192
|
+
)
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""
|
|
2
|
+
SlackAdapter — polls Slack channels for recent messages.
|
|
3
|
+
|
|
4
|
+
Required credentials:
|
|
5
|
+
bot_token Slack bot token (xoxb-...)
|
|
6
|
+
|
|
7
|
+
Config keys:
|
|
8
|
+
channels List of channel IDs to poll
|
|
9
|
+
lookback_hours How far back to fetch messages, default 24
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import logging
|
|
15
|
+
import time
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
import requests
|
|
19
|
+
|
|
20
|
+
from backend.adapters._retry import retry
|
|
21
|
+
from backend.adapters.base import BaseAdapter, NormalizedItem
|
|
22
|
+
|
|
23
|
+
logger = logging.getLogger(__name__)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class SlackAdapter(BaseAdapter):
|
|
27
|
+
"""Polls Slack channels for recent messages."""
|
|
28
|
+
|
|
29
|
+
source_name = "slack"
|
|
30
|
+
required_credentials = ["bot_token"]
|
|
31
|
+
|
|
32
|
+
def __init__(self, credentials: dict, config: dict) -> None:
|
|
33
|
+
super().__init__(credentials, config)
|
|
34
|
+
self._token = credentials["bot_token"]
|
|
35
|
+
self._channels: list[str] = config.get("channels", [])
|
|
36
|
+
self._lookback_hours = int(config.get("lookback_hours", 24))
|
|
37
|
+
self._headers = {
|
|
38
|
+
"Authorization": f"Bearer {self._token}",
|
|
39
|
+
"Content-Type": "application/json",
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
@retry(max_attempts=3, base_delay=1.0, exceptions=(requests.RequestException,))
|
|
43
|
+
def poll(self) -> list[dict]:
|
|
44
|
+
"""Fetch recent messages from configured Slack channels."""
|
|
45
|
+
oldest = str(time.time() - self._lookback_hours * 3600)
|
|
46
|
+
all_messages: list[dict] = []
|
|
47
|
+
|
|
48
|
+
for channel_id in self._channels:
|
|
49
|
+
url = "https://slack.com/api/conversations.history"
|
|
50
|
+
params: dict[str, Any] = {
|
|
51
|
+
"channel": channel_id,
|
|
52
|
+
"oldest": oldest,
|
|
53
|
+
"limit": 200,
|
|
54
|
+
}
|
|
55
|
+
response = requests.get(
|
|
56
|
+
url, headers=self._headers, params=params, timeout=30
|
|
57
|
+
)
|
|
58
|
+
response.raise_for_status()
|
|
59
|
+
data = response.json()
|
|
60
|
+
|
|
61
|
+
if not data.get("ok"):
|
|
62
|
+
logger.warning(
|
|
63
|
+
"Slack API error for channel %s: %s",
|
|
64
|
+
channel_id,
|
|
65
|
+
data.get("error", "unknown"),
|
|
66
|
+
)
|
|
67
|
+
continue
|
|
68
|
+
|
|
69
|
+
messages = data.get("messages", [])
|
|
70
|
+
for msg in messages:
|
|
71
|
+
msg["_channel_id"] = channel_id
|
|
72
|
+
all_messages.extend(messages)
|
|
73
|
+
|
|
74
|
+
return all_messages
|
|
75
|
+
|
|
76
|
+
def normalize(self, raw_item: dict) -> NormalizedItem:
|
|
77
|
+
"""Map a Slack message dict to NormalizedItem."""
|
|
78
|
+
ts = raw_item.get("ts", "")
|
|
79
|
+
channel_id = raw_item.get("_channel_id", "")
|
|
80
|
+
text = raw_item.get("text") or ""
|
|
81
|
+
|
|
82
|
+
title = text[:100].replace("\n", " ") if text else "(no text)"
|
|
83
|
+
body = text
|
|
84
|
+
|
|
85
|
+
user = raw_item.get("user") or raw_item.get("bot_id") or "unknown"
|
|
86
|
+
|
|
87
|
+
created_at = ts
|
|
88
|
+
|
|
89
|
+
source_url = (
|
|
90
|
+
f"https://slack.com/archives/{channel_id}/p{ts.replace('.', '')}"
|
|
91
|
+
if channel_id and ts
|
|
92
|
+
else None
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
return NormalizedItem(
|
|
96
|
+
source=self.source_name,
|
|
97
|
+
source_id=f"{channel_id}:{ts}",
|
|
98
|
+
title=title,
|
|
99
|
+
body=body,
|
|
100
|
+
status="open",
|
|
101
|
+
priority="medium",
|
|
102
|
+
assignee=None,
|
|
103
|
+
requester=user,
|
|
104
|
+
created_at=created_at,
|
|
105
|
+
updated_at=None,
|
|
106
|
+
tags=[],
|
|
107
|
+
custom_fields={"channel_id": channel_id},
|
|
108
|
+
raw_payload=raw_item,
|
|
109
|
+
source_url=source_url,
|
|
110
|
+
)
|
|
File without changes
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""
|
|
2
|
+
SQLite connection helper for ftm-inbox.
|
|
3
|
+
|
|
4
|
+
Uses WAL journal mode for better read concurrency and sets a sensible
|
|
5
|
+
busy timeout so concurrent writer contention fails gracefully rather
|
|
6
|
+
than immediately.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import sqlite3
|
|
10
|
+
import threading
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
_local = threading.local()
|
|
14
|
+
|
|
15
|
+
DEFAULT_DB_PATH = Path(__file__).resolve().parent.parent.parent / "ftm-inbox.db"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def get_connection(db_path: Path | None = None) -> sqlite3.Connection:
|
|
19
|
+
"""
|
|
20
|
+
Return a thread-local SQLite connection.
|
|
21
|
+
|
|
22
|
+
The connection is configured with:
|
|
23
|
+
- WAL journal mode for concurrent reads during writes
|
|
24
|
+
- 5-second busy timeout to handle writer contention
|
|
25
|
+
- Row factory set to sqlite3.Row for dict-like access
|
|
26
|
+
- Foreign keys enabled
|
|
27
|
+
"""
|
|
28
|
+
path = db_path or DEFAULT_DB_PATH
|
|
29
|
+
|
|
30
|
+
if not hasattr(_local, "conn") or _local.conn is None:
|
|
31
|
+
_local.conn = _open_connection(path)
|
|
32
|
+
|
|
33
|
+
return _local.conn
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _open_connection(path: Path) -> sqlite3.Connection:
|
|
37
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
38
|
+
conn = sqlite3.connect(str(path), check_same_thread=False)
|
|
39
|
+
conn.row_factory = sqlite3.Row
|
|
40
|
+
|
|
41
|
+
conn.execute("PRAGMA journal_mode=WAL")
|
|
42
|
+
conn.execute("PRAGMA busy_timeout=5000")
|
|
43
|
+
conn.execute("PRAGMA foreign_keys=ON")
|
|
44
|
+
conn.execute("PRAGMA synchronous=NORMAL")
|
|
45
|
+
conn.commit()
|
|
46
|
+
|
|
47
|
+
return conn
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def close_connection() -> None:
|
|
51
|
+
"""Close the thread-local connection if open."""
|
|
52
|
+
if hasattr(_local, "conn") and _local.conn is not None:
|
|
53
|
+
_local.conn.close()
|
|
54
|
+
_local.conn = None
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""
|
|
2
|
+
SQLite schema definitions for ftm-inbox.
|
|
3
|
+
|
|
4
|
+
Tables:
|
|
5
|
+
- inbox : normalized items from all pollers
|
|
6
|
+
- events : raw event log from all sources
|
|
7
|
+
- plans : structured YAML plans linked to inbox tasks
|
|
8
|
+
- audit_log : immutable record of every mutation performed by the executor
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
SCHEMA_SQL = """
|
|
12
|
+
CREATE TABLE IF NOT EXISTS inbox (
|
|
13
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
14
|
+
source TEXT NOT NULL,
|
|
15
|
+
source_id TEXT NOT NULL,
|
|
16
|
+
title TEXT NOT NULL DEFAULT '',
|
|
17
|
+
body TEXT NOT NULL DEFAULT '',
|
|
18
|
+
status TEXT NOT NULL DEFAULT 'open',
|
|
19
|
+
priority TEXT NOT NULL DEFAULT 'medium',
|
|
20
|
+
assignee TEXT,
|
|
21
|
+
requester TEXT,
|
|
22
|
+
created_at TEXT,
|
|
23
|
+
updated_at TEXT,
|
|
24
|
+
tags TEXT NOT NULL DEFAULT '[]',
|
|
25
|
+
custom_fields TEXT NOT NULL DEFAULT '{}',
|
|
26
|
+
raw_payload TEXT NOT NULL DEFAULT '{}',
|
|
27
|
+
source_url TEXT,
|
|
28
|
+
content_hash TEXT NOT NULL UNIQUE,
|
|
29
|
+
ingested_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
30
|
+
);
|
|
31
|
+
|
|
32
|
+
CREATE INDEX IF NOT EXISTS idx_inbox_source ON inbox(source);
|
|
33
|
+
CREATE INDEX IF NOT EXISTS idx_inbox_status ON inbox(status);
|
|
34
|
+
CREATE INDEX IF NOT EXISTS idx_inbox_content_hash ON inbox(content_hash);
|
|
35
|
+
|
|
36
|
+
CREATE TABLE IF NOT EXISTS events (
|
|
37
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
38
|
+
type TEXT NOT NULL,
|
|
39
|
+
payload TEXT NOT NULL DEFAULT '{}',
|
|
40
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
41
|
+
);
|
|
42
|
+
|
|
43
|
+
CREATE INDEX IF NOT EXISTS idx_events_type ON events(type);
|
|
44
|
+
CREATE INDEX IF NOT EXISTS idx_events_created_at ON events(created_at);
|
|
45
|
+
|
|
46
|
+
CREATE TABLE IF NOT EXISTS plans (
|
|
47
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
48
|
+
task_id INTEGER NOT NULL REFERENCES inbox(id) ON DELETE CASCADE,
|
|
49
|
+
yaml_content TEXT NOT NULL,
|
|
50
|
+
status TEXT NOT NULL DEFAULT 'draft',
|
|
51
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
52
|
+
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
53
|
+
);
|
|
54
|
+
|
|
55
|
+
CREATE INDEX IF NOT EXISTS idx_plans_task_id ON plans(task_id);
|
|
56
|
+
CREATE INDEX IF NOT EXISTS idx_plans_status ON plans(status);
|
|
57
|
+
|
|
58
|
+
CREATE TABLE IF NOT EXISTS audit_log (
|
|
59
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
60
|
+
step_id TEXT NOT NULL,
|
|
61
|
+
action_type TEXT NOT NULL,
|
|
62
|
+
target_system TEXT NOT NULL,
|
|
63
|
+
target_object TEXT NOT NULL,
|
|
64
|
+
mutation_performed TEXT NOT NULL,
|
|
65
|
+
result TEXT NOT NULL DEFAULT '{}',
|
|
66
|
+
rollback_available INTEGER NOT NULL DEFAULT 0,
|
|
67
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
68
|
+
);
|
|
69
|
+
|
|
70
|
+
CREATE INDEX IF NOT EXISTS idx_audit_step_id ON audit_log(step_id);
|
|
71
|
+
CREATE INDEX IF NOT EXISTS idx_audit_action_type ON audit_log(action_type);
|
|
72
|
+
"""
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def initialize_schema(conn) -> None:
|
|
76
|
+
"""Execute all CREATE TABLE and CREATE INDEX statements."""
|
|
77
|
+
conn.executescript(SCHEMA_SQL)
|
|
78
|
+
conn.commit()
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
"""
|
|
2
|
+
ExecutionEngine — orchestrates sequential execution of approved plan steps.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
import logging
|
|
9
|
+
from datetime import datetime, timezone
|
|
10
|
+
from typing import Any, Callable
|
|
11
|
+
|
|
12
|
+
from backend.db.connection import get_connection
|
|
13
|
+
from backend.executor.step_runner import StepRunner
|
|
14
|
+
|
|
15
|
+
logger = logging.getLogger(__name__)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class ExecutionEngine:
|
|
19
|
+
"""Executes approved plan steps in sequence with pause/resume support."""
|
|
20
|
+
|
|
21
|
+
def __init__(self, task_id: int, plan_id: int) -> None:
|
|
22
|
+
self.task_id = task_id
|
|
23
|
+
self.plan_id = plan_id
|
|
24
|
+
self._paused = False
|
|
25
|
+
self._callbacks: list[Callable[[str], None]] = []
|
|
26
|
+
self._invocation_count = 0
|
|
27
|
+
|
|
28
|
+
def on_output(self, callback: Callable[[str], None]) -> None:
|
|
29
|
+
"""Register a callback for streaming output."""
|
|
30
|
+
self._callbacks.append(callback)
|
|
31
|
+
|
|
32
|
+
def pause(self) -> None:
|
|
33
|
+
self._paused = True
|
|
34
|
+
|
|
35
|
+
def resume(self) -> None:
|
|
36
|
+
self._paused = False
|
|
37
|
+
|
|
38
|
+
def _emit(self, text: str) -> None:
|
|
39
|
+
for cb in self._callbacks:
|
|
40
|
+
try:
|
|
41
|
+
cb(text)
|
|
42
|
+
except Exception:
|
|
43
|
+
pass
|
|
44
|
+
|
|
45
|
+
async def execute(self) -> dict[str, Any]:
|
|
46
|
+
"""Execute all approved steps in sequence."""
|
|
47
|
+
conn = get_connection()
|
|
48
|
+
steps = self._load_approved_steps(conn)
|
|
49
|
+
task_context = self._load_task_context(conn)
|
|
50
|
+
|
|
51
|
+
if not steps:
|
|
52
|
+
return {"status": "no_steps", "message": "No approved steps to execute"}
|
|
53
|
+
|
|
54
|
+
self._update_plan_status(conn, "executing")
|
|
55
|
+
results: list[dict] = []
|
|
56
|
+
|
|
57
|
+
for step in steps:
|
|
58
|
+
if self._paused:
|
|
59
|
+
self._emit("Execution paused. Use resume to continue.")
|
|
60
|
+
return {"status": "paused", "last_step_id": step["id"], "results": results}
|
|
61
|
+
|
|
62
|
+
step_id = step["id"]
|
|
63
|
+
self._update_step_status(conn, step_id, "running")
|
|
64
|
+
self._emit(f"Step {step_id}: {step.get('title', '...')}")
|
|
65
|
+
|
|
66
|
+
result = await StepRunner.run(step, task_context)
|
|
67
|
+
self._invocation_count += 1
|
|
68
|
+
results.append({"step_id": step_id, **result})
|
|
69
|
+
|
|
70
|
+
if result["status"] == "completed":
|
|
71
|
+
self._update_step_status(conn, step_id, "completed")
|
|
72
|
+
self._log_audit(conn, step, result)
|
|
73
|
+
self._emit(f"Step {step_id} completed ({result['duration_ms']}ms)")
|
|
74
|
+
else:
|
|
75
|
+
self._update_step_status(conn, step_id, "failed")
|
|
76
|
+
self._mark_dependents_blocked(conn, step_id, steps)
|
|
77
|
+
self._log_audit(conn, step, result)
|
|
78
|
+
self._emit(f"Step {step_id} failed: {result.get('error', 'unknown')}")
|
|
79
|
+
self._update_plan_status(conn, "failed")
|
|
80
|
+
return {"status": "failed", "failed_step": step_id, "results": results}
|
|
81
|
+
|
|
82
|
+
self._update_plan_status(conn, "completed")
|
|
83
|
+
self._emit(f"Execution complete. {len(steps)} steps, {self._invocation_count} CLI invocations.")
|
|
84
|
+
return {"status": "completed", "results": results, "invocations": self._invocation_count}
|
|
85
|
+
|
|
86
|
+
def _load_approved_steps(self, conn) -> list[dict]:
|
|
87
|
+
row = conn.execute(
|
|
88
|
+
"SELECT yaml_content FROM plans WHERE id = ?", (self.plan_id,)
|
|
89
|
+
).fetchone()
|
|
90
|
+
if not row:
|
|
91
|
+
return []
|
|
92
|
+
import yaml
|
|
93
|
+
plan_data = yaml.safe_load(row["yaml_content"]) or {}
|
|
94
|
+
steps = plan_data.get("steps", [])
|
|
95
|
+
return [s for s in steps if s.get("status") in ("approved", "pending")]
|
|
96
|
+
|
|
97
|
+
def _load_task_context(self, conn) -> dict:
|
|
98
|
+
row = conn.execute(
|
|
99
|
+
"SELECT * FROM inbox WHERE id = ?", (self.task_id,)
|
|
100
|
+
).fetchone()
|
|
101
|
+
return dict(row) if row else {}
|
|
102
|
+
|
|
103
|
+
def _update_step_status(self, conn, step_id: int, status: str) -> None:
|
|
104
|
+
row = conn.execute(
|
|
105
|
+
"SELECT yaml_content FROM plans WHERE id = ?", (self.plan_id,)
|
|
106
|
+
).fetchone()
|
|
107
|
+
if not row:
|
|
108
|
+
return
|
|
109
|
+
import yaml
|
|
110
|
+
plan_data = yaml.safe_load(row["yaml_content"]) or {}
|
|
111
|
+
for step in plan_data.get("steps", []):
|
|
112
|
+
if step.get("id") == step_id:
|
|
113
|
+
step["status"] = status
|
|
114
|
+
updated = yaml.dump(plan_data, default_flow_style=False)
|
|
115
|
+
conn.execute(
|
|
116
|
+
"UPDATE plans SET yaml_content = ?, updated_at = datetime('now') WHERE id = ?",
|
|
117
|
+
(updated, self.plan_id),
|
|
118
|
+
)
|
|
119
|
+
conn.commit()
|
|
120
|
+
|
|
121
|
+
def _update_plan_status(self, conn, status: str) -> None:
|
|
122
|
+
conn.execute(
|
|
123
|
+
"UPDATE plans SET status = ?, updated_at = datetime('now') WHERE id = ?",
|
|
124
|
+
(status, self.plan_id),
|
|
125
|
+
)
|
|
126
|
+
conn.commit()
|
|
127
|
+
|
|
128
|
+
def _mark_dependents_blocked(self, conn, failed_step_id: int, all_steps: list[dict]) -> None:
|
|
129
|
+
for step in all_steps:
|
|
130
|
+
if step.get("id", 0) > failed_step_id and step.get("status") != "completed":
|
|
131
|
+
self._update_step_status(conn, step["id"], "blocked")
|
|
132
|
+
|
|
133
|
+
def _log_audit(self, conn, step: dict, result: dict) -> None:
|
|
134
|
+
conn.execute(
|
|
135
|
+
"""INSERT INTO audit_log
|
|
136
|
+
(step_id, action_type, target_system, target_object,
|
|
137
|
+
mutation_performed, result, rollback_available)
|
|
138
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)""",
|
|
139
|
+
(
|
|
140
|
+
str(step.get("id", "")),
|
|
141
|
+
"execute_step",
|
|
142
|
+
step.get("target_system", ""),
|
|
143
|
+
step.get("title", ""),
|
|
144
|
+
result.get("output", "")[:500],
|
|
145
|
+
json.dumps({"status": result["status"], "duration_ms": result.get("duration_ms", 0)}),
|
|
146
|
+
1 if step.get("rollback") else 0,
|
|
147
|
+
),
|
|
148
|
+
)
|
|
149
|
+
conn.commit()
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""
|
|
2
|
+
StepRunner — executes a single plan step via Claude CLI.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
import logging
|
|
9
|
+
import subprocess
|
|
10
|
+
import time
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
logger = logging.getLogger(__name__)
|
|
14
|
+
|
|
15
|
+
_STEP_TIMEOUT = 120 # seconds
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class StepRunner:
|
|
19
|
+
"""Runs a single plan step by invoking Claude CLI."""
|
|
20
|
+
|
|
21
|
+
@staticmethod
|
|
22
|
+
async def run(step: dict, task_context: dict) -> dict[str, Any]:
|
|
23
|
+
"""
|
|
24
|
+
Execute a plan step and return structured result.
|
|
25
|
+
|
|
26
|
+
Returns:
|
|
27
|
+
{"status": "completed"|"failed", "output": str, "error": str, "duration_ms": int}
|
|
28
|
+
"""
|
|
29
|
+
prompt = (
|
|
30
|
+
f"Execute this plan step:\n\n"
|
|
31
|
+
f"Step: {step.get('title', '')}\n"
|
|
32
|
+
f"Target system: {step.get('target_system', 'local')}\n"
|
|
33
|
+
f"Method: {step.get('method_primary', '')}\n"
|
|
34
|
+
f"Fallback: {step.get('method_fallback', '')}\n\n"
|
|
35
|
+
f"Task context:\n"
|
|
36
|
+
f"Title: {task_context.get('title', '')}\n"
|
|
37
|
+
f"Source: {task_context.get('source', '')}\n"
|
|
38
|
+
f"Body: {task_context.get('body', '')}\n\n"
|
|
39
|
+
f"Execute the step and report what was done. "
|
|
40
|
+
f"If the action cannot be performed, explain why."
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
start = time.monotonic()
|
|
44
|
+
try:
|
|
45
|
+
result = subprocess.run(
|
|
46
|
+
["claude", "-p", prompt, "--output-format", "json"],
|
|
47
|
+
capture_output=True,
|
|
48
|
+
text=True,
|
|
49
|
+
timeout=_STEP_TIMEOUT,
|
|
50
|
+
)
|
|
51
|
+
duration_ms = int((time.monotonic() - start) * 1000)
|
|
52
|
+
|
|
53
|
+
if result.returncode != 0:
|
|
54
|
+
return {
|
|
55
|
+
"status": "failed",
|
|
56
|
+
"output": result.stdout,
|
|
57
|
+
"error": result.stderr or f"Exit code {result.returncode}",
|
|
58
|
+
"duration_ms": duration_ms,
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
# Parse Claude JSON output
|
|
62
|
+
try:
|
|
63
|
+
data = json.loads(result.stdout)
|
|
64
|
+
text = data.get("result", result.stdout)
|
|
65
|
+
except json.JSONDecodeError:
|
|
66
|
+
text = result.stdout
|
|
67
|
+
|
|
68
|
+
return {
|
|
69
|
+
"status": "completed",
|
|
70
|
+
"output": text,
|
|
71
|
+
"error": "",
|
|
72
|
+
"duration_ms": duration_ms,
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
except subprocess.TimeoutExpired:
|
|
76
|
+
duration_ms = int((time.monotonic() - start) * 1000)
|
|
77
|
+
return {
|
|
78
|
+
"status": "failed",
|
|
79
|
+
"output": "",
|
|
80
|
+
"error": f"Step timed out after {_STEP_TIMEOUT}s",
|
|
81
|
+
"duration_ms": duration_ms,
|
|
82
|
+
}
|
|
83
|
+
except FileNotFoundError:
|
|
84
|
+
duration_ms = int((time.monotonic() - start) * 1000)
|
|
85
|
+
return {
|
|
86
|
+
"status": "failed",
|
|
87
|
+
"output": "",
|
|
88
|
+
"error": "Claude CLI not found on PATH",
|
|
89
|
+
"duration_ms": duration_ms,
|
|
90
|
+
}
|
|
91
|
+
except Exception as exc:
|
|
92
|
+
duration_ms = int((time.monotonic() - start) * 1000)
|
|
93
|
+
return {
|
|
94
|
+
"status": "failed",
|
|
95
|
+
"output": "",
|
|
96
|
+
"error": str(exc),
|
|
97
|
+
"duration_ms": duration_ms,
|
|
98
|
+
}
|