knurl 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.
knurl/__init__.py ADDED
@@ -0,0 +1,22 @@
1
+ # KNURL - Content-Addressable Primitives
2
+ #
3
+ # Provides rock-solid primitives for:
4
+ # - knurl.canon: Canonical serialization
5
+ # - knurl.hash: Content-addressable hashing
6
+ # - knurl.address: SKEIN address parsing
7
+ # - knurl.yield_: Yield serialization
8
+ # - knurl.diff: Diff computation & application
9
+ # - knurl.chain: Chain fingerprinting
10
+ # - knurl.diverge: Divergence detection
11
+
12
+ from .canon import serialize, CanonError
13
+ from .hash import compute, verify, HashError
14
+ from .address import parse, construct, validate, ParsedAddress, AddressError
15
+ from .chain import fingerprint, fingerprint_step, ChainError
16
+ from . import yield_
17
+ from . import diff
18
+ from . import chain
19
+ from . import diverge
20
+ from . import address
21
+ from .diff import DiffError, PatchConflictError, InvalidPatchError, PathNotFoundError
22
+ from .diverge import DivergenceResult
knurl/address.py ADDED
@@ -0,0 +1,365 @@
1
+ """
2
+ Parse and construct layered SKEIN addresses.
3
+
4
+ SKEIN addresses support three layers:
5
+ - Layer 1 (Bare): folio_id only, e.g., "brief-20251226-n1br"
6
+ - Layer 2 (Project): project/folio_id, e.g., "speakbot/brief-20251226-n1br"
7
+ - Layer 3 (User): @user/project/folio_id, e.g., "@patrick/speakbot/brief-20251226-n1br"
8
+
9
+ Usage:
10
+ from knurl.address import parse, construct, validate, ParsedAddress
11
+
12
+ # Parse addresses
13
+ parse("brief-20251226-n1br")
14
+ # → ParsedAddress(user=None, project=None, folio_id="brief-20251226-n1br")
15
+
16
+ parse("speakbot/brief-20251226-n1br")
17
+ # → ParsedAddress(user=None, project="speakbot", folio_id="brief-20251226-n1br")
18
+
19
+ parse("@patrick/speakbot/brief-20251226-n1br")
20
+ # → ParsedAddress(user="patrick", project="speakbot", folio_id="brief-20251226-n1br")
21
+
22
+ # Construct addresses
23
+ construct(folio_id="brief-20251226-n1br")
24
+ # → "brief-20251226-n1br"
25
+
26
+ construct(project="speakbot", folio_id="brief-20251226-n1br")
27
+ # → "speakbot/brief-20251226-n1br"
28
+
29
+ # Validate addresses
30
+ validate("brief-20251226-n1br") # → True
31
+ validate("not valid!") # → False
32
+ """
33
+
34
+ from __future__ import annotations
35
+
36
+ import re
37
+ from dataclasses import dataclass
38
+ from datetime import datetime
39
+ from typing import Optional
40
+
41
+
42
+ class AddressError(Exception):
43
+ """Raised when an address cannot be parsed or constructed.
44
+
45
+ Common causes:
46
+ - Empty address string
47
+ - Invalid characters in user/project name
48
+ - Malformed folio ID
49
+ - Too many path components
50
+ """
51
+ pass
52
+
53
+
54
+ # Valid folio types in SKEIN
55
+ VALID_FOLIO_TYPES = frozenset([
56
+ "brief", "issue", "friction", "finding", "notion",
57
+ "summary", "tender", "plan", "playbook", "mantle", "writ",
58
+ "thread", "sack", # Internal types
59
+ ])
60
+
61
+ # Regex for valid user/project names: alphanumeric, hyphen, underscore
62
+ NAME_PATTERN = re.compile(r'^[a-zA-Z0-9_-]+$')
63
+
64
+ # Regex for folio ID: {type}-{YYYYMMDD}-{4lowercase_alphanumeric}
65
+ # Type bounded to 1-32 chars as defensive measure (longest SKEIN type is ~10 chars)
66
+ FOLIO_ID_PATTERN = re.compile(
67
+ r'^([a-z]{1,32})-(\d{8})-([a-z0-9]{4})$'
68
+ )
69
+
70
+ # Length limits to prevent DoS attacks
71
+ MAX_ADDRESS_LENGTH = 256 # Total address string
72
+ MAX_NAME_LENGTH = 128 # User or project name
73
+
74
+
75
+ @dataclass(frozen=True)
76
+ class ParsedAddress:
77
+ """Result of parsing a SKEIN address.
78
+
79
+ Attributes:
80
+ user: User name (Layer 3) or None
81
+ project: Project name (Layer 2) or None
82
+ folio_id: The folio identifier (always present)
83
+ """
84
+ user: Optional[str]
85
+ project: Optional[str]
86
+ folio_id: str
87
+
88
+ @property
89
+ def is_bare(self) -> bool:
90
+ """True if this is a bare (Layer 1) address with no project."""
91
+ return self.project is None
92
+
93
+ @property
94
+ def is_user_scoped(self) -> bool:
95
+ """True if this is a user-scoped (Layer 3) address."""
96
+ return self.user is not None
97
+
98
+
99
+ def _validate_name(name: str, field: str) -> None:
100
+ """Validate a user or project name.
101
+
102
+ Args:
103
+ name: The name to validate
104
+ field: Field name for error messages ("user" or "project")
105
+
106
+ Raises:
107
+ AddressError: If name is empty, too long, or contains invalid characters
108
+ """
109
+ if not name:
110
+ raise AddressError(f"Address has empty {field} name")
111
+ if len(name) > MAX_NAME_LENGTH:
112
+ raise AddressError(
113
+ f"Address has {field} name that is too long: {len(name)} chars "
114
+ f"(max {MAX_NAME_LENGTH})"
115
+ )
116
+ if not NAME_PATTERN.match(name):
117
+ raise AddressError(
118
+ f"Address has invalid {field} name: {name!r}. "
119
+ f"Must contain only alphanumeric characters, hyphens, and underscores."
120
+ )
121
+
122
+
123
+ def _validate_folio_id(folio_id: str) -> None:
124
+ """Validate a folio ID format.
125
+
126
+ Args:
127
+ folio_id: The folio ID to validate
128
+
129
+ Raises:
130
+ AddressError: If folio ID format is invalid
131
+ """
132
+ if not folio_id:
133
+ raise AddressError("Address has empty folio ID")
134
+
135
+ match = FOLIO_ID_PATTERN.match(folio_id)
136
+ if not match:
137
+ raise AddressError(
138
+ f"Address has invalid folio ID format: {folio_id!r}. "
139
+ f"Expected format: {{type}}-{{YYYYMMDD}}-{{4char}}"
140
+ )
141
+
142
+ folio_type = match.group(1)
143
+ if folio_type not in VALID_FOLIO_TYPES:
144
+ raise AddressError(
145
+ f"Address has unknown folio type: {folio_type!r}. "
146
+ f"Valid types: {', '.join(sorted(VALID_FOLIO_TYPES))}"
147
+ )
148
+
149
+ # Validate date is a real date
150
+ date_str = match.group(2)
151
+ try:
152
+ datetime.strptime(date_str, "%Y%m%d")
153
+ except ValueError:
154
+ raise AddressError(
155
+ f"Address has invalid date in folio ID: {date_str!r}. "
156
+ f"Expected valid YYYYMMDD date."
157
+ )
158
+
159
+
160
+ def parse(address: str) -> ParsedAddress:
161
+ """Parse a SKEIN address string into components.
162
+
163
+ Args:
164
+ address: A SKEIN address string in one of these formats:
165
+ - "folio_id" (bare)
166
+ - "project/folio_id" (project-qualified)
167
+ - "@user/project/folio_id" (user-scoped)
168
+
169
+ Returns:
170
+ ParsedAddress with user, project, and folio_id fields.
171
+
172
+ Raises:
173
+ AddressError: If the address is invalid.
174
+
175
+ Examples:
176
+ >>> parse("brief-20251226-n1br")
177
+ ParsedAddress(user=None, project=None, folio_id='brief-20251226-n1br')
178
+
179
+ >>> parse("speakbot/brief-20251226-n1br")
180
+ ParsedAddress(user=None, project='speakbot', folio_id='brief-20251226-n1br')
181
+
182
+ >>> parse("@patrick/speakbot/brief-20251226-n1br")
183
+ ParsedAddress(user='patrick', project='speakbot', folio_id='brief-20251226-n1br')
184
+ """
185
+ # Type check
186
+ if not isinstance(address, str):
187
+ raise AddressError(
188
+ f"Address must be a string, got {type(address).__name__}"
189
+ )
190
+
191
+ # Strip whitespace
192
+ address = address.strip()
193
+
194
+ # Check for empty
195
+ if not address:
196
+ raise AddressError("Address is empty")
197
+
198
+ # Check total length
199
+ if len(address) > MAX_ADDRESS_LENGTH:
200
+ raise AddressError(
201
+ f"Address is too long: {len(address)} chars (max {MAX_ADDRESS_LENGTH})"
202
+ )
203
+
204
+ # Check for user-scoped address (@user/project/folio_id)
205
+ if address.startswith("@"):
206
+ # Remove @ prefix
207
+ address_body = address[1:]
208
+
209
+ # Split and strip each component
210
+ parts = [p.strip() for p in address_body.split("/")]
211
+
212
+ # Check for empty components (from "//" or "/ /")
213
+ if "" in parts:
214
+ # Find which one is empty
215
+ if parts[0] == "":
216
+ raise AddressError("Address has empty user name")
217
+ elif len(parts) > 1 and parts[1] == "":
218
+ raise AddressError("Address has empty project name")
219
+ else:
220
+ raise AddressError("Address has empty folio ID")
221
+
222
+ # Must have exactly 3 parts for user-scoped
223
+ if len(parts) != 3:
224
+ if len(parts) < 3:
225
+ raise AddressError(
226
+ f"Address has invalid folio ID format: {address!r}. "
227
+ f"Expected format: {{type}}-{{YYYYMMDD}}-{{4char}}"
228
+ )
229
+ raise AddressError(
230
+ f"Address has too many path components: {address!r}. "
231
+ f"Expected format: @user/project/folio_id"
232
+ )
233
+
234
+ user, project, folio_id = parts
235
+
236
+ # Validate components
237
+ _validate_name(user, "user")
238
+ _validate_name(project, "project")
239
+ _validate_folio_id(folio_id)
240
+
241
+ return ParsedAddress(user=user, project=project, folio_id=folio_id)
242
+
243
+ # Non-@ address: split and strip components
244
+ parts = [p.strip() for p in address.split("/")]
245
+
246
+ # Check for empty components (from "//" or leading "/")
247
+ if "" in parts:
248
+ if parts[0] == "":
249
+ raise AddressError("Address has empty project name")
250
+ else:
251
+ raise AddressError("Address has empty folio ID")
252
+
253
+ if len(parts) == 1:
254
+ # Bare folio ID
255
+ folio_id = parts[0]
256
+ _validate_folio_id(folio_id)
257
+ return ParsedAddress(user=None, project=None, folio_id=folio_id)
258
+
259
+ elif len(parts) == 2:
260
+ # Project-qualified
261
+ project, folio_id = parts
262
+ _validate_name(project, "project")
263
+ _validate_folio_id(folio_id)
264
+ return ParsedAddress(user=None, project=project, folio_id=folio_id)
265
+
266
+ else:
267
+ # Too many slashes
268
+ raise AddressError(
269
+ f"Address has too many path components: {address!r}. "
270
+ f"Expected format: folio_id or project/folio_id"
271
+ )
272
+
273
+
274
+ def construct(
275
+ *,
276
+ user: Optional[str] = None,
277
+ project: Optional[str] = None,
278
+ folio_id: Optional[str] = None,
279
+ ) -> str:
280
+ """Construct a SKEIN address string from components.
281
+
282
+ Args:
283
+ user: Optional user name (Layer 3). Requires project if specified.
284
+ project: Optional project name (Layer 2).
285
+ folio_id: The folio identifier (required).
286
+
287
+ Returns:
288
+ A SKEIN address string.
289
+
290
+ Raises:
291
+ AddressError: If required fields are missing or values are invalid.
292
+
293
+ Examples:
294
+ >>> construct(folio_id="brief-20251226-n1br")
295
+ 'brief-20251226-n1br'
296
+
297
+ >>> construct(project="speakbot", folio_id="brief-20251226-n1br")
298
+ 'speakbot/brief-20251226-n1br'
299
+
300
+ >>> construct(user="patrick", project="speakbot", folio_id="brief-20251226-n1br")
301
+ '@patrick/speakbot/brief-20251226-n1br'
302
+ """
303
+ # Validate folio_id (required)
304
+ if not folio_id:
305
+ raise AddressError("folio_id is required for address construction")
306
+
307
+ _validate_folio_id(folio_id)
308
+
309
+ # Normalize empty string to None
310
+ if project == "":
311
+ project = None
312
+ if user == "":
313
+ user = None
314
+
315
+ # Validate user requires project
316
+ if user and not project:
317
+ raise AddressError(
318
+ "project is required when user is specified "
319
+ "(cannot have Layer 3 without Layer 2)"
320
+ )
321
+
322
+ # Validate names if provided
323
+ if project:
324
+ _validate_name(project, "project")
325
+ if user:
326
+ _validate_name(user, "user")
327
+
328
+ # Build address
329
+ if user:
330
+ return f"@{user}/{project}/{folio_id}"
331
+ elif project:
332
+ return f"{project}/{folio_id}"
333
+ else:
334
+ return folio_id
335
+
336
+
337
+ def validate(address: object) -> bool:
338
+ """Check if an address string is valid.
339
+
340
+ Unlike parse(), this returns False instead of raising for invalid input.
341
+
342
+ Args:
343
+ address: Value to check.
344
+
345
+ Returns:
346
+ True if address is a valid SKEIN address string, False otherwise.
347
+
348
+ Examples:
349
+ >>> validate("brief-20251226-n1br")
350
+ True
351
+
352
+ >>> validate("not valid!")
353
+ False
354
+
355
+ >>> validate(None)
356
+ False
357
+ """
358
+ if not isinstance(address, str):
359
+ return False
360
+
361
+ try:
362
+ parse(address)
363
+ return True
364
+ except AddressError:
365
+ return False
knurl/canon.py ADDED
@@ -0,0 +1,164 @@
1
+ """
2
+ Canonical JSON serialization for content-addressable hashing.
3
+
4
+ This module produces deterministic JSON bytes where the same input always
5
+ produces the exact same output. Suitable for hashing configurations and
6
+ other data structures where byte-level reproducibility matters.
7
+
8
+ Based on RFC 8785 (JSON Canonicalization Scheme) principles:
9
+ - Dict keys sorted lexicographically (ASCII/UTF-16 code unit order)
10
+ - No whitespace between tokens
11
+ - -0.0 normalized to 0.0
12
+ - NaN/Infinity raise errors
13
+ - UTF-8 encoded output
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import json
19
+ import math
20
+ from typing import Any
21
+
22
+
23
+ class CanonError(Exception):
24
+ """Raised when a value cannot be canonically serialized.
25
+
26
+ Common causes:
27
+ - NaN or Infinity floats
28
+ - Circular references
29
+ - Non-JSON-serializable types (bytes, sets, custom objects)
30
+ - Excessive nesting depth
31
+ """
32
+ pass
33
+
34
+
35
+ # Maximum nesting depth to prevent stack overflow
36
+ MAX_DEPTH = 500
37
+
38
+
39
+ def _validate(obj: Any, seen: set[int], depth: int = 0) -> None:
40
+ """Recursively validate that obj contains no invalid values.
41
+
42
+ Raises CanonError for:
43
+ - NaN floats
44
+ - Infinity floats (positive or negative)
45
+ - Circular references
46
+ - Non-string dict keys
47
+ - Excessive nesting depth
48
+
49
+ Args:
50
+ obj: The object to validate
51
+ seen: Set of object ids already visited (for circular reference detection)
52
+ depth: Current nesting depth
53
+ """
54
+ if depth > MAX_DEPTH:
55
+ raise CanonError(f"Maximum nesting depth ({MAX_DEPTH}) exceeded")
56
+
57
+ # Check for circular references in containers
58
+ if isinstance(obj, (dict, list)):
59
+ obj_id = id(obj)
60
+ if obj_id in seen:
61
+ raise CanonError("Circular reference detected")
62
+ seen = seen | {obj_id} # Create new set to avoid mutation across branches
63
+
64
+ if isinstance(obj, dict):
65
+ for key, value in obj.items():
66
+ if not isinstance(key, str):
67
+ raise CanonError(
68
+ f"Dict keys must be strings for canonical JSON, got {type(key).__name__}: {key!r}"
69
+ )
70
+ _validate(value, seen, depth + 1)
71
+ else: # list
72
+ for item in obj:
73
+ _validate(item, seen, depth + 1)
74
+
75
+ elif isinstance(obj, float):
76
+ if math.isnan(obj):
77
+ raise CanonError("NaN values cannot be serialized to canonical JSON")
78
+ if math.isinf(obj):
79
+ raise CanonError("Infinity values cannot be serialized to canonical JSON")
80
+
81
+
82
+ def _normalize(obj: Any) -> Any:
83
+ """Recursively normalize values for canonical serialization.
84
+
85
+ Transformations:
86
+ - -0.0 becomes 0.0 (RFC 8785 requirement)
87
+ - Dict keys remain strings (JSON requirement)
88
+ - All other values pass through unchanged
89
+
90
+ Args:
91
+ obj: The object to normalize
92
+
93
+ Returns:
94
+ Normalized object suitable for json.dumps
95
+ """
96
+ if isinstance(obj, dict):
97
+ return {key: _normalize(value) for key, value in obj.items()}
98
+
99
+ elif isinstance(obj, list):
100
+ return [_normalize(item) for item in obj]
101
+
102
+ elif isinstance(obj, float):
103
+ # Handle -0.0 -> 0.0 (copysign detects negative zero)
104
+ if obj == 0.0 and math.copysign(1.0, obj) < 0:
105
+ return 0.0
106
+ return obj
107
+
108
+ # bool must be checked before int (bool is subclass of int in Python)
109
+ elif isinstance(obj, bool):
110
+ return obj
111
+
112
+ elif isinstance(obj, (int, str, type(None))):
113
+ return obj
114
+
115
+ # Let json.dumps handle type errors for other types
116
+ return obj
117
+
118
+
119
+ def serialize(obj: Any) -> bytes:
120
+ """Serialize an object to canonical JSON bytes.
121
+
122
+ Produces deterministic output suitable for content-addressable hashing.
123
+ The same input will always produce the exact same byte sequence.
124
+
125
+ Args:
126
+ obj: A JSON-serializable object (dict, list, str, int, float, bool, None)
127
+
128
+ Returns:
129
+ UTF-8 encoded canonical JSON bytes
130
+
131
+ Raises:
132
+ CanonError: If the object contains NaN, Infinity, or circular references
133
+ TypeError: If the object contains non-JSON-serializable types
134
+
135
+ Example:
136
+ >>> serialize({"b": 1, "a": 2})
137
+ b'{"a":2,"b":1}'
138
+
139
+ >>> serialize([1, 2, 3])
140
+ b'[1,2,3]'
141
+
142
+ >>> serialize(float('nan'))
143
+ CanonError: NaN values cannot be serialized to canonical JSON
144
+ """
145
+ # Validate first (check for NaN, Infinity, circular refs)
146
+ _validate(obj, set())
147
+
148
+ # Normalize values (convert -0.0 to 0.0)
149
+ normalized = _normalize(obj)
150
+
151
+ # Serialize with canonical settings
152
+ try:
153
+ json_str = json.dumps(
154
+ normalized,
155
+ sort_keys=True, # Lexicographic key ordering
156
+ separators=(',', ':'), # No whitespace
157
+ ensure_ascii=False, # Allow UTF-8 characters directly
158
+ allow_nan=False, # Belt-and-suspenders: reject NaN/Inf at json level too
159
+ )
160
+ except ValueError as e:
161
+ # json.dumps raises ValueError for NaN/Infinity when allow_nan=False
162
+ raise CanonError(str(e)) from e
163
+
164
+ return json_str.encode('utf-8')