capabilities-contract 0.1.0__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.
@@ -0,0 +1,5 @@
1
+ """The capabilities contract as a library. Its first part is `capabilities_contract.db`."""
2
+
3
+ from capabilities_contract.version import __version__
4
+
5
+ __all__ = ["__version__"]
@@ -0,0 +1,31 @@
1
+ """The shared database layer: read the machine's store setting, connect bound to its
2
+ schema, and migrate each owner's tables once under a ledger.
3
+
4
+ Importing this module does not import psycopg; `connect` and `migrate` do.
5
+ """
6
+
7
+ from capabilities_contract.db._connect import connect
8
+ from capabilities_contract.db._errors import DbError
9
+ from capabilities_contract.db._migrate import MigrateResult, Step, migrate
10
+ from capabilities_contract.db._setting import (
11
+ DEFAULT_SCHEMA,
12
+ SETTING_SCHEMA_V1,
13
+ SETTING_SCHEMA_V2,
14
+ Setting,
15
+ read_setting,
16
+ setting_files,
17
+ )
18
+
19
+ __all__ = [
20
+ "DEFAULT_SCHEMA",
21
+ "SETTING_SCHEMA_V1",
22
+ "SETTING_SCHEMA_V2",
23
+ "DbError",
24
+ "MigrateResult",
25
+ "Setting",
26
+ "Step",
27
+ "connect",
28
+ "migrate",
29
+ "read_setting",
30
+ "setting_files",
31
+ ]
@@ -0,0 +1,63 @@
1
+ """A connection bound to the configured schema. psycopg is imported here, lazily."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import weakref
6
+ from typing import Any
7
+
8
+ from capabilities_contract.db._errors import DbError
9
+ from capabilities_contract.db._setting import Setting, check_schema_name, read_setting
10
+
11
+ # The schema each connection from `connect` is bound to, so `migrate` needs no
12
+ # second argument naming it.
13
+ _BOUND: weakref.WeakKeyDictionary = weakref.WeakKeyDictionary()
14
+
15
+
16
+ def _psycopg():
17
+ try:
18
+ import psycopg
19
+ from psycopg import sql
20
+ except ImportError as exc: # pragma: no cover - depends on the installed wheels
21
+ raise DbError("driver_missing", "psycopg is not installed",
22
+ "depend on capabilities-contract, which brings psycopg[binary]") from exc
23
+ return psycopg, sql
24
+
25
+
26
+ def bind_search_path(conn: Any, schema: str) -> None:
27
+ """Set the session's search_path to `schema` alone."""
28
+ _, sql = _psycopg()
29
+ conn.execute(sql.SQL("SET search_path TO {}").format(sql.Identifier(schema)))
30
+
31
+
32
+ def connect(*, application_name: str, setting: Setting | None = None,
33
+ connect_timeout: int = 10) -> Any:
34
+ """A psycopg connection to the store, with search_path set to the configured
35
+ schema only (never `public`). The schema need not exist yet: `migrate` creates
36
+ it. The connection is returned idle, outside any transaction."""
37
+ if not isinstance(application_name, str) or not application_name:
38
+ raise DbError("bad_application_name", "application_name must be a non-empty string")
39
+ setting = setting if setting is not None else read_setting()
40
+ schema = check_schema_name(setting.schema)
41
+ psycopg, _ = _psycopg()
42
+ try:
43
+ conn = psycopg.connect(**setting.connect_kwargs(), application_name=application_name,
44
+ connect_timeout=connect_timeout)
45
+ except psycopg.OperationalError as exc:
46
+ raise DbError("store_unreachable", f"cannot reach the store: {exc}",
47
+ "check the store setting with `capabilities store doctor`") from exc
48
+ try:
49
+ bind_search_path(conn, schema)
50
+ conn.commit()
51
+ except Exception:
52
+ conn.close()
53
+ raise
54
+ _BOUND[conn] = schema
55
+ return conn
56
+
57
+
58
+ def bound_schema(conn: Any) -> str | None:
59
+ """The schema `connect` bound this connection to, or None."""
60
+ try:
61
+ return _BOUND.get(conn)
62
+ except TypeError:
63
+ return None
@@ -0,0 +1,12 @@
1
+ class DbError(Exception):
2
+ """Every failure the database layer reports. `slug` is stable and machine-read,
3
+ `message` says what happened, `hint` (possibly None) says what to do."""
4
+
5
+ def __init__(self, slug: str, message: str, hint: str | None = None):
6
+ super().__init__(message)
7
+ self.slug = slug
8
+ self.message = message
9
+ self.hint = hint
10
+
11
+ def __repr__(self) -> str:
12
+ return f"DbError({self.slug!r}, {self.message!r}, {self.hint!r})"
@@ -0,0 +1,282 @@
1
+ """Each owner's tables, migrated once under a ledger.
2
+
3
+ An owner is the tool that owns a set of tables, named for it: every relation, index,
4
+ sequence, type and function its steps create is named `<owner>` or `<owner>_*`, in
5
+ the configured schema. Two platform tables in the same schema keep the books:
6
+ `schema_ledger` (one row per applied step) and `schema_version` (one row per owner).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import hashlib
12
+ import re
13
+ from collections.abc import Iterable, Sequence
14
+ from dataclasses import dataclass, field
15
+ from typing import Any
16
+
17
+ from capabilities_contract.db._connect import _psycopg, bind_search_path, bound_schema
18
+ from capabilities_contract.db._errors import DbError
19
+ from capabilities_contract.db._setting import check_schema_name
20
+ from capabilities_contract.version import __version__
21
+
22
+ LEDGER_TABLE = "schema_ledger"
23
+ VERSION_TABLE = "schema_version"
24
+ RESERVED_NAMES = (LEDGER_TABLE, VERSION_TABLE)
25
+ RESERVED_OWNERS = ("schema", "pg")
26
+
27
+ # No underscore: then no owner's `<owner>_` prefix can cover another owner's.
28
+ _OWNER = re.compile(r"[a-z][a-z0-9]{0,30}")
29
+ _STEP_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,127}")
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class Step:
34
+ """One migration step: a stable id and the SQL it runs. The checksum is the
35
+ SHA-256 of the SQL text exactly as given."""
36
+
37
+ id: str
38
+ sql: str
39
+
40
+ @property
41
+ def checksum(self) -> str:
42
+ return hashlib.sha256(self.sql.encode("utf-8")).hexdigest()
43
+
44
+
45
+ @dataclass
46
+ class MigrateResult:
47
+ """What `migrate` did. `warnings` is empty unless the store is ahead of the
48
+ caller in a way the caller may still work with (a newer minor)."""
49
+
50
+ owner: str
51
+ schema: str
52
+ applied: list[str] = field(default_factory=list)
53
+ skipped: list[str] = field(default_factory=list)
54
+ warnings: list[str] = field(default_factory=list)
55
+ major: int | None = None
56
+ minor: int | None = None
57
+
58
+
59
+ def check_owner(owner: object) -> str:
60
+ if not isinstance(owner, str) or not _OWNER.fullmatch(owner) or owner in RESERVED_OWNERS:
61
+ raise DbError("bad_owner", f"owner {owner!r} is not a lowercase identifier",
62
+ "use lowercase letters and digits, starting with a letter, "
63
+ "no underscore, at most 31 characters")
64
+ return owner
65
+
66
+
67
+ def _check_version_numbers(major: object, minor: object) -> tuple[int, int]:
68
+ for name, value in (("major", major), ("minor", minor)):
69
+ if isinstance(value, bool) or not isinstance(value, int) or value < 0:
70
+ raise DbError("bad_version", f"{name} must be a non-negative integer")
71
+ return major, minor # type: ignore[return-value]
72
+
73
+
74
+ def _normalise_steps(steps: Iterable[Step | Sequence[str]]) -> list[Step]:
75
+ out: list[Step] = []
76
+ seen: set[str] = set()
77
+ for raw in steps:
78
+ if isinstance(raw, Step):
79
+ step = raw
80
+ elif isinstance(raw, (tuple, list)) and len(raw) == 2:
81
+ step = Step(raw[0], raw[1])
82
+ else:
83
+ raise DbError("bad_step", f"a step is a Step or a (step_id, sql) pair, not {raw!r}")
84
+ if not isinstance(step.id, str) or not _STEP_ID.fullmatch(step.id):
85
+ raise DbError("bad_step", f"step id {step.id!r} is not a valid step id",
86
+ "letters, digits, '.', '_' and '-', starting with a letter or digit")
87
+ if not isinstance(step.sql, str) or not step.sql.strip():
88
+ raise DbError("bad_step", f"step {step.id!r} has no SQL")
89
+ if step.id in seen:
90
+ raise DbError("bad_step", f"step id {step.id!r} appears twice")
91
+ seen.add(step.id)
92
+ out.append(step)
93
+ return out
94
+
95
+
96
+ _SYSTEM_NS = ("n.nspname NOT IN ('pg_catalog', 'information_schema') "
97
+ "AND n.nspname NOT LIKE 'pg\\_%'")
98
+
99
+ # Every named object a step can leave behind in a user schema: relations (tables,
100
+ # indexes, sequences, views, composite types), free-standing types (an array type
101
+ # Postgres makes for another type is skipped), functions and procedures,
102
+ # collations, statistics objects, and schemas themselves.
103
+ _SNAPSHOT = f"""
104
+ SELECT 'relation', c.oid::bigint, n.nspname, c.relname
105
+ FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE {_SYSTEM_NS}
106
+ UNION ALL
107
+ SELECT 'type', t.oid::bigint, n.nspname, t.typname
108
+ FROM pg_type t JOIN pg_namespace n ON n.oid = t.typnamespace
109
+ WHERE {_SYSTEM_NS} AND t.typrelid = 0
110
+ AND NOT EXISTS (SELECT 1 FROM pg_type e WHERE e.typarray = t.oid)
111
+ UNION ALL
112
+ SELECT 'function', p.oid::bigint, n.nspname, p.proname
113
+ FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace WHERE {_SYSTEM_NS}
114
+ UNION ALL
115
+ SELECT 'collation', o.oid::bigint, n.nspname, o.collname
116
+ FROM pg_collation o JOIN pg_namespace n ON n.oid = o.collnamespace WHERE {_SYSTEM_NS}
117
+ UNION ALL
118
+ SELECT 'statistics', s.oid::bigint, n.nspname, s.stxname
119
+ FROM pg_statistic_ext s JOIN pg_namespace n ON n.oid = s.stxnamespace WHERE {_SYSTEM_NS}
120
+ UNION ALL
121
+ SELECT 'schema', n.oid::bigint, n.nspname, n.nspname FROM pg_namespace n WHERE {_SYSTEM_NS}
122
+ """
123
+
124
+
125
+ def _snapshot(conn: Any) -> set[tuple]:
126
+ return set(conn.execute(_SNAPSHOT).fetchall())
127
+
128
+
129
+ def _violations(before: set[tuple], after: set[tuple], owner: str, schema: str) -> list[str]:
130
+ bad = []
131
+ for kind, _oid, nspname, name in sorted(after - before, key=lambda r: (r[2], r[3])):
132
+ if kind == "schema":
133
+ bad.append(f"schema {name}")
134
+ elif nspname != schema:
135
+ bad.append(f"{kind} {nspname}.{name} (outside schema {schema})")
136
+ elif name in RESERVED_NAMES:
137
+ bad.append(f"{kind} {name} (reserved)")
138
+ elif not (name == owner or name.startswith(owner + "_")):
139
+ bad.append(f"{kind} {name}")
140
+ return bad
141
+
142
+
143
+ def _lock(conn: Any, key: str) -> None:
144
+ conn.execute("SELECT pg_advisory_xact_lock(hashtextextended(%s, 0))", (key,))
145
+
146
+
147
+ def _bootstrap(conn: Any, schema: str) -> None:
148
+ """Create the schema and the platform tables if missing, under the schema lock.
149
+ Existence is checked first, so a role that may not create them can still use them
150
+ once they exist."""
151
+ _, sql = _psycopg()
152
+ with conn.transaction():
153
+ _lock(conn, f"capabilities_contract:{schema}")
154
+ exists = conn.execute("SELECT 1 FROM pg_namespace WHERE nspname = %s",
155
+ (schema,)).fetchone()
156
+ if not exists:
157
+ conn.execute(sql.SQL("CREATE SCHEMA {}").format(sql.Identifier(schema)))
158
+ ledger = conn.execute("SELECT to_regclass(%s)",
159
+ (f'"{schema}".{LEDGER_TABLE}',)).fetchone()[0]
160
+ if ledger is None:
161
+ conn.execute(sql.SQL(
162
+ "CREATE TABLE {}.{} (owner text NOT NULL, step text NOT NULL, "
163
+ "checksum text NOT NULL, applied_at timestamptz NOT NULL DEFAULT now(), "
164
+ "library_version text NOT NULL, PRIMARY KEY (owner, step))").format(
165
+ sql.Identifier(schema), sql.Identifier(LEDGER_TABLE)))
166
+ version = conn.execute("SELECT to_regclass(%s)",
167
+ (f'"{schema}".{VERSION_TABLE}',)).fetchone()[0]
168
+ if version is None:
169
+ conn.execute(sql.SQL(
170
+ "CREATE TABLE {}.{} (owner text PRIMARY KEY, major integer NOT NULL, "
171
+ "minor integer NOT NULL, updated_at timestamptz NOT NULL DEFAULT now())").format(
172
+ sql.Identifier(schema), sql.Identifier(VERSION_TABLE)))
173
+
174
+
175
+ def _stored_version(conn: Any, schema: str, owner: str) -> tuple[int, int] | None:
176
+ _, sql = _psycopg()
177
+ row = conn.execute(sql.SQL("SELECT major, minor FROM {}.{} WHERE owner = %s").format(
178
+ sql.Identifier(schema), sql.Identifier(VERSION_TABLE)), (owner,)).fetchone()
179
+ return (row[0], row[1]) if row else None
180
+
181
+
182
+ def _check_version(conn: Any, schema: str, owner: str, major: int, minor: int,
183
+ result: MigrateResult) -> tuple[int, int] | None:
184
+ stored = _stored_version(conn, schema, owner)
185
+ if stored is None:
186
+ return None
187
+ s_major, s_minor = stored
188
+ if s_major > major:
189
+ raise DbError("schema_too_new",
190
+ f"the store's {owner} tables are at schema version {s_major}.{s_minor}, "
191
+ f"newer than the {major}.{minor} this code knows",
192
+ f"update the release that owns the {owner} tables to one that knows "
193
+ f"schema major {s_major}")
194
+ if s_major == major and s_minor > minor:
195
+ warning = (f"the store's {owner} tables are at schema version {s_major}.{s_minor}, "
196
+ f"a newer minor than the {major}.{minor} this code knows; "
197
+ "it works, but an update is available")
198
+ if warning not in result.warnings:
199
+ result.warnings.append(warning)
200
+ return stored
201
+
202
+
203
+ def migrate(conn: Any, owner: str, steps: Iterable[Step | Sequence[str]], *,
204
+ major: int, minor: int, schema: str | None = None) -> MigrateResult:
205
+ """Apply `owner`'s steps that are not yet applied, in order, each once.
206
+
207
+ `conn` comes from `connect` (its bound schema is used) and must be idle. Each
208
+ step runs in its own transaction under a per-owner advisory lock, together with
209
+ its ledger row, so concurrent callers apply it exactly once. Refuses (DbError):
210
+ a stored major newer than `major` (`schema_too_new`), an applied step whose SQL
211
+ changed (`checksum_mismatch`), a step that creates an object not named
212
+ `<owner>`/`<owner>_*` in the schema (`naming_law`, rolled back), and a failing
213
+ step (`step_failed`, rolled back). A newer stored minor proceeds with a warning
214
+ in the result. Afterwards the caller's version is recorded unless the store's is
215
+ newer."""
216
+ psycopg, sql = _psycopg()
217
+ owner = check_owner(owner)
218
+ major, minor = _check_version_numbers(major, minor)
219
+ schema = check_schema_name(schema if schema is not None else bound_schema(conn))
220
+ plan = _normalise_steps(steps)
221
+ if conn.info.transaction_status != psycopg.pq.TransactionStatus.IDLE:
222
+ raise DbError("connection_busy", "migrate needs an idle connection",
223
+ "commit or roll back before migrating")
224
+ result = MigrateResult(owner=owner, schema=schema)
225
+ lock_key = f"capabilities_contract:{schema}:{owner}"
226
+ ledger = sql.SQL("{}.{}").format(sql.Identifier(schema), sql.Identifier(LEDGER_TABLE))
227
+ versions = sql.SQL("{}.{}").format(sql.Identifier(schema), sql.Identifier(VERSION_TABLE))
228
+
229
+ _bootstrap(conn, schema)
230
+ bind_search_path(conn, schema)
231
+ conn.commit()
232
+
233
+ for step in plan:
234
+ with conn.transaction():
235
+ _lock(conn, lock_key)
236
+ _check_version(conn, schema, owner, major, minor, result)
237
+ row = conn.execute(sql.SQL("SELECT checksum FROM {} WHERE owner = %s AND step = %s")
238
+ .format(ledger), (owner, step.id)).fetchone()
239
+ if row is not None:
240
+ if row[0] != step.checksum:
241
+ raise DbError("checksum_mismatch",
242
+ f"step {step.id} of {owner} was applied with different SQL",
243
+ "never edit an applied step; add a new step instead")
244
+ result.skipped.append(step.id)
245
+ continue
246
+ before = _snapshot(conn)
247
+ try:
248
+ with conn.transaction():
249
+ conn.execute(step.sql)
250
+ except psycopg.Error as exc:
251
+ raise DbError("step_failed", f"step {step.id} of {owner} failed: {exc}",
252
+ "the step was rolled back; fix it and migrate again") from exc
253
+ if conn.info.transaction_status != psycopg.pq.TransactionStatus.INTRANS:
254
+ raise DbError("step_failed",
255
+ f"step {step.id} of {owner} ended its own transaction",
256
+ "a step may not COMMIT or ROLLBACK")
257
+ bind_search_path(conn, schema)
258
+ bad = _violations(before, _snapshot(conn), owner, schema)
259
+ if bad:
260
+ raise DbError("naming_law",
261
+ f"step {step.id} of {owner} creates objects not named "
262
+ f"{owner}_*: {', '.join(bad)}",
263
+ f"name everything the step creates {owner} or {owner}_* "
264
+ f"inside schema {schema}; the step was rolled back")
265
+ conn.execute(sql.SQL("INSERT INTO {} (owner, step, checksum, library_version) "
266
+ "VALUES (%s, %s, %s, %s)").format(ledger),
267
+ (owner, step.id, step.checksum, __version__))
268
+ result.applied.append(step.id)
269
+
270
+ with conn.transaction():
271
+ _lock(conn, lock_key)
272
+ stored = _check_version(conn, schema, owner, major, minor, result)
273
+ if stored is None or (major, minor) >= stored:
274
+ conn.execute(sql.SQL(
275
+ "INSERT INTO {} (owner, major, minor) VALUES (%s, %s, %s) "
276
+ "ON CONFLICT (owner) DO UPDATE SET major = EXCLUDED.major, "
277
+ "minor = EXCLUDED.minor, updated_at = now()").format(versions),
278
+ (owner, major, minor))
279
+ result.major, result.minor = major, minor
280
+ else:
281
+ result.major, result.minor = stored
282
+ return result
@@ -0,0 +1,184 @@
1
+ """The machine's store setting, read exactly as the manager's store tier reads it.
2
+
3
+ The manager is the one writer: `capabilities store set` writes the non-secret values
4
+ to `$XDG_CONFIG_HOME/capabilities/store.json` and the password to
5
+ `$XDG_CONFIG_HOME/capabilities/credentials.env` as `CAPABILITIES_STORE_PASSWORD`.
6
+ This module reads both and writes nothing. `CAPABILITIES_STORE_URL`, when set, is the
7
+ store in force and wins over the setting.
8
+
9
+ A `capabilities.store.v1` setting binds the default schema `agentkit`. A
10
+ `capabilities.store.v2` setting may name another one in `db_schema`; the document's
11
+ own `schema` key already holds the setting's id, so the schema name has its own key.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import os
18
+ import re
19
+ from dataclasses import dataclass, field
20
+ from pathlib import Path
21
+ from urllib.parse import urlparse
22
+
23
+ from capabilities_contract.db._errors import DbError
24
+
25
+ SETTING_SCHEMA_V1 = "capabilities.store.v1"
26
+ SETTING_SCHEMA_V2 = "capabilities.store.v2"
27
+ SETTING_SCHEMAS = (SETTING_SCHEMA_V1, SETTING_SCHEMA_V2)
28
+ PASSWORD_KEY = "CAPABILITIES_STORE_PASSWORD"
29
+ URL_ENV = "CAPABILITIES_STORE_URL"
30
+ SSLMODES = ("require", "verify-ca", "verify-full")
31
+ SSLMODES_REFUSED = ("disable", "allow", "prefer")
32
+ SETTING_FIELDS = ("host", "port", "database", "user", "sslmode", "sslrootcert")
33
+ SCHEMA_FIELD = "db_schema"
34
+ DEFAULT_SCHEMA = "agentkit"
35
+
36
+ _IDENTIFIER = re.compile(r"[a-z_][a-z0-9_]{0,62}")
37
+ _SYSTEM_SCHEMAS = ("public", "information_schema")
38
+
39
+ NOT_CONFIGURED_HINT = "run capabilities store set"
40
+
41
+
42
+ def check_schema_name(name: object) -> str:
43
+ """A schema name the library may bind: a lowercase identifier, never `public`
44
+ and never a system schema."""
45
+ if not isinstance(name, str) or not _IDENTIFIER.fullmatch(name):
46
+ raise DbError("bad_schema_name",
47
+ f"schema name {name!r} is not a lowercase identifier",
48
+ "use letters, digits and underscores, starting with a letter or _")
49
+ if name in _SYSTEM_SCHEMAS or name.startswith("pg_"):
50
+ raise DbError("bad_schema_name", f"schema {name!r} is reserved",
51
+ "name a schema of the store's own, such as agentkit")
52
+ return name
53
+
54
+
55
+ @dataclass(frozen=True)
56
+ class Setting:
57
+ """Where the store is and which schema it binds.
58
+
59
+ Either `url` (from `CAPABILITIES_STORE_URL`) or the host fields are set. `source`
60
+ is `CAPABILITIES_STORE_URL` or the setting file's path. The password and URL are
61
+ never shown in the repr."""
62
+
63
+ schema: str = DEFAULT_SCHEMA
64
+ source: str = ""
65
+ url: str | None = field(default=None, repr=False)
66
+ host: str | None = None
67
+ port: int | None = None
68
+ database: str | None = None
69
+ user: str | None = None
70
+ sslmode: str | None = None
71
+ sslrootcert: str | None = None
72
+ password: str | None = field(default=None, repr=False)
73
+
74
+ def connect_kwargs(self) -> dict:
75
+ """Arguments for `psycopg.connect`: a conninfo string, or keyword values."""
76
+ if self.url is not None:
77
+ return {"conninfo": self.url}
78
+ out = {"host": self.host, "port": self.port, "dbname": self.database,
79
+ "user": self.user, "sslmode": self.sslmode}
80
+ if self.sslrootcert:
81
+ out["sslrootcert"] = self.sslrootcert
82
+ if self.password:
83
+ out["password"] = self.password
84
+ return out
85
+
86
+
87
+ def setting_files(config_home: Path | str | None = None) -> tuple[Path, Path]:
88
+ """The setting file and the password file, in that order."""
89
+ home = Path(config_home or os.environ.get("XDG_CONFIG_HOME")
90
+ or os.path.join(os.path.expanduser("~"), ".config"))
91
+ return (home / "capabilities" / "store.json",
92
+ home / "capabilities" / "credentials.env")
93
+
94
+
95
+ def check_setting(values: dict) -> dict:
96
+ """The setting's non-secret values, checked and normalised, or DbError. The same
97
+ rules as the manager's store tier: no unknown field, host/database/user without
98
+ whitespace, port 1-65535, sslmode at least `require`."""
99
+ if not isinstance(values, dict):
100
+ raise DbError("bad_store_setting", "the store setting is not an object")
101
+ unknown = sorted(set(values) - set(SETTING_FIELDS))
102
+ if unknown:
103
+ raise DbError("bad_store_setting",
104
+ f"the store setting carries unknown fields: {', '.join(unknown)}")
105
+ out: dict = {}
106
+ for name in ("host", "database", "user"):
107
+ value = values.get(name)
108
+ if not isinstance(value, str) or not value or any(
109
+ ch.isspace() or ch == "\0" for ch in value):
110
+ raise DbError("bad_store_setting",
111
+ f"the store setting needs a {name} with no whitespace")
112
+ out[name] = value
113
+ port = values.get("port", 5432)
114
+ if isinstance(port, str) and port.isdigit():
115
+ port = int(port)
116
+ if isinstance(port, bool) or not isinstance(port, int) or not 0 < port < 65536:
117
+ raise DbError("bad_store_setting", "the store port must be 1-65535")
118
+ out["port"] = port
119
+ sslmode = values.get("sslmode")
120
+ if sslmode in SSLMODES_REFUSED:
121
+ raise DbError("sslmode_too_weak",
122
+ f"sslmode {sslmode!r} lets the store be reached without TLS",
123
+ f"use one of {', '.join(SSLMODES)}")
124
+ if sslmode not in SSLMODES:
125
+ raise DbError("bad_store_setting", f"unknown sslmode {sslmode!r}",
126
+ f"use one of {', '.join(SSLMODES)}")
127
+ out["sslmode"] = sslmode
128
+ root = values.get("sslrootcert")
129
+ if root is not None:
130
+ if not isinstance(root, str) or not root or "\n" in root:
131
+ raise DbError("bad_store_setting",
132
+ "sslrootcert must be a certificate file path or `system`")
133
+ out["sslrootcert"] = root
134
+ return out
135
+
136
+
137
+ def read_setting(config_home: Path | str | None = None) -> Setting:
138
+ """The store in force on this machine.
139
+
140
+ `CAPABILITIES_STORE_URL` first, then the manager's setting. With neither, raises
141
+ DbError `store_not_configured`. Reads only; never creates a file."""
142
+ url = os.environ.get(URL_ENV)
143
+ if url:
144
+ scheme = urlparse(url).scheme
145
+ if scheme not in ("postgres", "postgresql"):
146
+ raise DbError("store_not_postgres",
147
+ f"{URL_ENV} names a {scheme or 'file'} store, not Postgres",
148
+ f"point {URL_ENV} at a postgresql:// URL or unset it")
149
+ return Setting(url=url, schema=DEFAULT_SCHEMA, source=URL_ENV)
150
+ setting_file, password_file = setting_files(config_home)
151
+ try:
152
+ raw = setting_file.read_text()
153
+ except FileNotFoundError:
154
+ raise DbError("store_not_configured", "this machine has no store setting",
155
+ NOT_CONFIGURED_HINT) from None
156
+ except OSError as exc:
157
+ raise DbError("store_setting_unreadable",
158
+ f"cannot read the store setting {setting_file}: {exc}") from exc
159
+ try:
160
+ data = json.loads(raw)
161
+ except ValueError as exc:
162
+ raise DbError("bad_store_setting", f"{setting_file} is not a store setting",
163
+ "rewrite it with `capabilities store set`") from exc
164
+ if not isinstance(data, dict) or data.get("schema") not in SETTING_SCHEMAS:
165
+ raise DbError("bad_store_setting",
166
+ f"{setting_file} is not a {' or '.join(SETTING_SCHEMAS)} setting",
167
+ "rewrite it with `capabilities store set`")
168
+ values = check_setting({k: v for k, v in data.items() if k in SETTING_FIELDS})
169
+ schema = DEFAULT_SCHEMA
170
+ if data["schema"] == SETTING_SCHEMA_V2 and data.get(SCHEMA_FIELD) is not None:
171
+ schema = check_schema_name(data[SCHEMA_FIELD])
172
+ password = None
173
+ try:
174
+ lines = password_file.read_text().splitlines()
175
+ except FileNotFoundError:
176
+ lines = []
177
+ except OSError as exc:
178
+ raise DbError("store_setting_unreadable",
179
+ f"cannot read the store password file {password_file}: {exc}") from exc
180
+ prefix = PASSWORD_KEY + "="
181
+ for line in lines:
182
+ if line.startswith(prefix):
183
+ password = line[len(prefix):] or None
184
+ return Setting(schema=schema, source=str(setting_file), password=password, **values)
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
@@ -0,0 +1,85 @@
1
+ Metadata-Version: 2.5
2
+ Name: capabilities-contract
3
+ Version: 0.1.0
4
+ Summary: The shared database layer of the capabilities contract: read the machine's store setting, connect bound to its schema, and migrate each owner's tables once under a ledger.
5
+ Project-URL: Homepage, https://github.com/ai-cluster-one/capabilities-contract
6
+ Project-URL: Source, https://github.com/ai-cluster-one/capabilities-contract
7
+ Author: ai-cluster-one
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ Keywords: capabilities,migrations,postgres,psycopg,schema
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: Apache Software License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3 :: Only
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Topic :: Database
17
+ Classifier: Topic :: Software Development :: Libraries
18
+ Requires-Python: >=3.11
19
+ Requires-Dist: psycopg[binary]<4,>=3.2
20
+ Provides-Extra: dev
21
+ Requires-Dist: pytest>=8; extra == 'dev'
22
+ Requires-Dist: ruff>=0.6; extra == 'dev'
23
+ Description-Content-Type: text/markdown
24
+
25
+ # capabilities-contract
26
+
27
+ The capabilities contract as a Python library. Its first part, `capabilities_contract.db`, is the one way the capabilities manager, its capabilities and ContextKit reach the shared Postgres database: read the machine's store setting, connect bound to its schema, and migrate each owner's tables once under a ledger. It does nothing else: no SQLite, no project registry, no records.
28
+
29
+ ## Install
30
+
31
+ ```
32
+ pip install capabilities-contract
33
+ ```
34
+
35
+ Its one dependency is `psycopg[binary]>=3.2,<4`, imported lazily: `import capabilities_contract.db` does not import psycopg, only `connect` and `migrate` do. In a PEP 723 script, pin the exact version:
36
+
37
+ ```python
38
+ # /// script
39
+ # dependencies = ["capabilities-contract==0.1.0"]
40
+ # ///
41
+ ```
42
+
43
+ ## The store setting
44
+
45
+ `read_setting()` returns the store in force as a `Setting`, reading and never writing. `CAPABILITIES_STORE_URL`, when set, wins and must be a `postgresql://` URL. Otherwise it reads the manager's setting, written only by `capabilities store set`: the non-secret values in `$XDG_CONFIG_HOME/capabilities/store.json` and the password as `CAPABILITIES_STORE_PASSWORD` in `$XDG_CONFIG_HOME/capabilities/credentials.env`. The fields and their checks are the manager's: `host`, `database`, `user` with no whitespace, `port` 1-65535 (default 5432), `sslmode` one of `require`, `verify-ca`, `verify-full` (`disable`, `allow` and `prefer` are refused as `sslmode_too_weak`), and an optional `sslrootcert`. A `capabilities.store.v1` setting binds the schema `agentkit`; a `capabilities.store.v2` setting may name another schema in `db_schema` (the document's `schema` key is its id). The URL override binds `agentkit`. With neither a setting nor the override, it raises `DbError("store_not_configured", ..., "run capabilities store set")`.
46
+
47
+ ## Connect
48
+
49
+ ```python
50
+ from capabilities_contract.db import DbError, Step, connect, migrate
51
+
52
+ conn = connect(application_name="automations")
53
+ ```
54
+
55
+ `connect(*, application_name, setting=None)` returns a psycopg 3 connection whose `search_path` is the configured schema alone, never `public`, so unqualified names land in that schema. The schema need not exist yet: `migrate` creates it. Pass `setting=` to use a `Setting` other than the machine's.
56
+
57
+ ## Migrate
58
+
59
+ ```python
60
+ result = migrate(conn, "automations", [
61
+ Step("0001-runs", "CREATE TABLE automations_runs (id bigint PRIMARY KEY)"),
62
+ ("0002-runs-host", "ALTER TABLE automations_runs ADD COLUMN host text"),
63
+ ], major=1, minor=1)
64
+ for warning in result.warnings:
65
+ print(warning)
66
+ ```
67
+
68
+ `migrate(conn, owner, steps, *, major, minor)` applies each step that is not yet applied, in order, once. The owner is the tool that owns the tables, a lowercase identifier without underscores. The first call creates the schema and two platform tables in it: `schema_ledger(owner, step, checksum, applied_at, library_version)` and `schema_version(owner, major, minor, updated_at)`. Each step runs in its own transaction under a per-owner advisory lock together with its ledger row, so concurrent processes apply it exactly once. It returns a `MigrateResult` with `applied`, `skipped`, `warnings`, `major` and `minor`.
69
+
70
+ It refuses with a `DbError`, rolling the step back: an applied step whose SQL changed (`checksum_mismatch`); a step that creates a relation, index, sequence, type, function, collation, statistics object or schema not named `<owner>` or `<owner>_*` inside the configured schema, or named `schema_ledger` or `schema_version` (`naming_law`); a step that fails or ends its own transaction (`step_failed`). A step cannot use statements that refuse a transaction, such as `CREATE INDEX CONCURRENTLY`.
71
+
72
+ The version rule lets tools at different releases share one database. When the store records a newer major for the owner than the caller's `major`, `migrate` refuses with `schema_too_new` before applying anything, and the hint says to update. When it records the same major with a newer minor, it proceeds and adds a warning to `result.warnings`, keeping the stored version. Otherwise it records the caller's version.
73
+
74
+ ## Errors
75
+
76
+ Every failure is a `DbError` with `slug` (stable, for the caller to map to an exit code), `message` and `hint` (possibly `None`). Slugs: `store_not_configured`, `store_not_postgres`, `store_setting_unreadable`, `bad_store_setting`, `sslmode_too_weak`, `bad_schema_name`, `store_unreachable`, `driver_missing`, `bad_application_name`, `bad_owner`, `bad_version`, `bad_step`, `connection_busy`, `checksum_mismatch`, `naming_law`, `step_failed`, `schema_too_new`.
77
+
78
+ ## Development
79
+
80
+ ```
81
+ uv venv && uv pip install -e ".[dev]"
82
+ uv run pytest
83
+ ```
84
+
85
+ The suite starts a throwaway PostgreSQL cluster with TLS under a temporary directory (`initdb` and `pg_ctl` on `PATH`, or in `$PG_BIN`) on a random port. Set `CAPABILITIES_CONTRACT_TEST_URL` to a TLS-enabled server's admin URL to run it against that server instead, as CI does. The tests that compare the setting reader with the manager's own run only when `CAPABILITIES_STORE_TIER` names the manager's `contract/store.py`; otherwise they skip.
@@ -0,0 +1,11 @@
1
+ capabilities_contract/__init__.py,sha256=Rgfd5Kv-bgbeq2-MW3XY3DLCpATD0xi502Tq37JZM84,174
2
+ capabilities_contract/version.py,sha256=kUR5RAFc7HCeiqdlX36dZOHkUI5wI6V_43RpEcD8b-0,22
3
+ capabilities_contract/db/__init__.py,sha256=BZngl-knYaByJwzrNdzltwjQSt6cYAibJO4YEsvIfls,796
4
+ capabilities_contract/db/_connect.py,sha256=bmk28wfifNH4MaxpgBtzqYAnBhvVmYihqTWyxOPXvFw,2447
5
+ capabilities_contract/db/_errors.py,sha256=JFFTm-pKydSQHKuottbgD55_hqZcjbNDmld7OEkJ1ww,483
6
+ capabilities_contract/db/_migrate.py,sha256=C23mfTQJ49RbG0P1E95rRYXwvoxadcM_nRvXNgvuZF8,13237
7
+ capabilities_contract/db/_setting.py,sha256=BjlQMHW0XeQ8bmxTpezjVSaDHQoRlKz1WIM-WuSHeOE,8180
8
+ capabilities_contract-0.1.0.dist-info/METADATA,sha256=bdf35XNbC93zMTKCz5qzy7xJlmcB_BXixSAdSEHVdHc,6162
9
+ capabilities_contract-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
10
+ capabilities_contract-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
11
+ capabilities_contract-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.