contitext 0.5.1__py3-none-any.whl
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.
- contitext/__init__.py +3 -0
- contitext/admin.py +122 -0
- contitext/api.py +214 -0
- contitext/auth.py +106 -0
- contitext/cli.py +68 -0
- contitext/config.py +53 -0
- contitext/db.py +23 -0
- contitext/demo.py +49 -0
- contitext/locking.py +24 -0
- contitext/mcp_server.py +131 -0
- contitext/mcp_smoke.py +140 -0
- contitext/migrations/__init__.py +0 -0
- contitext/migrations/env.py +48 -0
- contitext/migrations/versions/0001_foundation.py +109 -0
- contitext/migrations/versions/__init__.py +0 -0
- contitext/models.py +87 -0
- contitext/projector.py +291 -0
- contitext/repository.py +326 -0
- contitext/schemas.py +145 -0
- contitext/service.py +134 -0
- contitext-0.5.1.dist-info/METADATA +169 -0
- contitext-0.5.1.dist-info/RECORD +27 -0
- contitext-0.5.1.dist-info/WHEEL +5 -0
- contitext-0.5.1.dist-info/entry_points.txt +6 -0
- contitext-0.5.1.dist-info/licenses/LICENSE +202 -0
- contitext-0.5.1.dist-info/licenses/NOTICE +4 -0
- contitext-0.5.1.dist-info/top_level.txt +1 -0
contitext/__init__.py
ADDED
contitext/admin.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"""Idempotent local administration for projects, principals, and ACLs."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
from typing import Literal
|
|
9
|
+
from uuid import UUID
|
|
10
|
+
|
|
11
|
+
from pydantic import BaseModel, ConfigDict, Field, ValidationError
|
|
12
|
+
from sqlalchemy.dialects.postgresql import insert
|
|
13
|
+
|
|
14
|
+
from contitext.config import ConfigurationError, Settings
|
|
15
|
+
from contitext.db import create_database_engine, create_session_factory
|
|
16
|
+
from contitext.models import Principal, Project, ProjectACL
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class SeedProject(BaseModel):
|
|
20
|
+
model_config = ConfigDict(extra="forbid")
|
|
21
|
+
id: str = Field(min_length=1, pattern=r"^[A-Za-z0-9][A-Za-z0-9._-]*$")
|
|
22
|
+
display_name: str = Field(min_length=1)
|
|
23
|
+
status: str = Field(min_length=1)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class SeedPrincipal(BaseModel):
|
|
27
|
+
model_config = ConfigDict(extra="forbid")
|
|
28
|
+
id: UUID
|
|
29
|
+
name: str = Field(min_length=1)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class SeedACL(BaseModel):
|
|
33
|
+
model_config = ConfigDict(extra="forbid")
|
|
34
|
+
project_id: str = Field(min_length=1)
|
|
35
|
+
principal_id: UUID
|
|
36
|
+
role: Literal["reader", "writer", "owner"]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class SeedDocument(BaseModel):
|
|
40
|
+
model_config = ConfigDict(extra="forbid")
|
|
41
|
+
projects: list[SeedProject] = Field(default_factory=list)
|
|
42
|
+
principals: list[SeedPrincipal] = Field(default_factory=list)
|
|
43
|
+
acls: list[SeedACL] = Field(default_factory=list)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def seed_database(database_url: str, document: SeedDocument) -> dict[str, int]:
|
|
47
|
+
project_ids = {item.id for item in document.projects}
|
|
48
|
+
principal_ids = {item.id for item in document.principals}
|
|
49
|
+
if len(project_ids) != len(document.projects):
|
|
50
|
+
raise ValueError("seed contains duplicate project ids")
|
|
51
|
+
if len(principal_ids) != len(document.principals):
|
|
52
|
+
raise ValueError("seed contains duplicate principal ids")
|
|
53
|
+
if any(item.project_id not in project_ids for item in document.acls):
|
|
54
|
+
raise ValueError("every ACL project must appear in seed projects")
|
|
55
|
+
if any(item.principal_id not in principal_ids for item in document.acls):
|
|
56
|
+
raise ValueError("every ACL principal must appear in seed principals")
|
|
57
|
+
|
|
58
|
+
engine = create_database_engine(database_url)
|
|
59
|
+
factory = create_session_factory(engine)
|
|
60
|
+
try:
|
|
61
|
+
with factory.begin() as session:
|
|
62
|
+
for item in document.projects:
|
|
63
|
+
session.execute(
|
|
64
|
+
insert(Project)
|
|
65
|
+
.values(id=item.id, display_name=item.display_name, status=item.status)
|
|
66
|
+
.on_conflict_do_update(
|
|
67
|
+
index_elements=[Project.id],
|
|
68
|
+
set_={"display_name": item.display_name, "status": item.status},
|
|
69
|
+
)
|
|
70
|
+
)
|
|
71
|
+
for item in document.principals:
|
|
72
|
+
session.execute(
|
|
73
|
+
insert(Principal)
|
|
74
|
+
.values(id=item.id, name=item.name)
|
|
75
|
+
.on_conflict_do_update(
|
|
76
|
+
index_elements=[Principal.id], set_={"name": item.name}
|
|
77
|
+
)
|
|
78
|
+
)
|
|
79
|
+
for item in document.acls:
|
|
80
|
+
session.execute(
|
|
81
|
+
insert(ProjectACL)
|
|
82
|
+
.values(
|
|
83
|
+
project_id=item.project_id,
|
|
84
|
+
principal_id=item.principal_id,
|
|
85
|
+
role=item.role,
|
|
86
|
+
)
|
|
87
|
+
.on_conflict_do_update(
|
|
88
|
+
index_elements=[ProjectACL.project_id, ProjectACL.principal_id],
|
|
89
|
+
set_={"role": item.role},
|
|
90
|
+
)
|
|
91
|
+
)
|
|
92
|
+
finally:
|
|
93
|
+
engine.dispose()
|
|
94
|
+
return {
|
|
95
|
+
"projects": len(document.projects),
|
|
96
|
+
"principals": len(document.principals),
|
|
97
|
+
"acls": len(document.acls),
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _load_seed() -> SeedDocument:
|
|
102
|
+
raw = os.environ.get("CONTITEXT_SEED_JSON")
|
|
103
|
+
if not raw:
|
|
104
|
+
raise ValueError("CONTITEXT_SEED_JSON is required")
|
|
105
|
+
return SeedDocument.model_validate_json(raw)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def main(argv: list[str] | None = None, *, prog: str = "contitext-admin") -> None:
|
|
109
|
+
parser = argparse.ArgumentParser(prog=prog)
|
|
110
|
+
parser.add_argument("command", choices=["seed"])
|
|
111
|
+
args = parser.parse_args(argv)
|
|
112
|
+
try:
|
|
113
|
+
if args.command == "seed":
|
|
114
|
+
settings = Settings.from_env()
|
|
115
|
+
counts = seed_database(settings.database_url, _load_seed())
|
|
116
|
+
print(json.dumps({"status": "ok", **counts}, sort_keys=True))
|
|
117
|
+
except (ConfigurationError, ValueError, ValidationError) as exc:
|
|
118
|
+
parser.error(str(exc))
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
if __name__ == "__main__":
|
|
122
|
+
main()
|
contitext/api.py
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
"""Thin FastAPI adapter for the Contitext application service."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
import time
|
|
7
|
+
from typing import Any, Callable
|
|
8
|
+
from uuid import uuid4
|
|
9
|
+
|
|
10
|
+
from fastapi import Depends, FastAPI, HTTPException, Query, Request, Response, status
|
|
11
|
+
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
|
12
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
13
|
+
|
|
14
|
+
from contitext.auth import AuthenticationError, PrincipalIdentity, ProjectNotFoundError, TokenStore
|
|
15
|
+
from contitext.config import Settings
|
|
16
|
+
from contitext.db import create_database_engine, create_session_factory
|
|
17
|
+
from contitext.repository import BindingNotFoundError, IdempotencyConflictError, Repository
|
|
18
|
+
from contitext.projector import Projector
|
|
19
|
+
from contitext.schemas import (
|
|
20
|
+
BindProjectRequest,
|
|
21
|
+
HandoffRequest,
|
|
22
|
+
RecordEventKind,
|
|
23
|
+
RecordContextRequest,
|
|
24
|
+
)
|
|
25
|
+
from contitext.service import ContextService, WriterFencedError, ProjectionUnavailableError
|
|
26
|
+
|
|
27
|
+
logger = logging.getLogger("contitext.http")
|
|
28
|
+
bearer = HTTPBearer(auto_error=False)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class BindBody(BaseModel):
|
|
32
|
+
model_config = ConfigDict(extra="forbid")
|
|
33
|
+
project_id: str = Field(min_length=1)
|
|
34
|
+
session_id: str = Field(min_length=1)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class RecordBody(BaseModel):
|
|
38
|
+
model_config = ConfigDict(extra="forbid")
|
|
39
|
+
scope_id: str = Field(min_length=1)
|
|
40
|
+
session_id: str = Field(min_length=1)
|
|
41
|
+
agent_id: str = Field(min_length=1)
|
|
42
|
+
source_kind: str = Field(min_length=1)
|
|
43
|
+
source_id: str = Field(min_length=1)
|
|
44
|
+
event_kind: RecordEventKind
|
|
45
|
+
payload: dict[str, Any]
|
|
46
|
+
idempotency_key: str = Field(min_length=1)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class HandoffBody(BaseModel):
|
|
50
|
+
model_config = ConfigDict(extra="forbid")
|
|
51
|
+
scope_id: str = Field(min_length=1)
|
|
52
|
+
session_id: str = Field(min_length=1)
|
|
53
|
+
agent_id: str = Field(min_length=1)
|
|
54
|
+
source_kind: str = Field(min_length=1)
|
|
55
|
+
source_id: str = Field(min_length=1)
|
|
56
|
+
summary: str = Field(min_length=1)
|
|
57
|
+
next_action: str = Field(min_length=1)
|
|
58
|
+
completed: list[str] = Field(default_factory=list)
|
|
59
|
+
current: list[str] = Field(default_factory=list)
|
|
60
|
+
blockers: list[str] = Field(default_factory=list)
|
|
61
|
+
idempotency_key: str = Field(min_length=1)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def create_app(
|
|
65
|
+
*,
|
|
66
|
+
service: ContextService | None = None,
|
|
67
|
+
token_store: TokenStore | None = None,
|
|
68
|
+
projection: Callable[[PrincipalIdentity, str], Any] | None = None,
|
|
69
|
+
) -> FastAPI:
|
|
70
|
+
owned_engine = None
|
|
71
|
+
if service is None or token_store is None:
|
|
72
|
+
settings = Settings.from_env()
|
|
73
|
+
if service is None:
|
|
74
|
+
owned_engine = create_database_engine(settings.database_url)
|
|
75
|
+
factory = create_session_factory(owned_engine)
|
|
76
|
+
configured_projector = None
|
|
77
|
+
if projection is None:
|
|
78
|
+
import os
|
|
79
|
+
projects_root = os.environ.get("CONTITEXT_PROJECTS_ROOT")
|
|
80
|
+
if projects_root:
|
|
81
|
+
configured_projector = Projector(factory, projects_root)
|
|
82
|
+
service = ContextService(Repository(factory), configured_projector)
|
|
83
|
+
if token_store is None:
|
|
84
|
+
token_store = settings.token_store
|
|
85
|
+
if token_store is None:
|
|
86
|
+
raise AuthenticationError("local bearer token resolver is required")
|
|
87
|
+
|
|
88
|
+
app = FastAPI(
|
|
89
|
+
title="Contitext",
|
|
90
|
+
version="0.5.1",
|
|
91
|
+
docs_url=None,
|
|
92
|
+
redoc_url=None,
|
|
93
|
+
)
|
|
94
|
+
app.state.service = service
|
|
95
|
+
app.state.token_store = token_store
|
|
96
|
+
app.state.projection = projection
|
|
97
|
+
app.state.engine = owned_engine
|
|
98
|
+
|
|
99
|
+
@app.middleware("http")
|
|
100
|
+
async def request_context(request: Request, call_next):
|
|
101
|
+
request_id = request.headers.get("x-request-id") or str(uuid4())
|
|
102
|
+
request.state.request_id = request_id
|
|
103
|
+
started = time.monotonic()
|
|
104
|
+
response = await call_next(request)
|
|
105
|
+
response.headers["x-request-id"] = request_id
|
|
106
|
+
logger.info(
|
|
107
|
+
"http_request",
|
|
108
|
+
extra={
|
|
109
|
+
"request_id": request_id,
|
|
110
|
+
"method": request.method,
|
|
111
|
+
"path": request.url.path,
|
|
112
|
+
"status_code": response.status_code,
|
|
113
|
+
"duration_ms": round((time.monotonic() - started) * 1000, 3),
|
|
114
|
+
},
|
|
115
|
+
)
|
|
116
|
+
return response
|
|
117
|
+
|
|
118
|
+
def principal(
|
|
119
|
+
credentials: HTTPAuthorizationCredentials | None = Depends(bearer),
|
|
120
|
+
) -> PrincipalIdentity:
|
|
121
|
+
if credentials is None or credentials.scheme.lower() != "bearer":
|
|
122
|
+
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="invalid bearer credential")
|
|
123
|
+
try:
|
|
124
|
+
return token_store.resolve(credentials.credentials)
|
|
125
|
+
except AuthenticationError as exc:
|
|
126
|
+
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=str(exc)) from exc
|
|
127
|
+
|
|
128
|
+
@app.exception_handler(ProjectNotFoundError)
|
|
129
|
+
async def project_not_found(_: Request, __: ProjectNotFoundError):
|
|
130
|
+
return _json_error(404, "project not found")
|
|
131
|
+
|
|
132
|
+
@app.exception_handler(BindingNotFoundError)
|
|
133
|
+
async def binding_not_found(_: Request, __: BindingNotFoundError):
|
|
134
|
+
return _json_error(404, "scope is not bound")
|
|
135
|
+
|
|
136
|
+
@app.exception_handler(ValueError)
|
|
137
|
+
async def invalid_value(_: Request, exc: ValueError):
|
|
138
|
+
return _json_error(422, str(exc))
|
|
139
|
+
|
|
140
|
+
@app.exception_handler(IdempotencyConflictError)
|
|
141
|
+
async def idempotency_conflict(_: Request, exc: IdempotencyConflictError):
|
|
142
|
+
return _json_error(409, str(exc))
|
|
143
|
+
|
|
144
|
+
@app.exception_handler(ProjectionUnavailableError)
|
|
145
|
+
async def projection_unavailable(_: Request, exc: ProjectionUnavailableError):
|
|
146
|
+
return _json_error(503, str(exc))
|
|
147
|
+
|
|
148
|
+
@app.exception_handler(WriterFencedError)
|
|
149
|
+
async def writers_fenced(_: Request, exc: WriterFencedError):
|
|
150
|
+
return _json_error(503, str(exc))
|
|
151
|
+
|
|
152
|
+
@app.put("/v1/scopes/{scope_id}/binding")
|
|
153
|
+
def bind(scope_id: str, body: BindBody, identity: PrincipalIdentity = Depends(principal)):
|
|
154
|
+
return service.bind_project(identity, BindProjectRequest(
|
|
155
|
+
project_id=body.project_id, scope_id=scope_id, session_id=body.session_id,
|
|
156
|
+
))
|
|
157
|
+
|
|
158
|
+
@app.get("/v1/scopes/{scope_id}/binding")
|
|
159
|
+
def current(scope_id: str, identity: PrincipalIdentity = Depends(principal)):
|
|
160
|
+
return service.current_project(identity, scope_id)
|
|
161
|
+
|
|
162
|
+
@app.get("/v1/projects/{project_id}/context")
|
|
163
|
+
def context(project_id: str, identity: PrincipalIdentity = Depends(principal)):
|
|
164
|
+
return service.get_context(identity, project_id)
|
|
165
|
+
|
|
166
|
+
@app.get("/v1/projects/{project_id}/search")
|
|
167
|
+
def search(
|
|
168
|
+
project_id: str,
|
|
169
|
+
q: str = Query(min_length=1),
|
|
170
|
+
limit: int = Query(default=20, ge=1, le=100),
|
|
171
|
+
cursor: str | None = None,
|
|
172
|
+
identity: PrincipalIdentity = Depends(principal),
|
|
173
|
+
):
|
|
174
|
+
return service.search_context(identity, project_id, q, limit=limit, cursor=cursor)
|
|
175
|
+
|
|
176
|
+
@app.post("/v1/projects/{project_id}/events", status_code=201)
|
|
177
|
+
def record(project_id: str, body: RecordBody, identity: PrincipalIdentity = Depends(principal)):
|
|
178
|
+
return service.record_context(identity, RecordContextRequest(
|
|
179
|
+
project_id=project_id, **body.model_dump(),
|
|
180
|
+
))
|
|
181
|
+
|
|
182
|
+
@app.post("/v1/projects/{project_id}/handoffs", status_code=201)
|
|
183
|
+
def handoff(project_id: str, body: HandoffBody, identity: PrincipalIdentity = Depends(principal)):
|
|
184
|
+
return service.create_handoff(identity, HandoffRequest(
|
|
185
|
+
project_id=project_id, **body.model_dump(),
|
|
186
|
+
))
|
|
187
|
+
|
|
188
|
+
@app.post("/v1/projects/{project_id}/projection")
|
|
189
|
+
def project(project_id: str, identity: PrincipalIdentity = Depends(principal)):
|
|
190
|
+
if projection is not None:
|
|
191
|
+
return projection(identity, project_id)
|
|
192
|
+
return service.project_context(identity, project_id)
|
|
193
|
+
|
|
194
|
+
@app.get("/health/live")
|
|
195
|
+
def live():
|
|
196
|
+
return {"status": "live"}
|
|
197
|
+
|
|
198
|
+
@app.get("/health/ready")
|
|
199
|
+
def ready(response: Response):
|
|
200
|
+
if not service.ready():
|
|
201
|
+
response.status_code = 503
|
|
202
|
+
return {"status": "not ready"}
|
|
203
|
+
return {"status": "ready"}
|
|
204
|
+
|
|
205
|
+
return app
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _json_error(status_code: int, detail: str):
|
|
209
|
+
from fastapi.responses import JSONResponse
|
|
210
|
+
return JSONResponse(status_code=status_code, content={"detail": detail})
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def app_from_env() -> FastAPI:
|
|
214
|
+
return create_app()
|
contitext/auth.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""Local bearer-token authentication and project authorization."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
import hashlib
|
|
7
|
+
import hmac
|
|
8
|
+
import json
|
|
9
|
+
from types import MappingProxyType
|
|
10
|
+
from typing import Any, Mapping
|
|
11
|
+
from uuid import UUID
|
|
12
|
+
|
|
13
|
+
from sqlalchemy import select
|
|
14
|
+
from sqlalchemy.orm import Session
|
|
15
|
+
|
|
16
|
+
from contitext.models import Project, ProjectACL
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class AuthenticationError(RuntimeError):
|
|
20
|
+
"""Raised when a bearer credential is absent or unknown."""
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class ProjectNotFoundError(RuntimeError):
|
|
24
|
+
"""Used for both unknown and unauthorized projects."""
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass(frozen=True)
|
|
28
|
+
class PrincipalIdentity:
|
|
29
|
+
principal_id: UUID
|
|
30
|
+
name: str
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass(frozen=True)
|
|
34
|
+
class _StoredCredential:
|
|
35
|
+
token_hash: bytes
|
|
36
|
+
identity: PrincipalIdentity
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class TokenStore:
|
|
40
|
+
"""Resolve local bearer credentials while retaining hashes only."""
|
|
41
|
+
|
|
42
|
+
def __init__(self, credentials: Mapping[bytes, PrincipalIdentity]) -> None:
|
|
43
|
+
self._credentials = MappingProxyType(dict(credentials))
|
|
44
|
+
|
|
45
|
+
@classmethod
|
|
46
|
+
def from_json(cls, raw: str) -> "TokenStore":
|
|
47
|
+
try:
|
|
48
|
+
parsed: Any = json.loads(raw)
|
|
49
|
+
except json.JSONDecodeError as exc:
|
|
50
|
+
raise AuthenticationError("invalid CONTITEXT_AUTH_TOKENS JSON") from exc
|
|
51
|
+
if not isinstance(parsed, dict) or not parsed:
|
|
52
|
+
raise AuthenticationError("at least one local bearer credential is required")
|
|
53
|
+
|
|
54
|
+
credentials: dict[bytes, PrincipalIdentity] = {}
|
|
55
|
+
for plaintext, details in parsed.items():
|
|
56
|
+
if not isinstance(plaintext, str) or not plaintext:
|
|
57
|
+
raise AuthenticationError("bearer credentials must be non-empty strings")
|
|
58
|
+
if not isinstance(details, dict):
|
|
59
|
+
raise AuthenticationError("credential metadata must be an object")
|
|
60
|
+
try:
|
|
61
|
+
identity = PrincipalIdentity(
|
|
62
|
+
principal_id=UUID(str(details["principal_id"])),
|
|
63
|
+
name=str(details["name"]),
|
|
64
|
+
)
|
|
65
|
+
except (KeyError, ValueError) as exc:
|
|
66
|
+
raise AuthenticationError("credential metadata requires principal_id and name") from exc
|
|
67
|
+
digest = hashlib.sha256(plaintext.encode("utf-8")).digest()
|
|
68
|
+
if digest in credentials:
|
|
69
|
+
raise AuthenticationError("duplicate bearer credential")
|
|
70
|
+
credentials[digest] = identity
|
|
71
|
+
return cls(credentials)
|
|
72
|
+
|
|
73
|
+
def resolve(self, bearer_token: str) -> PrincipalIdentity:
|
|
74
|
+
candidate = hashlib.sha256(bearer_token.encode("utf-8")).digest()
|
|
75
|
+
for digest, identity in self._credentials.items():
|
|
76
|
+
if hmac.compare_digest(candidate, digest):
|
|
77
|
+
return identity
|
|
78
|
+
raise AuthenticationError("invalid bearer credential")
|
|
79
|
+
|
|
80
|
+
def __repr__(self) -> str:
|
|
81
|
+
return f"TokenStore(credentials={len(self._credentials)}, plaintext=redacted)"
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
ROLE_LEVEL = {"reader": 1, "writer": 2, "owner": 3}
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def require_project_access(
|
|
88
|
+
session: Session,
|
|
89
|
+
principal_id: UUID,
|
|
90
|
+
project_id: str,
|
|
91
|
+
minimum_role: str = "reader",
|
|
92
|
+
) -> str:
|
|
93
|
+
"""Return the granted role or raise the non-enumerating not-found error."""
|
|
94
|
+
if minimum_role not in ROLE_LEVEL:
|
|
95
|
+
raise ValueError(f"unknown required role: {minimum_role}")
|
|
96
|
+
role = session.execute(
|
|
97
|
+
select(ProjectACL.role)
|
|
98
|
+
.join(Project, Project.id == ProjectACL.project_id)
|
|
99
|
+
.where(
|
|
100
|
+
ProjectACL.project_id == project_id,
|
|
101
|
+
ProjectACL.principal_id == principal_id,
|
|
102
|
+
)
|
|
103
|
+
).scalar_one_or_none()
|
|
104
|
+
if role is None or ROLE_LEVEL[role] < ROLE_LEVEL[minimum_role]:
|
|
105
|
+
raise ProjectNotFoundError("project not found")
|
|
106
|
+
return role
|
contitext/cli.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""Public command line entry points, including migrations in installed wheels."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import sys
|
|
7
|
+
from importlib.metadata import version
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def migrate() -> None:
|
|
12
|
+
from alembic import command
|
|
13
|
+
from alembic.config import Config
|
|
14
|
+
|
|
15
|
+
config = Config()
|
|
16
|
+
config.set_main_option("script_location", str(Path(__file__).parent / "migrations"))
|
|
17
|
+
command.upgrade(config, "head")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def serve() -> None:
|
|
21
|
+
"""Compatibility entry point for the original contitext-api executable."""
|
|
22
|
+
main(["serve", *sys.argv[1:]])
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def main(argv: list[str] | None = None) -> None:
|
|
26
|
+
parser = argparse.ArgumentParser(
|
|
27
|
+
prog="contitext", description="Project continuity for AI agents.",
|
|
28
|
+
)
|
|
29
|
+
parser.add_argument("--version", action="version", version=version("contitext"))
|
|
30
|
+
commands = parser.add_subparsers(dest="command", required=True)
|
|
31
|
+
commands.add_parser("migrate", help="Apply database migrations.")
|
|
32
|
+
api = commands.add_parser("serve", help="Run the REST API.")
|
|
33
|
+
api.add_argument("--host", default="127.0.0.1")
|
|
34
|
+
api.add_argument("--port", type=int, default=8000)
|
|
35
|
+
commands.add_parser("mcp", help="Run the stdio MCP server.")
|
|
36
|
+
commands.add_parser(
|
|
37
|
+
"mcp-smoke", help="Check all six MCP tools using synthetic records.",
|
|
38
|
+
description="Check MCP against CONTITEXT_SMOKE_PROJECT_ID; writes synthetic records.",
|
|
39
|
+
)
|
|
40
|
+
admin = commands.add_parser("admin", help="Administer projects, principals, and access.")
|
|
41
|
+
admin_commands = admin.add_subparsers(dest="admin_command", required=True)
|
|
42
|
+
admin_commands.add_parser("seed", help="Apply the configured seed document.")
|
|
43
|
+
args = parser.parse_args(argv)
|
|
44
|
+
if args.command == "migrate":
|
|
45
|
+
migrate()
|
|
46
|
+
elif args.command == "serve":
|
|
47
|
+
import uvicorn
|
|
48
|
+
|
|
49
|
+
uvicorn.run(
|
|
50
|
+
"contitext.api:app_from_env", factory=True, host=args.host, port=args.port,
|
|
51
|
+
access_log=False,
|
|
52
|
+
)
|
|
53
|
+
elif args.command == "mcp":
|
|
54
|
+
from contitext.mcp_server import main as run_mcp
|
|
55
|
+
|
|
56
|
+
run_mcp()
|
|
57
|
+
elif args.command == "mcp-smoke":
|
|
58
|
+
from contitext.mcp_smoke import main as run_smoke
|
|
59
|
+
|
|
60
|
+
run_smoke()
|
|
61
|
+
elif args.command == "admin":
|
|
62
|
+
from contitext.admin import main as run_admin
|
|
63
|
+
|
|
64
|
+
run_admin([args.admin_command], prog="contitext admin")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
if __name__ == "__main__":
|
|
68
|
+
main()
|
contitext/config.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""Environment-only configuration for the Contitext service."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
import os
|
|
7
|
+
from typing import Mapping
|
|
8
|
+
|
|
9
|
+
from contitext.auth import AuthenticationError, TokenStore
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class ConfigurationError(RuntimeError):
|
|
13
|
+
"""Raised when required service configuration is missing or unsafe."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True)
|
|
17
|
+
class Settings:
|
|
18
|
+
database_url: str
|
|
19
|
+
token_store: TokenStore | None
|
|
20
|
+
|
|
21
|
+
@classmethod
|
|
22
|
+
def from_env(
|
|
23
|
+
cls,
|
|
24
|
+
environ: Mapping[str, str] | None = None,
|
|
25
|
+
*,
|
|
26
|
+
testing: bool = False,
|
|
27
|
+
) -> "Settings":
|
|
28
|
+
values = os.environ if environ is None else environ
|
|
29
|
+
database_key = "CONTITEXT_TEST_DATABASE_URL" if testing else "DATABASE_URL"
|
|
30
|
+
database_url = values.get(database_key, "").strip()
|
|
31
|
+
auth_tokens_json = values.get("CONTITEXT_AUTH_TOKENS", "").strip()
|
|
32
|
+
|
|
33
|
+
missing = []
|
|
34
|
+
if not database_url:
|
|
35
|
+
missing.append(database_key)
|
|
36
|
+
if not testing and not auth_tokens_json:
|
|
37
|
+
missing.append("CONTITEXT_AUTH_TOKENS")
|
|
38
|
+
if missing:
|
|
39
|
+
raise ConfigurationError(
|
|
40
|
+
"missing required environment configuration: " + ", ".join(missing)
|
|
41
|
+
)
|
|
42
|
+
if not database_url.startswith(("postgresql+psycopg://", "postgresql://")):
|
|
43
|
+
raise ConfigurationError("Contitext requires a PostgreSQL database URL")
|
|
44
|
+
if testing and "test" not in database_url.rsplit("/", 1)[-1].lower():
|
|
45
|
+
raise ConfigurationError("test database URL must name a dedicated test database")
|
|
46
|
+
|
|
47
|
+
token_store = None
|
|
48
|
+
if auth_tokens_json:
|
|
49
|
+
try:
|
|
50
|
+
token_store = TokenStore.from_json(auth_tokens_json)
|
|
51
|
+
except AuthenticationError as exc:
|
|
52
|
+
raise ConfigurationError(str(exc)) from exc
|
|
53
|
+
return cls(database_url=database_url, token_store=token_store)
|
contitext/db.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""SQLAlchemy engine and transaction helpers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Iterator
|
|
6
|
+
from contextlib import contextmanager
|
|
7
|
+
|
|
8
|
+
from sqlalchemy import Engine, create_engine
|
|
9
|
+
from sqlalchemy.orm import Session, sessionmaker
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def create_database_engine(database_url: str) -> Engine:
|
|
13
|
+
return create_engine(database_url, pool_pre_ping=True)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def create_session_factory(engine: Engine) -> sessionmaker[Session]:
|
|
17
|
+
return sessionmaker(bind=engine, expire_on_commit=False)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@contextmanager
|
|
21
|
+
def session_scope(factory: sessionmaker[Session]) -> Iterator[Session]:
|
|
22
|
+
with factory.begin() as session:
|
|
23
|
+
yield session
|
contitext/demo.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""A small real HTTP handoff between two example agents. Writes to project demo."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
from urllib.request import Request, urlopen
|
|
6
|
+
from uuid import uuid4
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def main() -> None:
|
|
10
|
+
base = os.environ.get("CONTITEXT_HTTP_URL", "http://127.0.0.1:8000").rstrip("/")
|
|
11
|
+
token = os.environ["CONTITEXT_MCP_TOKEN"]
|
|
12
|
+
run = uuid4().hex
|
|
13
|
+
|
|
14
|
+
def call(method, path, body=None):
|
|
15
|
+
data = json.dumps(body).encode() if body is not None else None
|
|
16
|
+
request = Request(base + path, data=data, method=method,
|
|
17
|
+
headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"})
|
|
18
|
+
with urlopen(request, timeout=10) as response:
|
|
19
|
+
return json.load(response)
|
|
20
|
+
|
|
21
|
+
scope_a, scope_b = f"demo:agent-a:{run}", f"demo:agent-b:{run}"
|
|
22
|
+
call("PUT", f"/v1/scopes/{scope_a}/binding", {"project_id": "demo", "session_id": run})
|
|
23
|
+
provenance = {"scope_id": scope_a, "session_id": run, "agent_id": "agent-a",
|
|
24
|
+
"source_kind": "demo", "source_id": run}
|
|
25
|
+
event = {**provenance, "event_kind": "decision", "payload": {"text": "Use PostgreSQL for durable project state."},
|
|
26
|
+
"idempotency_key": f"demo-decision:{run}"}
|
|
27
|
+
first = call("POST", "/v1/projects/demo/events", event)
|
|
28
|
+
retry = call("POST", "/v1/projects/demo/events", event)
|
|
29
|
+
assert first["event_id"] == retry["event_id"], "retry created a duplicate"
|
|
30
|
+
call("POST", "/v1/projects/demo/events", {
|
|
31
|
+
**provenance, "event_kind": "checkpoint", "payload": {"summary": "Storage design is agreed."},
|
|
32
|
+
"idempotency_key": f"demo-checkpoint:{run}",
|
|
33
|
+
})
|
|
34
|
+
handoff = call("POST", "/v1/projects/demo/handoffs", {
|
|
35
|
+
**provenance, "summary": "Design ready for implementation.",
|
|
36
|
+
"next_action": "Implement and test the first endpoint.",
|
|
37
|
+
"completed": ["Storage decision"], "current": ["Endpoint implementation"], "blockers": [],
|
|
38
|
+
"idempotency_key": f"demo-handoff:{run}",
|
|
39
|
+
})
|
|
40
|
+
call("PUT", f"/v1/scopes/{scope_b}/binding", {"project_id": "demo", "session_id": run})
|
|
41
|
+
resumed = call("GET", "/v1/projects/demo/context")
|
|
42
|
+
assert resumed["latest_handoff"]["event_id"] == handoff["event_id"]
|
|
43
|
+
print(json.dumps({"agent_b_resumed": resumed["overview"]["project_id"],
|
|
44
|
+
"next_action": resumed["latest_handoff"]["payload"]["next_action"],
|
|
45
|
+
"idempotent_retry": "passed"}, indent=2))
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
if __name__ == "__main__":
|
|
49
|
+
main()
|
contitext/locking.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""Shared PostgreSQL project transaction locking.
|
|
2
|
+
|
|
3
|
+
All context-event writers and the Markdown projector serialize on the same
|
|
4
|
+
64-bit advisory key: PostgreSQL ``hashtextextended(project_id, 0)``. Writers
|
|
5
|
+
assign ``clock_timestamp()`` only after acquiring this transaction lock, so a
|
|
6
|
+
projector cannot advance beyond an uncommitted event that will later appear
|
|
7
|
+
with an older ordering timestamp.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from sqlalchemy import text
|
|
13
|
+
from sqlalchemy.orm import Session
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
PROJECT_TRANSACTION_LOCK_SQL = text(
|
|
17
|
+
"SELECT pg_advisory_xact_lock(hashtextextended(CAST(:project_id AS text), 0))"
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def acquire_project_transaction_lock(session: Session, project_id: str) -> None:
|
|
22
|
+
"""Serialize a project's event insertion and projection transactions."""
|
|
23
|
+
|
|
24
|
+
session.execute(PROJECT_TRANSACTION_LOCK_SQL, {"project_id": project_id})
|