present-day 0.14.0__tar.gz

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.
Files changed (106) hide show
  1. present_day-0.14.0/LICENSE +177 -0
  2. present_day-0.14.0/PKG-INFO +52 -0
  3. present_day-0.14.0/PYPI.md +13 -0
  4. present_day-0.14.0/pyproject.toml +40 -0
  5. present_day-0.14.0/setup.cfg +4 -0
  6. present_day-0.14.0/src/present_day/__init__.py +4 -0
  7. present_day-0.14.0/src/present_day/agent.py +58 -0
  8. present_day-0.14.0/src/present_day/backends.py +87 -0
  9. present_day-0.14.0/src/present_day/canon.py +52 -0
  10. present_day-0.14.0/src/present_day/claims.py +148 -0
  11. present_day-0.14.0/src/present_day/cli.py +1045 -0
  12. present_day-0.14.0/src/present_day/client.py +122 -0
  13. present_day-0.14.0/src/present_day/cloud/__init__.py +1 -0
  14. present_day-0.14.0/src/present_day/cloud/app.py +1041 -0
  15. present_day-0.14.0/src/present_day/cloud/backup.py +199 -0
  16. present_day-0.14.0/src/present_day/cloud/db.py +168 -0
  17. present_day-0.14.0/src/present_day/cloud/mail.py +53 -0
  18. present_day-0.14.0/src/present_day/cloud/metrics.py +112 -0
  19. present_day-0.14.0/src/present_day/cloud/migrate.py +90 -0
  20. present_day-0.14.0/src/present_day/cloud/oidc.py +140 -0
  21. present_day-0.14.0/src/present_day/cloud/pgdb.py +117 -0
  22. present_day-0.14.0/src/present_day/cloud/plans.py +21 -0
  23. present_day-0.14.0/src/present_day/cloud/ratelimit.py +66 -0
  24. present_day-0.14.0/src/present_day/cloud/remote.py +220 -0
  25. present_day-0.14.0/src/present_day/cloud/rotate.py +64 -0
  26. present_day-0.14.0/src/present_day/cloud/saml.py +87 -0
  27. present_day-0.14.0/src/present_day/cloud/security.py +162 -0
  28. present_day-0.14.0/src/present_day/cloud/service.py +1858 -0
  29. present_day-0.14.0/src/present_day/cloud/settings.py +159 -0
  30. present_day-0.14.0/src/present_day/cloud/stripe.py +67 -0
  31. present_day-0.14.0/src/present_day/cloud/web/__init__.py +0 -0
  32. present_day-0.14.0/src/present_day/cloud/web/app.html +22 -0
  33. present_day-0.14.0/src/present_day/cloud/web/cabinet.css +136 -0
  34. present_day-0.14.0/src/present_day/cloud/web/cabinet.js +868 -0
  35. present_day-0.14.0/src/present_day/cloud/web/login.html +54 -0
  36. present_day-0.14.0/src/present_day/cloud/web/login.js +111 -0
  37. present_day-0.14.0/src/present_day/crypto.py +105 -0
  38. present_day-0.14.0/src/present_day/engine.py +328 -0
  39. present_day-0.14.0/src/present_day/evalkit.py +156 -0
  40. present_day-0.14.0/src/present_day/evidence.py +284 -0
  41. present_day-0.14.0/src/present_day/export.py +118 -0
  42. present_day-0.14.0/src/present_day/gateway.py +496 -0
  43. present_day-0.14.0/src/present_day/home.py +92 -0
  44. present_day-0.14.0/src/present_day/injection.py +355 -0
  45. present_day-0.14.0/src/present_day/integrations/__init__.py +119 -0
  46. present_day-0.14.0/src/present_day/integrations/langchain.py +19 -0
  47. present_day-0.14.0/src/present_day/integrations/llamaindex.py +19 -0
  48. present_day-0.14.0/src/present_day/integrations/openai_agents.py +20 -0
  49. present_day-0.14.0/src/present_day/ledger.py +370 -0
  50. present_day-0.14.0/src/present_day/llm.py +224 -0
  51. present_day-0.14.0/src/present_day/mcp_server.py +143 -0
  52. present_day-0.14.0/src/present_day/merkle.py +168 -0
  53. present_day-0.14.0/src/present_day/node.py +278 -0
  54. present_day-0.14.0/src/present_day/recorder.py +151 -0
  55. present_day-0.14.0/src/present_day/redteam.py +220 -0
  56. present_day-0.14.0/src/present_day/rules.py +256 -0
  57. present_day-0.14.0/src/present_day/soc.py +528 -0
  58. present_day-0.14.0/src/present_day/soc_demo.py +120 -0
  59. present_day-0.14.0/src/present_day/stores.py +310 -0
  60. present_day-0.14.0/src/present_day/sync.py +70 -0
  61. present_day-0.14.0/src/present_day/trust.py +379 -0
  62. present_day-0.14.0/src/present_day/watch.py +386 -0
  63. present_day-0.14.0/src/present_day/web/__init__.py +0 -0
  64. present_day-0.14.0/src/present_day/web/dashboard.css +22 -0
  65. present_day-0.14.0/src/present_day/web/dashboard.js +107 -0
  66. present_day-0.14.0/src/present_day/web/index.html +34 -0
  67. present_day-0.14.0/src/present_day.egg-info/PKG-INFO +52 -0
  68. present_day-0.14.0/src/present_day.egg-info/SOURCES.txt +104 -0
  69. present_day-0.14.0/src/present_day.egg-info/dependency_links.txt +1 -0
  70. present_day-0.14.0/src/present_day.egg-info/entry_points.txt +3 -0
  71. present_day-0.14.0/src/present_day.egg-info/requires.txt +32 -0
  72. present_day-0.14.0/src/present_day.egg-info/top_level.txt +1 -0
  73. present_day-0.14.0/tests/test_agent_demo.py +44 -0
  74. present_day-0.14.0/tests/test_agent_flow.py +130 -0
  75. present_day-0.14.0/tests/test_billing.py +232 -0
  76. present_day-0.14.0/tests/test_cli_mcp.py +142 -0
  77. present_day-0.14.0/tests/test_cloud.py +490 -0
  78. present_day-0.14.0/tests/test_cloud_web.py +30 -0
  79. present_day-0.14.0/tests/test_deliveries.py +210 -0
  80. present_day-0.14.0/tests/test_email_sso.py +312 -0
  81. present_day-0.14.0/tests/test_evalkit.py +103 -0
  82. present_day-0.14.0/tests/test_evidence_rules.py +274 -0
  83. present_day-0.14.0/tests/test_features.py +478 -0
  84. present_day-0.14.0/tests/test_gateway.py +287 -0
  85. present_day-0.14.0/tests/test_hardening.py +77 -0
  86. present_day-0.14.0/tests/test_incremental.py +63 -0
  87. present_day-0.14.0/tests/test_injection.py +92 -0
  88. present_day-0.14.0/tests/test_integrations.py +66 -0
  89. present_day-0.14.0/tests/test_js_interop.py +183 -0
  90. present_day-0.14.0/tests/test_ledger.py +159 -0
  91. present_day-0.14.0/tests/test_llm.py +309 -0
  92. present_day-0.14.0/tests/test_loadtest.py +22 -0
  93. present_day-0.14.0/tests/test_monitoring.py +65 -0
  94. present_day-0.14.0/tests/test_node.py +128 -0
  95. present_day-0.14.0/tests/test_ops.py +278 -0
  96. present_day-0.14.0/tests/test_postgres.py +212 -0
  97. present_day-0.14.0/tests/test_privacy.py +257 -0
  98. present_day-0.14.0/tests/test_ratelimit.py +165 -0
  99. present_day-0.14.0/tests/test_saml.py +188 -0
  100. present_day-0.14.0/tests/test_scale.py +87 -0
  101. present_day-0.14.0/tests/test_security.py +212 -0
  102. present_day-0.14.0/tests/test_soc.py +495 -0
  103. present_day-0.14.0/tests/test_timetravel.py +66 -0
  104. present_day-0.14.0/tests/test_transfer.py +111 -0
  105. present_day-0.14.0/tests/test_trust.py +137 -0
  106. present_day-0.14.0/tests/test_watch_redteam.py +53 -0
@@ -0,0 +1,177 @@
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
@@ -0,0 +1,52 @@
1
+ Metadata-Version: 2.4
2
+ Name: present-day
3
+ Version: 0.14.0
4
+ Summary: Tamper-evident signed memory, provenance and trust for AI agents
5
+ Author: Ruslan Tiahniienko
6
+ License-Expression: Apache-2.0
7
+ Keywords: ai-agents,memory,provenance,ed25519,merkle,mcp
8
+ Classifier: Development Status :: 4 - Beta
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Topic :: Security :: Cryptography
11
+ Requires-Python: >=3.10
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: cryptography>=42
15
+ Provides-Extra: mcp
16
+ Requires-Dist: mcp>=1.2; extra == "mcp"
17
+ Provides-Extra: web
18
+ Requires-Dist: fastapi>=0.110; extra == "web"
19
+ Requires-Dist: uvicorn>=0.27; extra == "web"
20
+ Provides-Extra: saml
21
+ Requires-Dist: python3-saml>=1.16; extra == "saml"
22
+ Provides-Extra: postgres
23
+ Requires-Dist: psycopg[binary]>=3.2; extra == "postgres"
24
+ Requires-Dist: psycopg-pool>=3.2; extra == "postgres"
25
+ Provides-Extra: langchain
26
+ Requires-Dist: langchain-core>=0.3; extra == "langchain"
27
+ Provides-Extra: llamaindex
28
+ Requires-Dist: llama-index-core>=0.12; extra == "llamaindex"
29
+ Provides-Extra: openai-agents
30
+ Requires-Dist: openai-agents>=0.2; extra == "openai-agents"
31
+ Provides-Extra: dev
32
+ Requires-Dist: pytest>=8; extra == "dev"
33
+ Requires-Dist: httpx>=0.27; extra == "dev"
34
+ Requires-Dist: build; extra == "dev"
35
+ Requires-Dist: twine; extra == "dev"
36
+ Requires-Dist: pip-audit; extra == "dev"
37
+ Requires-Dist: cyclonedx-bom; extra == "dev"
38
+ Dynamic: license-file
39
+
40
+ # Present Day
41
+
42
+ Tamper-evident, signed memory for AI agents: a hash-chained Ed25519 ledger, a trust graph with quorum and anti-Sybil rules,
43
+ drift and injection detection, offline-verifiable evidence bundles, a local node, a hosted cabinet, a CLI and an MCP server.
44
+
45
+ ```
46
+ pip install present-day # core, CLI
47
+ pip install "present-day[mcp]" # MCP server for Claude Desktop, Cursor, ...
48
+ pip install "present-day[web]" # hosted cabinet
49
+ present-day init && present-day redteam
50
+ ```
51
+
52
+ Licensed under Apache-2.0.
@@ -0,0 +1,13 @@
1
+ # Present Day
2
+
3
+ Tamper-evident, signed memory for AI agents: a hash-chained Ed25519 ledger, a trust graph with quorum and anti-Sybil rules,
4
+ drift and injection detection, offline-verifiable evidence bundles, a local node, a hosted cabinet, a CLI and an MCP server.
5
+
6
+ ```
7
+ pip install present-day # core, CLI
8
+ pip install "present-day[mcp]" # MCP server for Claude Desktop, Cursor, ...
9
+ pip install "present-day[web]" # hosted cabinet
10
+ present-day init && present-day redteam
11
+ ```
12
+
13
+ Licensed under Apache-2.0.
@@ -0,0 +1,40 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "present-day"
7
+ version = "0.14.0"
8
+ description = "Tamper-evident signed memory, provenance and trust for AI agents"
9
+ requires-python = ">=3.10"
10
+ license = "Apache-2.0"
11
+ license-files = ["LICENSE"]
12
+ authors = [{name = "Ruslan Tiahniienko"}]
13
+ readme = "PYPI.md"
14
+ keywords = ["ai-agents", "memory", "provenance", "ed25519", "merkle", "mcp"]
15
+ classifiers = ["Development Status :: 4 - Beta", "Intended Audience :: Developers", "Topic :: Security :: Cryptography"]
16
+
17
+ dependencies = ["cryptography>=42"]
18
+
19
+ [project.optional-dependencies]
20
+ mcp = ["mcp>=1.2"]
21
+ web = ["fastapi>=0.110", "uvicorn>=0.27"]
22
+ saml = ["python3-saml>=1.16"]
23
+ postgres = ["psycopg[binary]>=3.2", "psycopg-pool>=3.2"]
24
+ langchain = ["langchain-core>=0.3"]
25
+ llamaindex = ["llama-index-core>=0.12"]
26
+ openai-agents = ["openai-agents>=0.2"]
27
+ dev = ["pytest>=8", "httpx>=0.27", "build", "twine", "pip-audit", "cyclonedx-bom"]
28
+
29
+ [project.scripts]
30
+ present-day = "present_day.cli:main"
31
+ p7 = "present_day.cli:main"
32
+
33
+ [tool.setuptools.packages.find]
34
+ where = ["src"]
35
+
36
+ [tool.setuptools.package-data]
37
+ present_day = ["web/*", "cloud/web/*"]
38
+
39
+ [tool.pytest.ini_options]
40
+ testpaths = ["tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,4 @@
1
+ """Present Day: tamper-evident signed memory and provenance for AI agents (protocol P7)."""
2
+
3
+ __version__ = "0.14.0"
4
+ PROTOCOL = "P7/1"
@@ -0,0 +1,58 @@
1
+ """Agent home: the agent's own signing key plus the cabinet connection it should use.
2
+
3
+ The private key never leaves this directory; the cabinet only ever sees signed entries.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ import os
10
+ from pathlib import Path
11
+
12
+ from .client import CloudClient
13
+ from .crypto import NAME_RE, Identity
14
+
15
+
16
+ class AgentError(Exception):
17
+ pass
18
+
19
+
20
+ def default_path() -> Path:
21
+ return Path(os.environ.get("P7_AGENT_HOME") or Path.home() / ".present-day-agent")
22
+
23
+
24
+ class AgentHome:
25
+ def __init__(self, path: str | Path | None = None):
26
+ self.path = Path(path) if path else default_path()
27
+ self.cfg_path = self.path / "agent.json"
28
+
29
+ def exists(self) -> bool:
30
+ return self.cfg_path.exists()
31
+
32
+ def init(self, name: str, url: str, token: str, workspace: str) -> Identity:
33
+ if not NAME_RE.match(name):
34
+ raise AgentError("name must match [A-Za-z0-9_-]{1,32}")
35
+ if self.exists():
36
+ raise AgentError(f"{self.path} is already initialised")
37
+ self.path.mkdir(parents=True, exist_ok=True, mode=0o700)
38
+ os.chmod(self.path, 0o700)
39
+ ident = Identity.generate()
40
+ ident.save(self.path / "agent.pem", os.environ.get("P7_PASSPHRASE") or None)
41
+ cfg = {"name": name, "url": url.rstrip("/"), "workspace": workspace, "token": token}
42
+ fd = os.open(self.cfg_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
43
+ with os.fdopen(fd, "w") as f:
44
+ json.dump(cfg, f, indent=2)
45
+ return ident
46
+
47
+ def config(self) -> dict:
48
+ try:
49
+ return json.loads(self.cfg_path.read_text())
50
+ except (OSError, ValueError) as e:
51
+ raise AgentError(f"agent not initialised in {self.path}: run `present-day agent init`") from e
52
+
53
+ def identity(self) -> Identity:
54
+ return Identity.load(self.path / "agent.pem", os.environ.get("P7_PASSPHRASE") or None)
55
+
56
+ def client(self) -> CloudClient:
57
+ c = self.config()
58
+ return CloudClient(c["url"], c["token"], c["workspace"], self.identity())
@@ -0,0 +1,87 @@
1
+ """Memory backends shared by the MCP server and the framework integrations (no optional dependencies).
2
+
3
+ * local : a node home on this machine (PRESENT_DAY_HOME, key P7_IDENTITY, default "agent")
4
+ * cloud : a hosted workspace; the agent signs with its own key and authenticates with an API key
5
+ (P7_AGENT_HOME, created by `present-day agent init`)
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from .agent import AgentHome
11
+ from .home import Home
12
+
13
+
14
+ class LocalBackend:
15
+ def __init__(self, home: Home, identity_name: str):
16
+ self.engine, self._home, self._name = home.engine(), home, identity_name
17
+
18
+ def _me(self):
19
+ return self._home.identity(self._name)
20
+
21
+ def remember(self, subject, predicate, obj, confidence, source_uri, supersedes) -> dict:
22
+ e = self.engine.claim(self._me(), subject, predicate, obj, confidence=confidence,
23
+ sources=[{"uri": source_uri}] if source_uri else None,
24
+ supersedes=[supersedes] if supersedes else None)
25
+ return {"entry": e.entry_hash, "seq": e.seq}
26
+
27
+ def recall(self, subject, predicate, status, limit) -> list[dict]:
28
+ return self.engine.query(subject=subject or None, predicate=predicate or None,
29
+ status=status or None, limit=limit)
30
+
31
+ def attest(self, target, stance, note) -> dict:
32
+ e = self.engine.attest(self._me(), target, stance, note)
33
+ return {"entry": e.entry_hash, "seq": e.seq}
34
+
35
+ def history(self, subject, predicate) -> list[dict]:
36
+ return self.engine.history(subject, predicate)
37
+
38
+ def provenance(self, entry) -> dict:
39
+ return self.engine.provenance(entry)
40
+
41
+ def verify(self) -> dict:
42
+ return self.engine.verify()
43
+
44
+ def alerts(self) -> list[dict]:
45
+ return [a.to_dict() for a in self.engine.alerts()]
46
+
47
+ def receipt(self, subject, predicate, question, answer) -> dict:
48
+ return self.engine.answer_receipt(subject, predicate, question, answer, self._me())
49
+
50
+ def evidence(self, subject, predicate) -> dict:
51
+ return self.engine.evidence_for(subject, predicate)
52
+
53
+
54
+ class CloudBackend:
55
+ def __init__(self, agent: AgentHome):
56
+ self.c = agent.client()
57
+
58
+ def remember(self, subject, predicate, obj, confidence, source_uri, supersedes) -> dict:
59
+ r = self.c.claim(subject, predicate, obj, confidence=confidence,
60
+ sources=[{"uri": source_uri}] if source_uri else None,
61
+ supersedes=[supersedes] if supersedes else None)
62
+ return {"entry": r["entry_hash"], "seq": r["seq"]}
63
+
64
+ def recall(self, subject, predicate, status, limit) -> list[dict]:
65
+ return self.c.recall(subject=subject, predicate=predicate, status=status, limit=str(limit))
66
+
67
+ def attest(self, target, stance, note) -> dict:
68
+ r = self.c.attest(target, stance, note) # signed locally; needs the full 64-hex hash
69
+ return {"entry": r["entry_hash"], "seq": r["seq"]}
70
+
71
+ def history(self, subject, predicate) -> list[dict]:
72
+ return self.c.history(subject, predicate)
73
+
74
+ def provenance(self, entry) -> dict:
75
+ return self.c.provenance(entry)
76
+
77
+ def verify(self) -> dict:
78
+ return self.c.verify()
79
+
80
+ def alerts(self) -> list[dict]:
81
+ return self.c.alerts()
82
+
83
+ def receipt(self, subject, predicate, question, answer) -> dict:
84
+ return self.c.answer_receipt(subject, predicate, question, answer)
85
+
86
+ def evidence(self, subject, predicate) -> dict:
87
+ return self.c.evidence(subject, predicate)
@@ -0,0 +1,52 @@
1
+ """Canonical JSON (P7-canon-1): sorted keys, no whitespace, UTF-8, no floats.
2
+
3
+ Floats are rejected on purpose: their text form is not stable across runtimes,
4
+ which would break signatures. Confidence and similar values are integers.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ from typing import Any
11
+
12
+
13
+ class CanonError(ValueError):
14
+ pass
15
+
16
+
17
+ _MAX_DEPTH = 32
18
+ _MAX_INT = 2**53
19
+
20
+
21
+ def _check(o: Any, depth: int = 0) -> None:
22
+ if depth > _MAX_DEPTH:
23
+ raise CanonError("structure too deep")
24
+ if o is None or isinstance(o, (bool, str)):
25
+ return
26
+ if isinstance(o, int):
27
+ if not -_MAX_INT < o < _MAX_INT:
28
+ raise CanonError("integer out of range")
29
+ return
30
+ if isinstance(o, float):
31
+ raise CanonError("floats are not allowed; use integers")
32
+ if isinstance(o, (list, tuple)):
33
+ for x in o:
34
+ _check(x, depth + 1)
35
+ return
36
+ if isinstance(o, dict):
37
+ for k, v in o.items():
38
+ if not isinstance(k, str):
39
+ raise CanonError("object keys must be strings")
40
+ _check(v, depth + 1)
41
+ return
42
+ raise CanonError(f"unsupported type: {type(o).__name__}")
43
+
44
+
45
+ def canonical(o: Any) -> bytes:
46
+ _check(o)
47
+ try:
48
+ return json.dumps(
49
+ o, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False
50
+ ).encode("utf-8")
51
+ except UnicodeEncodeError as e:
52
+ raise CanonError("invalid unicode (lone surrogate)") from e
@@ -0,0 +1,148 @@
1
+ """P7 entry types and strict payload validation (unknown fields are rejected)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from typing import Any, Callable
7
+
8
+ HEX64 = re.compile(r"^[0-9a-f]{64}$")
9
+ CTRL = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]") # control chars except \t \n \r
10
+
11
+ GOVERNANCE_TYPES = {"genesis", "identity", "vouch", "revoke"}
12
+ CONTENT_TYPES = {"claim", "attest", "observation", "retract", "rollback"}
13
+ ALL_TYPES = GOVERNANCE_TYPES | CONTENT_TYPES
14
+ ROLES = {"agent", "source", "human", "node"}
15
+ STANCES = {"support", "dispute"}
16
+
17
+
18
+ class SchemaError(ValueError):
19
+ pass
20
+
21
+
22
+ def _s(maxlen: int, *, oneline: bool = False, minlen: int = 0) -> Callable[[Any], str]:
23
+ def check(v: Any) -> str:
24
+ if not isinstance(v, str):
25
+ raise SchemaError("must be a string")
26
+ if not minlen <= len(v) <= maxlen:
27
+ raise SchemaError(f"length must be {minlen}..{maxlen}")
28
+ if CTRL.search(v) or (oneline and ("\n" in v or "\r" in v)):
29
+ raise SchemaError("contains control characters")
30
+ return v
31
+ return check
32
+
33
+
34
+ def _hex64(v: Any) -> str:
35
+ if not isinstance(v, str) or not HEX64.match(v):
36
+ raise SchemaError("must be 64 lowercase hex chars")
37
+ return v
38
+
39
+
40
+ def _int(lo: int, hi: int) -> Callable[[Any], int]:
41
+ def check(v: Any) -> int:
42
+ if isinstance(v, bool) or not isinstance(v, int) or not lo <= v <= hi:
43
+ raise SchemaError(f"must be an integer {lo}..{hi}")
44
+ return v
45
+ return check
46
+
47
+
48
+ def _enum(options: set[str]) -> Callable[[Any], str]:
49
+ def check(v: Any) -> str:
50
+ if v not in options:
51
+ raise SchemaError(f"must be one of {sorted(options)}")
52
+ return v
53
+ return check
54
+
55
+
56
+ def _list(item: Callable[[Any], Any], maxn: int) -> Callable[[Any], list]:
57
+ def check(v: Any) -> list:
58
+ if not isinstance(v, list) or len(v) > maxn:
59
+ raise SchemaError(f"must be a list of at most {maxn} items")
60
+ return [item(x) for x in v]
61
+ return check
62
+
63
+
64
+ def _source(v: Any) -> dict:
65
+ if not isinstance(v, dict):
66
+ raise SchemaError("source must be an object")
67
+ return _validate(v, {
68
+ "uri": (_s(2048, oneline=True, minlen=1), False),
69
+ "entry": (_hex64, False),
70
+ "content_hash": (_hex64, False),
71
+ }, require_any=("uri", "entry"))
72
+
73
+
74
+ # field -> (validator, required)
75
+ SCHEMAS: dict[str, dict[str, tuple[Callable[[Any], Any], bool]]] = {
76
+ "genesis": {"name": (_s(64, oneline=True, minlen=1), True)},
77
+ "identity": {
78
+ "role": (_enum(ROLES), True),
79
+ "name": (_s(64, oneline=True, minlen=1), True),
80
+ },
81
+ "vouch": {"target": (_hex64, True), "weight": (_int(1, 100), False)},
82
+ "revoke": {"target": (_hex64, True), "reason": (_s(256), False)},
83
+ "claim": {
84
+ "subject": (_s(256, oneline=True, minlen=1), True),
85
+ "predicate": (_s(128, oneline=True, minlen=1), True),
86
+ "object": (_s(4096), True),
87
+ "confidence": (_int(0, 100), False),
88
+ "sources": (_list(_source, 20), False),
89
+ "supersedes": (_list(_hex64, 20), False),
90
+ "tags": (_list(_s(32, oneline=True, minlen=1), 10), False),
91
+ "text": (_s(8192), False),
92
+ },
93
+ "attest": {
94
+ "target": (_hex64, True),
95
+ "stance": (_enum(STANCES), True),
96
+ "note": (_s(512), False),
97
+ },
98
+ "retract": {"targets": (_list(_hex64, 50), True), "reason": (_s(256), False)},
99
+ "rollback": {"from_seq": (_int(2, 2**40), True), "reason": (_s(256), False)},
100
+ "observation": {
101
+ "source": (_s(2048, oneline=True, minlen=1), True),
102
+ "content_hash": (_hex64, True),
103
+ "size": (_int(0, 2**40), True),
104
+ "note": (_s(512), False),
105
+ },
106
+ }
107
+
108
+
109
+ def _validate(p: dict, spec: dict, require_any: tuple[str, ...] = ()) -> dict:
110
+ if not isinstance(p, dict):
111
+ raise SchemaError("payload must be an object")
112
+ unknown = set(p) - set(spec)
113
+ if unknown:
114
+ raise SchemaError(f"unknown fields: {sorted(unknown)}")
115
+ out: dict[str, Any] = {}
116
+ for name, (check, required) in spec.items():
117
+ if name not in p:
118
+ if required:
119
+ raise SchemaError(f"missing field: {name}")
120
+ continue
121
+ try:
122
+ out[name] = check(p[name])
123
+ except SchemaError as e:
124
+ raise SchemaError(f"{name}: {e}") from e
125
+ if require_any and not any(k in out for k in require_any):
126
+ raise SchemaError(f"one of {list(require_any)} is required")
127
+ return out
128
+
129
+
130
+ def validate_payload(type_: str, payload: dict) -> dict:
131
+ spec = SCHEMAS.get(type_)
132
+ if spec is None:
133
+ raise SchemaError(f"unknown entry type: {type_}")
134
+ return _validate(payload, spec)
135
+
136
+
137
+ def text_fields(type_: str, payload: dict) -> list[tuple[str, str]]:
138
+ """Free-text fields an LLM could later read; used by the injection scanner."""
139
+ names = {
140
+ "claim": ("subject", "predicate", "object", "text"),
141
+ "attest": ("note",),
142
+ "observation": ("source", "note"),
143
+ "identity": ("name",),
144
+ "retract": ("reason",),
145
+ "rollback": ("reason",),
146
+ "revoke": ("reason",),
147
+ }.get(type_, ())
148
+ return [(n, payload[n]) for n in names if isinstance(payload.get(n), str)]