pairl 1.5.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.
pairl/__init__.py ADDED
@@ -0,0 +1,27 @@
1
+ """PAIRL v1.5 reference implementation: parser, validator, canonicalizer, renderer."""
2
+
3
+ from .core import (
4
+ SPEC_VERSION,
5
+ ColumnarBlock,
6
+ Message,
7
+ Record,
8
+ parse,
9
+ )
10
+ from .canonical import canonicalize, compute_hash, hash_ref, serialize_record
11
+ from .render import render
12
+ from .validate import Result, validate
13
+
14
+ __all__ = [
15
+ "SPEC_VERSION",
16
+ "Message",
17
+ "Record",
18
+ "ColumnarBlock",
19
+ "parse",
20
+ "validate",
21
+ "Result",
22
+ "canonicalize",
23
+ "serialize_record",
24
+ "compute_hash",
25
+ "hash_ref",
26
+ "render",
27
+ ]
pairl/__main__.py ADDED
@@ -0,0 +1,56 @@
1
+ """CLI: python -m pairl <validate|render|hash> [--strict] <file.pairl>"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+
7
+ from . import canonicalize, compute_hash, parse, render, validate
8
+
9
+
10
+ def _usage() -> int:
11
+ print("usage: python -m pairl <validate|render|hash|canon> [--strict] <file.pairl>")
12
+ return 2
13
+
14
+
15
+ def main(argv: list[str]) -> int:
16
+ args = argv[1:]
17
+ if len(args) < 2:
18
+ return _usage()
19
+ cmd = args[0]
20
+ strict = "--strict" in args
21
+ files = [a for a in args[1:] if not a.startswith("-")]
22
+ if not files:
23
+ return _usage()
24
+ path = files[0]
25
+
26
+ try:
27
+ with open(path, encoding="utf-8") as f:
28
+ text = f.read()
29
+ except OSError as e:
30
+ print(f"error: {e}")
31
+ return 2
32
+
33
+ msg = parse(text)
34
+
35
+ if cmd == "validate":
36
+ res = validate(msg, strict=strict)
37
+ for e in res.errors:
38
+ print(f" ✗ {e}")
39
+ for w in res.warnings:
40
+ print(f" ⚠ {w}")
41
+ print(f"{'✓ PASSED' if res.valid else '✗ FAILED'} — {path}")
42
+ return 0 if res.valid else 1
43
+ if cmd == "render":
44
+ sys.stdout.write(render(msg))
45
+ return 0
46
+ if cmd == "hash":
47
+ print(f"ref:hash:sha256:{compute_hash(msg)}")
48
+ return 0
49
+ if cmd == "canon":
50
+ sys.stdout.write(canonicalize(msg, for_hash=not strict))
51
+ return 0
52
+ return _usage()
53
+
54
+
55
+ if __name__ == "__main__":
56
+ raise SystemExit(main(sys.argv))
pairl/canonical.py ADDED
@@ -0,0 +1,77 @@
1
+ """Canonicalization and hashing (SPEC §9).
2
+
3
+ Columnar blocks are expanded to `#type key=value` records before
4
+ canonicalization (§9.4a), so a message hashes identically in either form.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import hashlib
10
+
11
+ from .core import Message, Record
12
+
13
+ # Canonical header order (§9.1). Unknown headers are appended, sorted.
14
+ _HEADER_ORDER = ["v", "id", "mid", "sid", "ts", "p", "parent", "root", "deps", "budget", "quota"]
15
+ _ATOM_OK = set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789:._/@+-")
16
+
17
+
18
+ def _needs_quote(v: str) -> bool:
19
+ return v == "" or any(c not in _ATOM_OK for c in v)
20
+
21
+
22
+ def _fmt_value(v: str) -> str:
23
+ if _needs_quote(v):
24
+ return '"' + v.replace('"', '\\"') + '"'
25
+ return v
26
+
27
+
28
+ def serialize_record(r: Record) -> str:
29
+ if r.kind == "marker":
30
+ if r.parent is not None: # verbose #msg
31
+ return f"#msg {r.name} r={r.role} parent={r.parent}"
32
+ return f"#{r.name}"
33
+
34
+ if r.kind == "intent":
35
+ params = ",".join(f"{k}={_fmt_value(v)}" for k, v in r.kv.items())
36
+ head = f"{r.name}{{{params}}}" if r.kv or True else r.name
37
+ else:
38
+ pairs = " ".join(f"{k}={_fmt_value(v)}" for k, v in r.kv.items())
39
+ head = f"#{r.name} {pairs}".rstrip()
40
+
41
+ trail = ""
42
+ if r.m:
43
+ trail += f" @m={r.m}"
44
+ if r.rid:
45
+ trail += f" @rid={r.rid}"
46
+ return head + trail
47
+
48
+
49
+ def canonicalize(msg: Message, *, for_hash: bool = True) -> str:
50
+ """Produce the canonical text. With for_hash, @hash is omitted (§9.6)."""
51
+ lines: list[str] = []
52
+ keys = list(msg.headers.keys())
53
+ ordered = [k for k in _HEADER_ORDER if k in msg.headers]
54
+ ordered += sorted(k for k in keys if k not in _HEADER_ORDER and k != "hash")
55
+ if not for_hash and "hash" in msg.headers:
56
+ ordered.append("hash")
57
+ for k in ordered:
58
+ lines.append(f"@{k} {msg.headers[k]}")
59
+
60
+ lines.append("") # blank line separating header block from body
61
+
62
+ # Records already include columnar rows expanded into Record objects (§9.4a),
63
+ # so iterating msg.records yields the canonical, expanded body.
64
+ for r in msg.records:
65
+ lines.append(serialize_record(r))
66
+
67
+ return "\n".join(lines) + "\n"
68
+
69
+
70
+ def compute_hash(msg: Message) -> str:
71
+ canon = canonicalize(msg, for_hash=True)
72
+ digest = hashlib.sha256(canon.encode("utf-8")).hexdigest()
73
+ return digest
74
+
75
+
76
+ def hash_ref(msg: Message) -> str:
77
+ return f"ref:hash:sha256:{compute_hash(msg)}"
pairl/core.py ADDED
@@ -0,0 +1,250 @@
1
+ """PAIRL v1.5 data model and parser.
2
+
3
+ Parses a PAIRL message (headers + body records) into a typed AST, including
4
+ v1.3 turn markers, v1.4 short references, and v1.5 columnar record blocks.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ from dataclasses import dataclass, field
11
+ from typing import Optional
12
+
13
+ SPEC_VERSION = "1.5"
14
+
15
+ # Record types whose key schema is fixed (columnar-eligible). #fact/#ref have a
16
+ # variable key (the key is data) and are not columnar.
17
+ FIXED_SCHEMA_TYPES = {"evid", "rule", "cost", "quota", "call", "ret", "think", "edit"}
18
+ COLUMNAR_FORBIDDEN = {"fact", "ref"}
19
+
20
+ _COL_HEADER = re.compile(r"^#([a-z][a-z0-9_]*)\[([^\]]*)\]$")
21
+ _COMPACT_MARKER = re.compile(r"^#([uas])([0-9]{1,7})$")
22
+ _MSG_MARKER = re.compile(r"^#msg\s+(\S+)\s+r=(\S+)\s+parent=(\S+)\s*$")
23
+ _INTENT = re.compile(r"^([a-z0-9]{2,4}|[a-z][a-z0-9_-]*(?:\.[a-z][a-z0-9_-]*)+)(\{.*\})?(\s+@.*)?$")
24
+ _TRAILING_TAG = re.compile(r"@(m|rid)=([^\s]+)")
25
+
26
+
27
+ @dataclass
28
+ class Record:
29
+ """A single body record (or a columnar row expanded to a record)."""
30
+
31
+ kind: str # fact, ref, evid, rule, cost, quota, call, ret, think, edit, s, intent, marker
32
+ name: Optional[str] = None # intent name; record type tag; marker id
33
+ kv: dict[str, str] = field(default_factory=dict)
34
+ rid: Optional[str] = None
35
+ m: Optional[str] = None # @m= turn binding
36
+ raw: str = ""
37
+ from_columnar: bool = False
38
+ # marker-specific
39
+ role: Optional[str] = None
40
+ parent: Optional[str] = None
41
+
42
+
43
+ @dataclass
44
+ class ColumnarBlock:
45
+ rtype: str
46
+ columns: list[str]
47
+ rows: list[list[tuple[str, bool]]] # each row: list of (value, was_quoted)
48
+ raw_header: str = ""
49
+
50
+
51
+ @dataclass
52
+ class Message:
53
+ headers: dict[str, str] = field(default_factory=dict)
54
+ records: list[Record] = field(default_factory=list)
55
+ blocks: list[ColumnarBlock] = field(default_factory=list)
56
+ errors: list[str] = field(default_factory=list) # parse-level errors
57
+
58
+ @property
59
+ def msg_id(self) -> Optional[str]:
60
+ return self.headers.get("id") or self.headers.get("mid")
61
+
62
+
63
+ def split_fields(s: str) -> list[tuple[str, bool]]:
64
+ """Tokenize a whitespace-separated row into (value, was_quoted) fields.
65
+
66
+ A double-quoted field (with \\" escaping) is one field and may contain spaces.
67
+ """
68
+ out: list[tuple[str, bool]] = []
69
+ i, n = 0, len(s)
70
+ while i < n:
71
+ if s[i] == " ":
72
+ i += 1
73
+ continue
74
+ if s[i] == '"':
75
+ i += 1
76
+ buf: list[str] = []
77
+ while i < n:
78
+ if s[i] == "\\" and i + 1 < n and s[i + 1] == '"':
79
+ buf.append('"')
80
+ i += 2
81
+ continue
82
+ if s[i] == '"':
83
+ i += 1
84
+ break
85
+ buf.append(s[i])
86
+ i += 1
87
+ out.append(("".join(buf), True))
88
+ else:
89
+ start = i
90
+ while i < n and s[i] != " ":
91
+ i += 1
92
+ out.append((s[start:i], False))
93
+ return out
94
+
95
+
96
+ def _parse_kvpairs(s: str) -> dict[str, str]:
97
+ """Parse `key=value` pairs (space- or comma-separated), respecting quotes."""
98
+ kv: dict[str, str] = {}
99
+ i, n = 0, len(s)
100
+ while i < n:
101
+ if s[i] in " ,":
102
+ i += 1
103
+ continue
104
+ # key
105
+ kstart = i
106
+ while i < n and s[i] not in "=":
107
+ if s[i] in " ,":
108
+ break
109
+ i += 1
110
+ key = s[kstart:i]
111
+ if i >= n or s[i] != "=":
112
+ # bare token, skip
113
+ continue
114
+ i += 1 # skip '='
115
+ # value: quoted or atom up to space/comma
116
+ if i < n and s[i] == '"':
117
+ i += 1
118
+ buf: list[str] = []
119
+ while i < n:
120
+ if s[i] == "\\" and i + 1 < n and s[i + 1] == '"':
121
+ buf.append('"')
122
+ i += 2
123
+ continue
124
+ if s[i] == '"':
125
+ i += 1
126
+ break
127
+ buf.append(s[i])
128
+ i += 1
129
+ kv[key] = "".join(buf)
130
+ else:
131
+ vstart = i
132
+ while i < n and s[i] not in " ,":
133
+ i += 1
134
+ kv[key] = s[vstart:i]
135
+ return kv
136
+
137
+
138
+ def _strip_trailing_tags(line: str) -> tuple[str, Optional[str], Optional[str]]:
139
+ """Return (line_without_tags, m, rid)."""
140
+ m_val = rid_val = None
141
+ # iteratively peel trailing @m=/@rid= tokens
142
+ while True:
143
+ mt = re.search(r"\s+@(m|rid)=([^\s]+)\s*$", line)
144
+ if not mt:
145
+ break
146
+ if mt.group(1) == "rid":
147
+ rid_val = mt.group(2)
148
+ else:
149
+ m_val = mt.group(2)
150
+ line = line[: mt.start()]
151
+ return line.rstrip(), m_val, rid_val
152
+
153
+
154
+ def parse(text: str) -> Message:
155
+ msg = Message()
156
+ parts = text.strip("\n").split("\n\n", 1)
157
+ if len(parts) != 2:
158
+ # tolerate header-only or body-only, but record an error
159
+ msg.errors.append("message must have a header block and a body separated by a blank line")
160
+ if not parts:
161
+ return msg
162
+ # treat the single part as headers if it looks like headers, else body
163
+ single = parts[0]
164
+ if single.lstrip().startswith("@"):
165
+ header_part, body_part = single, ""
166
+ else:
167
+ header_part, body_part = "", single
168
+ else:
169
+ header_part, body_part = parts
170
+
171
+ for line in header_part.split("\n"):
172
+ line = line.strip()
173
+ if not line:
174
+ continue
175
+ if not line.startswith("@"):
176
+ msg.errors.append(f"invalid header line (must start with @): {line}")
177
+ continue
178
+ m = re.match(r"@(\w+)\s+(.+)$", line)
179
+ if m:
180
+ msg.headers[m.group(1)] = m.group(2).strip()
181
+ else:
182
+ msg.errors.append(f"malformed header: {line}")
183
+
184
+ lines = [ln.rstrip() for ln in body_part.split("\n")]
185
+ i = 0
186
+ while i < len(lines):
187
+ line = lines[i].strip()
188
+ if not line or line == "---":
189
+ i += 1
190
+ continue
191
+
192
+ hm = _COL_HEADER.match(line)
193
+ if hm:
194
+ rtype = hm.group(1)
195
+ cols = [c.strip() for c in hm.group(2).split(",")]
196
+ rows: list[list[tuple[str, bool]]] = []
197
+ i += 1
198
+ while i < len(lines):
199
+ row = lines[i].strip()
200
+ if not row or row.startswith("#") or row == "---":
201
+ break
202
+ fields, mval, ridval = _strip_trailing_tags(row)
203
+ cells = split_fields(fields)
204
+ rows.append(cells)
205
+ rec = Record(kind=rtype, name=rtype, from_columnar=True, raw=lines[i],
206
+ rid=ridval, m=mval)
207
+ for col, (val, _q) in zip(cols, cells):
208
+ rec.kv[col] = val
209
+ msg.records.append(rec)
210
+ i += 1
211
+ msg.blocks.append(ColumnarBlock(rtype=rtype, columns=cols, rows=rows, raw_header=line))
212
+ continue
213
+
214
+ msg.records.append(_parse_record(line))
215
+ i += 1
216
+
217
+ return msg
218
+
219
+
220
+ def _parse_record(line: str) -> Record:
221
+ raw = line
222
+ cm = _COMPACT_MARKER.match(line)
223
+ if cm:
224
+ return Record(kind="marker", name=f"{cm.group(1)}{cm.group(2)}",
225
+ role=cm.group(1), raw=raw)
226
+ mm = _MSG_MARKER.match(line)
227
+ if mm:
228
+ return Record(kind="marker", name=mm.group(1), role=mm.group(2),
229
+ parent=mm.group(3), raw=raw)
230
+
231
+ body, mval, ridval = _strip_trailing_tags(line)
232
+
233
+ if body.startswith("#"):
234
+ mtype = re.match(r"^#([a-z][a-z0-9_]*)\s*(.*)$", body, re.DOTALL)
235
+ if mtype:
236
+ tag, rest = mtype.group(1), mtype.group(2)
237
+ return Record(kind=tag, name=tag, kv=_parse_kvpairs(rest),
238
+ rid=ridval, m=mval, raw=raw)
239
+
240
+ # intent: name{params}
241
+ im = _INTENT.match(body)
242
+ if im:
243
+ name = im.group(1)
244
+ params = {}
245
+ if im.group(2):
246
+ inner = im.group(2)[1:-1]
247
+ params = _parse_kvpairs(inner)
248
+ return Record(kind="intent", name=name, kv=params, rid=ridval, m=mval, raw=raw)
249
+
250
+ return Record(kind="unknown", raw=raw, rid=ridval, m=mval)
pairl/render.py ADDED
@@ -0,0 +1,105 @@
1
+ """Deterministic PAIRL -> human-readable renderer.
2
+
3
+ This is a faithful, template-based rendering (no LLM): it never invents facts
4
+ and reproduces all #fact/#evid values verbatim (SPEC §12). For fluent natural
5
+ language, feed the message to an LLM renderer instead.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from .core import Message, Record
11
+
12
+ _INTENT_LABELS = {
13
+ "req": "Request", "qst": "Question", "ack": "Acknowledgement", "pln": "Plan",
14
+ "nxt": "Next action", "sum": "Summary", "upd": "Status update", "fin": "Done",
15
+ "blk": "Blocked", "ctx": "Context", "fnd": "Findings", "evl": "Assessment",
16
+ "cmp": "Comparison", "lst": "List", "def": "Clarification", "wrn": "Warning",
17
+ "agr": "Agreement", "dis": "Disagreement", "alt": "Alternative", "emf": "Emphasis",
18
+ "cnt": "Contrast", "rpt": "Report (unconfirmed)", "off": "Official", "inc": "Incident",
19
+ "apx": "Apology", "thx": "Thanks", "grt": "Greeting", "cls": "Closing", "bid": "Cost proposal",
20
+ }
21
+ _ROLE = {"u": "User", "a": "Assistant", "s": "System"}
22
+
23
+
24
+ def render(msg: Message) -> str:
25
+ out: list[str] = []
26
+ mid = msg.msg_id or "(no id)"
27
+ out.append(f"# PAIRL message {mid}")
28
+ meta = []
29
+ if msg.headers.get("ts"):
30
+ meta.append(f"time {msg.headers['ts']}")
31
+ if msg.headers.get("p"):
32
+ meta.append(f"in reply to {msg.headers['p']}")
33
+ if msg.headers.get("budget"):
34
+ meta.append(f"budget {msg.headers['budget']}")
35
+ if meta:
36
+ out.append("_" + " · ".join(meta) + "_")
37
+ out.append("")
38
+
39
+ current_turn = None
40
+ for r in msg.records:
41
+ if r.kind == "marker":
42
+ current_turn = r
43
+ speaker = _ROLE.get(r.role or "", r.role or "?")
44
+ out.append(f"## {speaker} ({r.name})")
45
+ continue
46
+ line = _render_record(r)
47
+ if line:
48
+ out.append(line)
49
+
50
+ return "\n".join(out).rstrip() + "\n"
51
+
52
+
53
+ def _render_record(r: Record) -> str:
54
+ if r.kind == "intent":
55
+ label = _INTENT_LABELS.get(r.name or "", (r.name or "intent"))
56
+ topic = r.kv.get("t")
57
+ s = f"- **{label}**"
58
+ if topic:
59
+ s += f": {topic.replace('_', ' ')}"
60
+ mood = r.kv.get("m")
61
+ if mood == "!":
62
+ s += " (urgent)"
63
+ return s
64
+ if r.kind == "fact":
65
+ return " - " + "; ".join(f"{k} = {v}" for k, v in r.kv.items())
66
+ if r.kind == "evid":
67
+ claim = r.kv.get("claim", "")
68
+ src = r.kv.get("src", "?")
69
+ conf = r.kv.get("conf", "?")
70
+ try:
71
+ conf = f"{float(conf) * 100:.0f}%"
72
+ except ValueError:
73
+ pass
74
+ return f' - Evidence: "{claim}" — source {src}, confidence {conf}'
75
+ if r.kind == "ref":
76
+ return " - Reference: " + "; ".join(f"{k} → {v}" for k, v in r.kv.items())
77
+ if r.kind == "rule":
78
+ return " - Rule: " + ", ".join(f"{k}={v}" for k, v in r.kv.items())
79
+ if r.kind == "cost":
80
+ val = r.kv.get("val", "?")
81
+ cur = r.kv.get("cur", "")
82
+ extra = f" ({r.kv['model']})" if r.kv.get("model") else ""
83
+ return f" - Cost: {val} {cur}{extra}".rstrip()
84
+ if r.kind == "quota":
85
+ t = r.kv.get("type", "?")
86
+ used = r.kv.get("used")
87
+ total = r.kv.get("total")
88
+ rem = r.kv.get("rem")
89
+ bits = [f"{t}"]
90
+ if used and total:
91
+ bits.append(f"used {used}/{total}")
92
+ if rem:
93
+ bits.append(f"{rem} remaining")
94
+ return " - Quota: " + ", ".join(bits)
95
+ if r.kind == "call":
96
+ return f" - Tool call: {r.kv.get('tool', '?')}"
97
+ if r.kind == "ret":
98
+ return f" - Tool result ({r.kv.get('status', '?')})"
99
+ if r.kind == "think":
100
+ return f" - Reasoning: {r.kv.get('summary', '')}"
101
+ if r.kind == "edit":
102
+ return f" - Edit: {r.kv.get('file', '?')} ({r.kv.get('changes', '?')} changes)"
103
+ if r.kind == "s":
104
+ return None
105
+ return None
pairl/validate.py ADDED
@@ -0,0 +1,206 @@
1
+ """PAIRL v1.5 validation rules (V1–V12) operating on a parsed Message."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from dataclasses import dataclass, field
7
+
8
+ from .core import COLUMNAR_FORBIDDEN, Message, split_fields
9
+
10
+ _REF = re.compile(r"^ref:[A-Za-z0-9_-]+:[^\s]+$")
11
+ _SLOC = re.compile(r"^@[A-Za-z0-9]{1,8}(?:#[A-Za-z0-9_-]{1,8})?$")
12
+ _BARE_DEP = re.compile(r"^[A-Za-z0-9]{1,8}(?:#[A-Za-z0-9_-]{1,8})?$")
13
+ _BUDGET = re.compile(r"^([0-9]+(?:\.[0-9]+)?)([A-Za-z]{1,16})$")
14
+ _NUMERIC_INTENT_KEYS = {"l", "m"}
15
+
16
+
17
+ def is_valid_ref(v: str) -> bool:
18
+ if not v.startswith("ref:") or " " in v:
19
+ return False
20
+ main = v.split("#", 1)[0]
21
+ return len(main.split(":")) >= 3 and bool(_REF.match(main))
22
+
23
+
24
+ def is_sloc_ref(v: str) -> bool:
25
+ return bool(_SLOC.match(v))
26
+
27
+
28
+ @dataclass
29
+ class Result:
30
+ errors: list[str] = field(default_factory=list)
31
+ warnings: list[str] = field(default_factory=list)
32
+
33
+ @property
34
+ def valid(self) -> bool:
35
+ return not self.errors
36
+
37
+
38
+ def validate(msg: Message, strict: bool = False) -> Result:
39
+ res = Result()
40
+ res.errors.extend(msg.errors)
41
+
42
+ # Required headers
43
+ for h in ("v", "ts"):
44
+ if h not in msg.headers:
45
+ res.errors.append(f"missing required header: @{h}")
46
+ if "id" not in msg.headers and "mid" not in msg.headers:
47
+ res.errors.append("missing required header: @id (or legacy @mid)")
48
+
49
+ _v1_no_new_facts(msg, res, strict)
50
+ _v2_evidence(msg, res)
51
+ _v3_refs(msg, res)
52
+ _v6_rid_unique(msg, res)
53
+ _v8_budget(msg, res)
54
+ _v9_tool_chain(msg, res, strict)
55
+ _v11_turn_markers(msg, res)
56
+ _v12_columnar(msg, res)
57
+ return res
58
+
59
+
60
+ def _has_rule(msg: Message, name: str) -> bool:
61
+ return any(r.kind == "rule" and r.kv.get(name) == "true" for r in msg.records)
62
+
63
+
64
+ def _v1_no_new_facts(msg: Message, res: Result, strict: bool) -> None:
65
+ enforce = strict and _has_rule(msg, "no_new_facts")
66
+ for r in msg.records:
67
+ if r.kind != "intent":
68
+ continue
69
+ for k, v in r.kv.items():
70
+ if re.search(r"https?://", v):
71
+ _emit(res, enforce, f"V1: intent param '{k}' has a URL (move to #ref): {v}")
72
+ elif re.search(r"[a-fA-F0-9]{12,}", v):
73
+ _emit(res, enforce, f"V1: intent param '{k}' looks like a hash (move to #ref): {v}")
74
+ elif k not in _NUMERIC_INTENT_KEYS and re.search(r"\d", v):
75
+ _emit(res, enforce, f"V1: intent param '{k}' has a number (consider #fact): {k}={v}")
76
+
77
+
78
+ def _v2_evidence(msg: Message, res: Result) -> None:
79
+ for r in msg.records:
80
+ if r.kind != "evid":
81
+ continue
82
+ missing = [k for k in ("claim", "src", "conf") if k not in r.kv]
83
+ if missing:
84
+ res.errors.append(f"V2: #evid missing {', '.join(missing)}: {r.raw}")
85
+ continue
86
+ try:
87
+ c = float(r.kv["conf"])
88
+ if not (0.0 <= c <= 1.0):
89
+ res.errors.append(f"V2: #evid conf must be in [0,1]: {r.raw}")
90
+ except ValueError:
91
+ res.errors.append(f"V2: #evid conf is not a number: {r.raw}")
92
+
93
+
94
+ def _v3_refs(msg: Message, res: Result) -> None:
95
+ for r in msg.records:
96
+ if r.kind == "ref":
97
+ for v in r.kv.values():
98
+ if not (is_valid_ref(v) or is_sloc_ref(v)):
99
+ res.errors.append(f"V3: invalid ref format: {v}")
100
+ deps = msg.headers.get("deps")
101
+ if deps:
102
+ for d in deps.split(","):
103
+ d = d.strip()
104
+ if not d or not (is_valid_ref(d) or is_sloc_ref(d) or _BARE_DEP.match(d)):
105
+ res.errors.append(f"V3: invalid @deps entry: {d!r}")
106
+ for k in ("p", "root", "parent"):
107
+ v = msg.headers.get(k)
108
+ if v and v.startswith("ref:") and not is_valid_ref(v):
109
+ res.errors.append(f"V3: invalid ref in @{k}: {v}")
110
+
111
+
112
+ def _v6_rid_unique(msg: Message, res: Result) -> None:
113
+ seen: set[str] = set()
114
+ for r in msg.records:
115
+ if r.rid:
116
+ low = r.rid.lower()
117
+ if low in seen:
118
+ res.errors.append(f"V6: duplicate @rid: {r.rid}")
119
+ seen.add(low)
120
+
121
+
122
+ def _v8_budget(msg: Message, res: Result) -> None:
123
+ b = msg.headers.get("budget")
124
+ if not b:
125
+ return
126
+ bm = _BUDGET.match(b)
127
+ if not bm:
128
+ res.errors.append(f"V8: invalid @budget format: {b}")
129
+ return
130
+ limit, cur = float(bm.group(1)), bm.group(2)
131
+ total = 0.0
132
+ for r in msg.records:
133
+ if r.kind == "cost" and r.kv.get("cur") == cur:
134
+ try:
135
+ total += float(r.kv.get("val", "0"))
136
+ except ValueError:
137
+ pass
138
+ if total > limit:
139
+ res.errors.append(f"V8: total cost {total} {cur} exceeds budget {limit} {cur}")
140
+
141
+
142
+ def _v9_tool_chain(msg: Message, res: Result, strict: bool) -> None:
143
+ call_rids = {r.rid.lower() for r in msg.records if r.kind == "call" and r.rid}
144
+ for r in msg.records:
145
+ if r.kind == "call" and "tool" not in r.kv:
146
+ res.errors.append(f"V9: #call missing 'tool': {r.raw}")
147
+ elif r.kind == "ret":
148
+ if "call" not in r.kv:
149
+ res.errors.append(f"V9: #ret missing 'call': {r.raw}")
150
+ elif r.kv["call"].lower() not in call_rids:
151
+ _emit(res, strict, f"V9: #ret references unknown call '{r.kv['call']}': {r.raw}")
152
+ status = r.kv.get("status")
153
+ if status is None:
154
+ res.errors.append(f"V9: #ret missing 'status': {r.raw}")
155
+ elif status not in ("ok", "err"):
156
+ res.errors.append(f"V9: #ret status must be ok|err: {r.raw}")
157
+ elif r.kind == "think" and "summary" not in r.kv:
158
+ res.errors.append(f"V9: #think missing 'summary': {r.raw}")
159
+ elif r.kind == "edit":
160
+ if "file" not in r.kv:
161
+ res.errors.append(f"V9: #edit missing 'file': {r.raw}")
162
+ ch = r.kv.get("changes")
163
+ if ch is None or not ch.isdigit() or int(ch) < 1:
164
+ res.errors.append(f"V9: #edit 'changes' must be a positive integer: {r.raw}")
165
+
166
+
167
+ def _v11_turn_markers(msg: Message, res: Result) -> None:
168
+ ids: set[str] = set()
169
+ refs: list[tuple[str, str]] = []
170
+ for r in msg.records:
171
+ if r.kind == "marker":
172
+ if r.name in ids:
173
+ res.errors.append(f"V11: duplicate turn marker {r.name}")
174
+ ids.add(r.name)
175
+ if r.parent and r.parent != "-":
176
+ refs.append((r.parent, "parent"))
177
+ if r.m:
178
+ refs.append((r.m, "@m"))
179
+ if ids:
180
+ for ref_id, kind in refs:
181
+ if ref_id not in ids:
182
+ res.errors.append(f"V11: {kind}={ref_id} references undeclared turn marker")
183
+
184
+
185
+ def _v12_columnar(msg: Message, res: Result) -> None:
186
+ for blk in msg.blocks:
187
+ label = f"#{blk.rtype}[{','.join(blk.columns)}]"
188
+ if blk.rtype in COLUMNAR_FORBIDDEN:
189
+ res.errors.append(f"V12: columnar form not allowed for #{blk.rtype} (key is data): {label}")
190
+ if not blk.columns or any(not re.fullmatch(r"[a-z][a-z0-9_]*", c) for c in blk.columns):
191
+ res.errors.append(f"V12: malformed column list: {label}")
192
+ continue
193
+ if len(set(blk.columns)) != len(blk.columns):
194
+ res.errors.append(f"V12: duplicate column key in {label}")
195
+ if not blk.rows:
196
+ res.warnings.append(f"V12: columnar block has no rows: {label}")
197
+ for row in blk.rows:
198
+ if len(row) != len(blk.columns):
199
+ vals = " ".join(('"%s"' % v if q else v) for v, q in row)
200
+ res.errors.append(
201
+ f"V12: row has {len(row)} field(s), expected {len(blk.columns)} for {label}: {vals}"
202
+ )
203
+
204
+
205
+ def _emit(res: Result, as_error: bool, msg: str) -> None:
206
+ (res.errors if as_error else res.warnings).append(msg)
@@ -0,0 +1,57 @@
1
+ Metadata-Version: 2.4
2
+ Name: pairl
3
+ Version: 1.5.0
4
+ Summary: PAIRL v1.5 reference implementation — parser, validator, canonicalizer, and renderer
5
+ Project-URL: Homepage, https://pairl.dev
6
+ Project-URL: Repository, https://github.com/dwehrmann/PAIRL
7
+ Author: PAIRL
8
+ License: Apache-2.0
9
+ License-File: LICENSE
10
+ Keywords: agent,compression,llm,pairl,protocol
11
+ Requires-Python: >=3.10
12
+ Description-Content-Type: text/markdown
13
+
14
+ # pairl (Python)
15
+
16
+ Reference implementation of the [PAIRL v1.5](../../SPEC.md) protocol: parser,
17
+ validator (rules V1–V12), canonicalizer + SHA-256 hashing, and a deterministic
18
+ human-readable renderer. Pure standard library, no runtime dependencies.
19
+
20
+ ## Install
21
+
22
+ ```bash
23
+ pip install -e impl/python # from the repo root
24
+ ```
25
+
26
+ ## Library
27
+
28
+ ```python
29
+ import pairl
30
+
31
+ msg = pairl.parse(open("message.pairl").read())
32
+
33
+ res = pairl.validate(msg) # rules V1–V12
34
+ print(res.valid, res.errors, res.warnings)
35
+
36
+ print(pairl.compute_hash(msg)) # canonical SHA-256 (columnar-invariant)
37
+ print(pairl.render(msg)) # faithful human-readable rendering
38
+ ```
39
+
40
+ Columnar blocks (`#evid[claim,src,conf]` + positional rows, §3.4) are parsed and
41
+ expanded to their canonical `#type key=value` records, so a message **hashes
42
+ identically** whether sent in columnar or `key=value` form (§9.4a).
43
+
44
+ ## CLI
45
+
46
+ ```bash
47
+ python -m pairl validate [--strict] message.pairl
48
+ python -m pairl render message.pairl
49
+ python -m pairl hash message.pairl
50
+ python -m pairl canon message.pairl
51
+ ```
52
+
53
+ ## Test
54
+
55
+ ```bash
56
+ cd impl/python && python -m unittest discover -s tests
57
+ ```
@@ -0,0 +1,11 @@
1
+ pairl/__init__.py,sha256=pjlJtXIrfEQVMxp2RBArdIiwDcfj2ED5wFbJvqMt2pQ,549
2
+ pairl/__main__.py,sha256=tP3jJnY3t8zzL3eZZ35Afk7i6ONVKxnFfswamakhtyA,1436
3
+ pairl/canonical.py,sha256=6OHy8hjRc5PhJr9a7S3kx0_Eo6TTvV4QPkoHKinpsM4,2463
4
+ pairl/core.py,sha256=WSb_c1D2c7OG64Gkb1ooV5P7ftebMReVIhORdlqE4Zs,8170
5
+ pairl/render.py,sha256=KzE7xIl4p4ehVqQ8IH6XSGNTJm9-1lQOTifAREC-77c,3864
6
+ pairl/validate.py,sha256=IkmwYWr6DQbxCRJ_kT4yUZS9lm9GUYdS4prhf7S9SVo,7772
7
+ pairl-1.5.0.dist-info/METADATA,sha256=9IN-D3CdYKhHua3ot6TIzMX5zQ1AOULyI0dK_NUtIxo,1575
8
+ pairl-1.5.0.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
9
+ pairl-1.5.0.dist-info/entry_points.txt,sha256=f5EYhxH0hucZNgxLrcyh5aNuy8ZpD6dZ0LwsoydyDMo,46
10
+ pairl-1.5.0.dist-info/licenses/LICENSE,sha256=8SuCyXM72P2YmDaKMKew2GxhI5HYpRsy0m6Gz2wgt3c,10766
11
+ pairl-1.5.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.30.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ pairl = pairl.__main__:main
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 PAIRL Contributors
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.