vikela 4.6.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.
- vikela/__init__.py +17 -0
- vikela/__main__.py +2 -0
- vikela/analysis.py +329 -0
- vikela/cli.py +116 -0
- vikela/config.py +33 -0
- vikela/notebook.py +11 -0
- vikela/pylint_plugin.py +24 -0
- vikela/style.py +110 -0
- vikela-4.6.0.dist-info/METADATA +140 -0
- vikela-4.6.0.dist-info/RECORD +13 -0
- vikela-4.6.0.dist-info/WHEEL +4 -0
- vikela-4.6.0.dist-info/entry_points.txt +2 -0
- vikela-4.6.0.dist-info/licenses/LICENSE +176 -0
vikela/__init__.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""Vikela: optional development tooling, never a JsonPit runtime dependency."""
|
|
2
|
+
__version__ = "4.6.0"
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def register(linter):
|
|
6
|
+
"""Pylint's plugin entry point; import its dependency only in plugin mode."""
|
|
7
|
+
from .pylint_plugin import MutationChecker
|
|
8
|
+
linter.register_checker(MutationChecker(linter))
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def load_ipython_extension(ipython):
|
|
12
|
+
from .notebook import cell_magic
|
|
13
|
+
ipython.register_magic_function(cell_magic, magic_kind="cell", magic_name="vikela")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def unload_ipython_extension(ipython):
|
|
17
|
+
ipython.magics_manager.magics["cell"].pop("vikela", None)
|
vikela/__main__.py
ADDED
vikela/analysis.py
ADDED
|
@@ -0,0 +1,329 @@
|
|
|
1
|
+
"""Conservative, non-executing JsonPit provenance analysis (CR077).
|
|
2
|
+
|
|
3
|
+
Only resolved JsonPit imports/annotations and propagated values establish types.
|
|
4
|
+
Unknown calls are not assumed to return a fresh or detached item. Branch joins
|
|
5
|
+
retain facts only when all continuing paths agree. Loops join zero/one iteration;
|
|
6
|
+
this is bounded analysis, not a proof about arbitrary Python execution.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import ast
|
|
11
|
+
from dataclasses import asdict, dataclass, replace
|
|
12
|
+
from typing import Iterable
|
|
13
|
+
|
|
14
|
+
DOCS = "https://github.com/Burkhardt/vikela/blob/main/docs/rules.md"
|
|
15
|
+
PROTECTED = {"id", "modified", "deleted"}
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True)
|
|
19
|
+
class Finding:
|
|
20
|
+
rule: str
|
|
21
|
+
severity: str
|
|
22
|
+
path: str
|
|
23
|
+
line: int
|
|
24
|
+
column: int
|
|
25
|
+
reason: str
|
|
26
|
+
suggestion: str
|
|
27
|
+
documentation: str
|
|
28
|
+
cell: int | None = None
|
|
29
|
+
fix_available: bool = False
|
|
30
|
+
|
|
31
|
+
def to_dict(self):
|
|
32
|
+
return asdict(self)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass(frozen=True)
|
|
36
|
+
class Value:
|
|
37
|
+
kind: str = "unknown"
|
|
38
|
+
owner: str | None = None
|
|
39
|
+
key: str | None = None
|
|
40
|
+
fields: frozenset[str] = frozenset()
|
|
41
|
+
element: Value | None = None
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
UNKNOWN = Value()
|
|
45
|
+
ITEM_KINDS = {"live", "detached", "fresh", "item"}
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def path_name(node):
|
|
49
|
+
if isinstance(node, ast.Name): return node.id
|
|
50
|
+
if isinstance(node, ast.Attribute):
|
|
51
|
+
base = path_name(node.value)
|
|
52
|
+
return base + "." + node.attr if base else ""
|
|
53
|
+
return ""
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def literal(node):
|
|
57
|
+
return str(node.value) if isinstance(node, ast.Constant) and isinstance(node.value, str) else None
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def join_values(values):
|
|
61
|
+
values = list(values)
|
|
62
|
+
return values[0] if values and all(v == values[0] for v in values) else UNKNOWN
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class Analyzer:
|
|
66
|
+
def __init__(self, source: str, path: str = "<source>"):
|
|
67
|
+
self.tree = ast.parse(source, filename=path)
|
|
68
|
+
self.path = path
|
|
69
|
+
self.findings: list[Finding] = []
|
|
70
|
+
self.imports: dict[str, str] = {}
|
|
71
|
+
self.functions: dict[str, ast.FunctionDef | ast.AsyncFunctionDef] = {}
|
|
72
|
+
self.invalid: set[tuple[str | None, str | None]] = set()
|
|
73
|
+
self.depth = 0
|
|
74
|
+
self._seen = set()
|
|
75
|
+
self.scope = "module"
|
|
76
|
+
|
|
77
|
+
def qualified(self, node, env):
|
|
78
|
+
name = path_name(node)
|
|
79
|
+
head, _, tail = name.partition(".")
|
|
80
|
+
if head in env: return ""
|
|
81
|
+
return self.imports.get(head, head) + ("." + tail if tail else "")
|
|
82
|
+
|
|
83
|
+
def annotated(self, node, env, identity):
|
|
84
|
+
if isinstance(node, ast.Constant) and isinstance(node.value, str):
|
|
85
|
+
try: node = ast.parse(node.value, mode="eval").body
|
|
86
|
+
except SyntaxError: return UNKNOWN
|
|
87
|
+
name = self.qualified(node, env)
|
|
88
|
+
if name in {"jsonpit.Pit", "jsonpit.store.Pit"}: return Value("pit", identity)
|
|
89
|
+
if name in {"jsonpit.PitItem", "jsonpit.item.PitItem"}: return Value("item")
|
|
90
|
+
if isinstance(node, ast.Subscript):
|
|
91
|
+
element = self.annotated(node.slice, env, identity)
|
|
92
|
+
if self.qualified(node.value, env) in {"list", "set", "tuple", "typing.List", "typing.Sequence", "typing.Iterable"}:
|
|
93
|
+
return Value("collection", element=element)
|
|
94
|
+
return UNKNOWN
|
|
95
|
+
|
|
96
|
+
def emit(self, rule, node, reason):
|
|
97
|
+
key = (rule, node.lineno, node.col_offset, reason)
|
|
98
|
+
if key in self._seen: return
|
|
99
|
+
self._seen.add(key)
|
|
100
|
+
suggestion = (
|
|
101
|
+
"Update the same-owner live item through indexing or set_property; create a fresh PitItem containing only the intended fields for an explicit delta. Historical replay is not a client-write workaround."
|
|
102
|
+
if rule == "RAI011" else
|
|
103
|
+
"Let JsonPit manage Id, Modified and Deleted. Use rename_id or delete_item for lifecycle changes; update business properties through the live item."
|
|
104
|
+
)
|
|
105
|
+
self.findings.append(Finding(rule, "Warning", self.path, node.lineno, node.col_offset + 1,
|
|
106
|
+
reason, suggestion, DOCS + "#" + rule.lower()))
|
|
107
|
+
|
|
108
|
+
def payload_fields(self, node, env):
|
|
109
|
+
if isinstance(node, ast.Dict):
|
|
110
|
+
fields = set()
|
|
111
|
+
for key, value in zip(node.keys, node.values):
|
|
112
|
+
if key is None: fields.update(self.value(value, env).fields)
|
|
113
|
+
elif literal(key) is not None: fields.add(literal(key))
|
|
114
|
+
return frozenset(fields)
|
|
115
|
+
return self.value(node, env).fields
|
|
116
|
+
|
|
117
|
+
def payload_check(self, node, receiver, payload, env):
|
|
118
|
+
for field in self.payload_fields(payload, env):
|
|
119
|
+
if field.lower() in {"modified", "deleted"}:
|
|
120
|
+
self.emit("RAI012", node, f"Client mutation includes protected lifecycle attribute '{field}'.")
|
|
121
|
+
elif field.lower() == "id" and isinstance(payload, ast.Dict):
|
|
122
|
+
for key, val in zip(payload.keys, payload.values):
|
|
123
|
+
if literal(key) == field and literal(val) is not None and receiver.key is not None and literal(val) != receiver.key:
|
|
124
|
+
self.emit("RAI012", node, "Client mutation changes the item's immutable Id.")
|
|
125
|
+
|
|
126
|
+
def value(self, node, env):
|
|
127
|
+
if node is None: return UNKNOWN
|
|
128
|
+
name = path_name(node)
|
|
129
|
+
if name and name in env: return env[name]
|
|
130
|
+
if isinstance(node, ast.NamedExpr):
|
|
131
|
+
value = self.value(node.value, env); self.bind(node.target, value, env); return value
|
|
132
|
+
if isinstance(node, ast.Subscript):
|
|
133
|
+
base = self.value(node.value, env)
|
|
134
|
+
if base.kind == "pit": return Value("live", base.owner, literal(node.slice))
|
|
135
|
+
if base.kind == "collection": return base.element or UNKNOWN
|
|
136
|
+
if isinstance(node, (ast.List, ast.Tuple, ast.Set)):
|
|
137
|
+
return Value("collection", element=join_values(self.value(e, env) for e in node.elts) if node.elts else None)
|
|
138
|
+
if isinstance(node, ast.Dict): return Value("payload", fields=self.payload_fields(node, env))
|
|
139
|
+
if isinstance(node, ast.IfExp):
|
|
140
|
+
self.value(node.test, env)
|
|
141
|
+
return join_values([self.value(node.body, dict(env)), self.value(node.orelse, dict(env))])
|
|
142
|
+
if isinstance(node, ast.BoolOp): return join_values(self.value(v, env) for v in node.values)
|
|
143
|
+
if isinstance(node, ast.Call): return self.call(node, env)
|
|
144
|
+
if isinstance(node, ast.Await): return self.value(node.value, env)
|
|
145
|
+
return UNKNOWN
|
|
146
|
+
|
|
147
|
+
def call(self, node, env):
|
|
148
|
+
qualified = self.qualified(node.func, env)
|
|
149
|
+
args = [self.value(arg, env) for arg in node.args]
|
|
150
|
+
if qualified in {"jsonpit.Pit", "jsonpit.store.Pit"}:
|
|
151
|
+
return Value("pit", f"allocation:{self.scope}:{node.lineno}:{node.col_offset}")
|
|
152
|
+
if qualified in {"jsonpit.PitItem", "jsonpit.item.PitItem"}:
|
|
153
|
+
first = args[0] if args else UNKNOWN
|
|
154
|
+
key = literal(node.args[0]) if node.args else None
|
|
155
|
+
key = next((literal(k.value) for k in node.keywords if k.arg == "id"), key)
|
|
156
|
+
if first.kind in {"live", "detached"}: return replace(first, kind="detached")
|
|
157
|
+
if first.fields & {"Modified", "Deleted", "modified", "deleted"}:
|
|
158
|
+
return Value("detached", fields=first.fields)
|
|
159
|
+
return Value("fresh", key=key, fields=first.fields)
|
|
160
|
+
if qualified == "typing.cast" and len(args) == 2: return args[1]
|
|
161
|
+
if qualified in {"dict", "copy.copy", "copy.deepcopy"} and args:
|
|
162
|
+
return replace(args[0], kind="detached") if args[0].kind in ITEM_KINDS else args[0]
|
|
163
|
+
if isinstance(node.func, ast.Attribute):
|
|
164
|
+
receiver = self.value(node.func.value, env)
|
|
165
|
+
method = node.func.attr
|
|
166
|
+
if receiver.kind == "pit":
|
|
167
|
+
if method in {"get", "get_at"}:
|
|
168
|
+
explicit_none = any(k.arg == "at" and isinstance(k.value, ast.Constant) and k.value.value is None for k in node.keywords) or (method == "get_at" and len(node.args) > 1 and isinstance(node.args[1], ast.Constant) and node.args[1].value is None)
|
|
169
|
+
detached = method == "get_at" and not explicit_none or any(k.arg == "at" and not (isinstance(k.value, ast.Constant) and k.value.value is None) for k in node.keywords)
|
|
170
|
+
return Value("detached" if detached else "live", receiver.owner, literal(node.args[0]) if node.args else None)
|
|
171
|
+
if method == "add" and args:
|
|
172
|
+
value = args[0]
|
|
173
|
+
if value.kind == "detached": self.emit("RAI011", node, "A detached full projection is being submitted as a live write; it can replay unrelated fields and engine lifecycle metadata.")
|
|
174
|
+
elif value.kind == "live":
|
|
175
|
+
if (value.owner, value.key) in self.invalid or (value.owner, "*") in self.invalid:
|
|
176
|
+
self.emit("RAI011", node, "The live handle belongs to a deleted item or disposed Pit lifetime.")
|
|
177
|
+
elif value.owner != receiver.owner and all((o or "").startswith("allocation:") for o in [value.owner, receiver.owner]):
|
|
178
|
+
self.emit("RAI011", node, "The live handle belongs to a different Pit instance.")
|
|
179
|
+
if value.kind == "fresh":
|
|
180
|
+
# A first Add adopts the original item; subsequent aliases share it.
|
|
181
|
+
for name, old in list(env.items()):
|
|
182
|
+
if old is value: env[name] = Value("live", receiver.owner, old.key)
|
|
183
|
+
if method == "delete_item" and node.args and literal(node.args[0]) is not None:
|
|
184
|
+
self.invalid.add((receiver.owner, literal(node.args[0])))
|
|
185
|
+
if method in {"close", "dispose"}: self.invalid.add((receiver.owner, "*"))
|
|
186
|
+
elif receiver.kind in ITEM_KINDS:
|
|
187
|
+
if method in {"to_dict", "clone", "copy", "__copy__", "__deepcopy__"}: return replace(receiver, kind="detached")
|
|
188
|
+
if method in {"extend_with", "set_property", "merge"} and node.args:
|
|
189
|
+
self.payload_check(node, receiver, node.args[0], env)
|
|
190
|
+
if method in {"delete_property", "delete_property_path", "pop", "__delitem__"} and node.args:
|
|
191
|
+
field = literal(node.args[0])
|
|
192
|
+
if field and field.split(".")[0].lower() in PROTECTED:
|
|
193
|
+
self.emit("RAI012", node, f"Cannot delete protected lifecycle attribute '{field}'.")
|
|
194
|
+
elif receiver.kind == "collection" and method in {"append", "add", "extend"} and args:
|
|
195
|
+
name = path_name(node.func.value)
|
|
196
|
+
new = args[0].element if method == "extend" else args[0]
|
|
197
|
+
old = receiver.element
|
|
198
|
+
combined = new if old is None else join_values([old, new or UNKNOWN])
|
|
199
|
+
for alias, value in list(env.items()):
|
|
200
|
+
if value is receiver: env[alias] = replace(receiver, element=combined)
|
|
201
|
+
function = self.functions.get(path_name(node.func))
|
|
202
|
+
if function is not None and self.depth < 4:
|
|
203
|
+
local = dict(env)
|
|
204
|
+
for param, val in zip(function.args.args, args): local[param.arg] = val
|
|
205
|
+
self.depth += 1
|
|
206
|
+
invalid = set(self.invalid)
|
|
207
|
+
try:
|
|
208
|
+
returns, _ = self.block(function.body, local)
|
|
209
|
+
assigned = {path_name(target) for statement in ast.walk(function) if isinstance(statement, ast.Assign) for target in statement.targets}
|
|
210
|
+
for param, original in zip(function.args.args, args):
|
|
211
|
+
current = local.get(param.arg, UNKNOWN)
|
|
212
|
+
if param.arg not in assigned and (original.kind == "collection" or original.kind == "fresh" and current.kind == "live"):
|
|
213
|
+
for name, value in list(env.items()):
|
|
214
|
+
if value is original: env[name] = current
|
|
215
|
+
return join_values(returns)
|
|
216
|
+
finally: self.invalid = invalid; self.depth -= 1
|
|
217
|
+
return UNKNOWN
|
|
218
|
+
|
|
219
|
+
def bind(self, target, value, env):
|
|
220
|
+
name = path_name(target)
|
|
221
|
+
if name: env[name] = value
|
|
222
|
+
elif isinstance(target, (ast.Tuple, ast.List)):
|
|
223
|
+
for element in target.elts: self.bind(element, UNKNOWN, env)
|
|
224
|
+
|
|
225
|
+
def assignment(self, target, value, env):
|
|
226
|
+
if isinstance(target, (ast.Subscript, ast.Attribute)):
|
|
227
|
+
base = self.value(target.value, env)
|
|
228
|
+
field = literal(target.slice) if isinstance(target, ast.Subscript) else target.attr
|
|
229
|
+
if base.kind in ITEM_KINDS and field and field.lower() in PROTECTED:
|
|
230
|
+
self.emit("RAI012", target, f"Direct assignment changes protected lifecycle attribute '{field}'.")
|
|
231
|
+
self.bind(target, value, env)
|
|
232
|
+
|
|
233
|
+
def merge_env(self, target, branches):
|
|
234
|
+
for key in set().union(*(b.keys() for b in branches)):
|
|
235
|
+
target[key] = join_values(b.get(key, UNKNOWN) for b in branches)
|
|
236
|
+
|
|
237
|
+
def block(self, statements, env):
|
|
238
|
+
returns = []
|
|
239
|
+
for statement in statements:
|
|
240
|
+
if isinstance(statement, ast.Import):
|
|
241
|
+
for alias in statement.names:
|
|
242
|
+
name = alias.asname or alias.name.split(".")[0]; env.pop(name, None)
|
|
243
|
+
self.imports[name] = alias.name if alias.asname else alias.name.split(".")[0]
|
|
244
|
+
elif isinstance(statement, ast.ImportFrom):
|
|
245
|
+
for alias in statement.names:
|
|
246
|
+
name = alias.asname or alias.name; env.pop(name, None)
|
|
247
|
+
self.imports[name] = (statement.module or "") + "." + alias.name
|
|
248
|
+
elif isinstance(statement, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
249
|
+
self.functions[statement.name] = statement
|
|
250
|
+
env[statement.name] = UNKNOWN
|
|
251
|
+
elif isinstance(statement, ast.ClassDef):
|
|
252
|
+
env[statement.name] = UNKNOWN
|
|
253
|
+
local = dict(env)
|
|
254
|
+
for member in statement.body:
|
|
255
|
+
if isinstance(member, ast.AnnAssign):
|
|
256
|
+
name = path_name(member.target)
|
|
257
|
+
local["self." + name] = self.value(member.value, local) if member.value else self.annotated(member.annotation, local, "field:" + statement.name + "." + name)
|
|
258
|
+
self.analyze_functions(statement.body, local)
|
|
259
|
+
elif isinstance(statement, ast.Assign):
|
|
260
|
+
value = self.value(statement.value, env)
|
|
261
|
+
for target in statement.targets: self.assignment(target, value, env)
|
|
262
|
+
elif isinstance(statement, ast.AnnAssign):
|
|
263
|
+
value = self.value(statement.value, env) if statement.value else self.annotated(statement.annotation, env, "annotation:" + self.scope + ":" + path_name(statement.target))
|
|
264
|
+
self.assignment(statement.target, value, env)
|
|
265
|
+
elif isinstance(statement, ast.AugAssign):
|
|
266
|
+
self.value(statement.value, env); self.assignment(statement.target, UNKNOWN, env)
|
|
267
|
+
elif isinstance(statement, ast.Expr): self.value(statement.value, env)
|
|
268
|
+
elif isinstance(statement, ast.Return):
|
|
269
|
+
returns.append(self.value(statement.value, env)); return returns, True
|
|
270
|
+
elif isinstance(statement, ast.Raise): self.value(statement.exc, env); return returns, True
|
|
271
|
+
elif isinstance(statement, ast.If):
|
|
272
|
+
self.value(statement.test, env)
|
|
273
|
+
branches = []; before = set(self.invalid); invalids = []
|
|
274
|
+
for body in [statement.body, statement.orelse]:
|
|
275
|
+
local = dict(env); self.invalid = set(before)
|
|
276
|
+
values, stopped = self.block(body, local); returns.extend(values)
|
|
277
|
+
if not stopped: branches.append(local); invalids.append(set(self.invalid))
|
|
278
|
+
self.invalid = set.intersection(*invalids) if invalids else before
|
|
279
|
+
if not branches: return returns, True
|
|
280
|
+
self.merge_env(env, branches)
|
|
281
|
+
elif isinstance(statement, (ast.For, ast.AsyncFor, ast.While)):
|
|
282
|
+
local = dict(env); before = set(self.invalid)
|
|
283
|
+
if isinstance(statement, (ast.For, ast.AsyncFor)):
|
|
284
|
+
iterable = self.value(statement.iter, env); self.bind(statement.target, iterable.element or UNKNOWN, local)
|
|
285
|
+
self.block(statement.body, local)
|
|
286
|
+
self.invalid = before; self.merge_env(env, [env.copy(), local])
|
|
287
|
+
self.block(statement.orelse, env)
|
|
288
|
+
elif isinstance(statement, (ast.With, ast.AsyncWith)):
|
|
289
|
+
for item in statement.items:
|
|
290
|
+
value = self.value(item.context_expr, env)
|
|
291
|
+
if item.optional_vars: self.bind(item.optional_vars, value, env)
|
|
292
|
+
values, stopped = self.block(statement.body, env); returns.extend(values)
|
|
293
|
+
if stopped: return returns, True
|
|
294
|
+
elif isinstance(statement, ast.Delete):
|
|
295
|
+
for target in statement.targets:
|
|
296
|
+
if isinstance(target, ast.Subscript):
|
|
297
|
+
base = self.value(target.value, env); field = literal(target.slice)
|
|
298
|
+
if base.kind in ITEM_KINDS and field and field.lower() in PROTECTED: self.emit("RAI012", target, f"Cannot delete protected lifecycle attribute '{field}'.")
|
|
299
|
+
else: env.pop(path_name(target), None)
|
|
300
|
+
elif isinstance(statement, (ast.Break, ast.Continue)): return returns, True
|
|
301
|
+
elif isinstance(statement, ast.Try):
|
|
302
|
+
before = dict(env); before_invalid = set(self.invalid); branches = []
|
|
303
|
+
for body in [statement.body, *(handler.body for handler in statement.handlers)]:
|
|
304
|
+
local = dict(before); self.invalid = set(before_invalid); self.block(body, local); branches.append(local)
|
|
305
|
+
self.invalid = before_invalid; self.merge_env(env, branches)
|
|
306
|
+
self.block(statement.orelse, env); self.block(statement.finalbody, env)
|
|
307
|
+
return returns, False
|
|
308
|
+
|
|
309
|
+
def analyze_functions(self, statements, base):
|
|
310
|
+
for node in statements:
|
|
311
|
+
if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): continue
|
|
312
|
+
self.functions[node.name] = node
|
|
313
|
+
for node in statements:
|
|
314
|
+
if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): continue
|
|
315
|
+
local = dict(base); self.scope = node.name; before = set(self.invalid)
|
|
316
|
+
before_imports = dict(self.imports); before_functions = dict(self.functions)
|
|
317
|
+
for param in [*node.args.posonlyargs, *node.args.args, *node.args.kwonlyargs]:
|
|
318
|
+
local[param.arg] = self.annotated(param.annotation, base, "parameter:" + node.name + ":" + param.arg)
|
|
319
|
+
self.block(node.body, local)
|
|
320
|
+
self.analyze_functions(node.body, local)
|
|
321
|
+
self.invalid = before; self.imports = before_imports; self.functions = before_functions
|
|
322
|
+
|
|
323
|
+
def run(self):
|
|
324
|
+
env = {}; self.block(self.tree.body, env); self.analyze_functions(self.tree.body, env)
|
|
325
|
+
return sorted(self.findings, key=lambda f: (f.line, f.column, f.rule))
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def analyze(source: str, path: str = "<source>") -> list[Finding]:
|
|
329
|
+
return Analyzer(source, path).run()
|
vikela/cli.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
"""Standalone, read-only-by-default CLI. No inspected code is imported or run."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
import argparse
|
|
4
|
+
from dataclasses import replace
|
|
5
|
+
import json
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
import sys
|
|
8
|
+
import tokenize
|
|
9
|
+
|
|
10
|
+
from . import __version__
|
|
11
|
+
from .analysis import Finding, analyze
|
|
12
|
+
from .config import ConfigurationError, disabled_rules
|
|
13
|
+
from .style import banner, enabled, help_text, paint
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class UsageError(ValueError): pass
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class Parser(argparse.ArgumentParser):
|
|
20
|
+
def error(self, message): raise UsageError(message)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def parser():
|
|
24
|
+
p = Parser(prog="vikela", add_help=False)
|
|
25
|
+
p.add_argument("paths", nargs="*")
|
|
26
|
+
p.add_argument("-h", "--help", action="store_true")
|
|
27
|
+
p.add_argument("-v", "--version", action="store_true")
|
|
28
|
+
p.add_argument("-n", "--nologo", action="store_true")
|
|
29
|
+
p.add_argument("--json", action="store_true")
|
|
30
|
+
p.add_argument("--fix", "--qondisa", dest="fix", action="store_true")
|
|
31
|
+
p.add_argument("--config")
|
|
32
|
+
p.add_argument("--disable", action="append", choices=["RAI011", "RAI012"], default=[])
|
|
33
|
+
return p
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def sources(path):
|
|
37
|
+
if path.suffix == ".ipynb":
|
|
38
|
+
try:
|
|
39
|
+
notebook = json.loads(path.read_text(encoding="utf-8"))
|
|
40
|
+
if not isinstance(notebook, dict) or not isinstance(notebook.get("cells"), list):
|
|
41
|
+
raise UsageError(f"{path}: notebook must contain a cells array")
|
|
42
|
+
# One non-executed source stream retains cross-cell provenance in document order.
|
|
43
|
+
chunks = []; locations = []
|
|
44
|
+
for index, cell in enumerate(notebook["cells"], 1):
|
|
45
|
+
if not isinstance(cell, dict): raise UsageError(f"{path}: malformed cell {index}")
|
|
46
|
+
if cell.get("cell_type") != "code": continue
|
|
47
|
+
text = cell.get("source", "")
|
|
48
|
+
if isinstance(text, list) and all(isinstance(s, str) for s in text): text = "".join(text)
|
|
49
|
+
if not isinstance(text, str): raise UsageError(f"{path}: malformed source in cell {index}")
|
|
50
|
+
for line_number, line in enumerate(text.splitlines(), 1):
|
|
51
|
+
# Ignore IPython commands without executing them; cell bodies remain Python.
|
|
52
|
+
chunks.append("" if line.lstrip().startswith(("%", "!")) else line)
|
|
53
|
+
locations.append((index, line_number))
|
|
54
|
+
yield "\n".join(chunks), locations
|
|
55
|
+
except (json.JSONDecodeError, UnicodeError) as exc: raise UsageError(f"{path}: {exc}") from exc
|
|
56
|
+
else:
|
|
57
|
+
with tokenize.open(path) as stream: yield stream.read(), None
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def inspect_paths(paths, disabled=(), config=None):
|
|
61
|
+
files = set()
|
|
62
|
+
for value in paths:
|
|
63
|
+
path = Path(value).expanduser()
|
|
64
|
+
if not path.exists(): raise UsageError(f"Path does not exist: {path}")
|
|
65
|
+
if path.is_dir():
|
|
66
|
+
files.update(p for p in path.rglob("*") if p.suffix in {".py", ".ipynb"} and not any(x in {".git", ".venv", "venv", "__pycache__"} for x in p.parts))
|
|
67
|
+
elif path.suffix in {".py", ".ipynb"}: files.add(path)
|
|
68
|
+
else: raise UsageError(f"Unsupported input type: {path}")
|
|
69
|
+
findings = []
|
|
70
|
+
for path in sorted(files):
|
|
71
|
+
ignored = set(disabled) | disabled_rules(path, config)
|
|
72
|
+
for source, locations in sources(path):
|
|
73
|
+
try: items = analyze(source, str(path.resolve()))
|
|
74
|
+
except SyntaxError as exc:
|
|
75
|
+
cell = f" cell {locations[exc.lineno - 1][0]}" if locations and exc.lineno and exc.lineno <= len(locations) else ""
|
|
76
|
+
raise UsageError(f"{path}{cell}:{exc.lineno}:{exc.offset}: {exc.msg}") from exc
|
|
77
|
+
for item in items:
|
|
78
|
+
if item.rule in ignored: continue
|
|
79
|
+
if locations:
|
|
80
|
+
cell, line = locations[item.line - 1]; item = replace(item, cell=cell, line=line)
|
|
81
|
+
findings.append(item)
|
|
82
|
+
return findings
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def render(findings, json_mode=False, nologo=False, fix=False):
|
|
86
|
+
if json_mode:
|
|
87
|
+
print(json.dumps([f.to_dict() for f in findings], ensure_ascii=False, indent=2))
|
|
88
|
+
else:
|
|
89
|
+
color = enabled()
|
|
90
|
+
if not nologo: print(banner(color))
|
|
91
|
+
for finding in findings:
|
|
92
|
+
cell = f" [cell {finding.cell}]" if finding.cell is not None else ""
|
|
93
|
+
print(f"{finding.path}{cell}:{finding.line}:{finding.column}: " + paint(finding.rule, "1;94", color) + " " + finding.reason)
|
|
94
|
+
print(" " + paint("Suggestion: ", "3;35", color) + finding.suggestion)
|
|
95
|
+
print(" " + finding.documentation)
|
|
96
|
+
if not findings: print(paint("✓ No mutation guardrail findings.", "92", color))
|
|
97
|
+
if fix and findings:
|
|
98
|
+
print("No proven safe automatic transformation is available for these findings; source files were left unchanged.", file=sys.stderr)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def main(argv=None):
|
|
102
|
+
json_mode = "--json" in (sys.argv[1:] if argv is None else argv)
|
|
103
|
+
try:
|
|
104
|
+
args = parser().parse_args(argv)
|
|
105
|
+
if args.help: print(help_text()); return 0
|
|
106
|
+
if args.version: print(f"vikela v{__version__}"); return 0
|
|
107
|
+
if not args.paths: raise UsageError("Specify a Python file, notebook or directory; use --help for options.")
|
|
108
|
+
findings = inspect_paths(args.paths, args.disable, args.config)
|
|
109
|
+
render(findings, args.json, args.nologo, args.fix)
|
|
110
|
+
return 1 if findings else 0
|
|
111
|
+
except (UsageError, ConfigurationError, SyntaxError, UnicodeError) as exc:
|
|
112
|
+
if json_mode: print("[]")
|
|
113
|
+
print(f"vikela: {exc}", file=sys.stderr); return 2
|
|
114
|
+
except Exception as exc:
|
|
115
|
+
if json_mode: print("[]")
|
|
116
|
+
print(f"vikela: {type(exc).__name__}: {exc}", file=sys.stderr); return 4
|
vikela/config.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""Shared standalone/editor project configuration; no inspected modules are imported."""
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
import tomllib
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class ConfigurationError(ValueError): pass
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def disabled_rules(path, explicit=None):
|
|
10
|
+
if explicit is not None:
|
|
11
|
+
candidates = [Path(explicit)]
|
|
12
|
+
else:
|
|
13
|
+
target = Path(path).resolve()
|
|
14
|
+
start = target if target.is_dir() else target.parent
|
|
15
|
+
candidates = [parent / "pyproject.toml" for parent in [start, *start.parents]]
|
|
16
|
+
for candidate in candidates:
|
|
17
|
+
if not candidate.is_file():
|
|
18
|
+
if explicit is not None: raise ConfigurationError(f"Configuration does not exist: {candidate}")
|
|
19
|
+
continue
|
|
20
|
+
try:
|
|
21
|
+
with candidate.open("rb") as stream: document = tomllib.load(stream)
|
|
22
|
+
except (tomllib.TOMLDecodeError, UnicodeError) as exc:
|
|
23
|
+
raise ConfigurationError(f"{candidate}: {exc}") from exc
|
|
24
|
+
section = document.get("tool", {}).get("vikela")
|
|
25
|
+
if section is None and explicit is None: continue
|
|
26
|
+
if section is None: return set()
|
|
27
|
+
if not isinstance(section, dict) or set(section) - {"disable"}:
|
|
28
|
+
raise ConfigurationError(f"{candidate}: tool.vikela supports only 'disable'")
|
|
29
|
+
value = section.get("disable", [])
|
|
30
|
+
if not isinstance(value, list) or any(rule not in {"RAI011", "RAI012"} for rule in value):
|
|
31
|
+
raise ConfigurationError(f"{candidate}: disable must be an array of RAI011/RAI012 rule IDs")
|
|
32
|
+
return set(value)
|
|
33
|
+
return set()
|
vikela/notebook.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""IPython extension: %%vikela checks a cell, but never executes its contents."""
|
|
2
|
+
import shlex
|
|
3
|
+
from .analysis import analyze
|
|
4
|
+
from .cli import parser, render, UsageError
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def cell_magic(line, cell):
|
|
8
|
+
args = parser().parse_args(shlex.split(line))
|
|
9
|
+
if args.paths: raise UsageError("%%vikela accepts options, not file paths")
|
|
10
|
+
findings = [f for f in analyze(cell, "<vikela-cell>") if f.rule not in args.disable]
|
|
11
|
+
render(findings, args.json, nologo=True, fix=args.fix)
|
vikela/pylint_plugin.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""Pylint adapter: framework analysis is shared with the standalone CLI."""
|
|
2
|
+
from pylint.checkers import BaseChecker
|
|
3
|
+
from .analysis import analyze
|
|
4
|
+
from .config import disabled_rules
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class MutationChecker(BaseChecker):
|
|
8
|
+
name = "vikela"
|
|
9
|
+
msgs = {
|
|
10
|
+
"W9011": ("RAI011: %s Suggestion: %s %s", "vikela-full-snapshot-write", "Unsafe detached projection, cross-owner live handle or retired lifetime write."),
|
|
11
|
+
"W9012": ("RAI012: %s Suggestion: %s %s", "vikela-protected-attribute", "JsonPit lifecycle metadata is engine-owned."),
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
def visit_module(self, node):
|
|
15
|
+
with node.stream() as stream:
|
|
16
|
+
raw = stream.read()
|
|
17
|
+
source = raw.decode(getattr(node, "file_encoding", None) or "utf-8") if isinstance(raw, bytes) else raw
|
|
18
|
+
source = source.removeprefix("\ufeff")
|
|
19
|
+
ignored = disabled_rules(node.file or ".")
|
|
20
|
+
for finding in analyze(source, node.file or "<module>"):
|
|
21
|
+
if finding.rule in ignored: continue
|
|
22
|
+
self.add_message("W9011" if finding.rule == "RAI011" else "W9012",
|
|
23
|
+
node=node, line=finding.line, col_offset=finding.column - 1,
|
|
24
|
+
args=(finding.reason, finding.suggestion, finding.documentation))
|
vikela/style.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""CR077 terminal rendering, based on RAIkeep's shared cli-style contract."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
import os
|
|
4
|
+
import platform
|
|
5
|
+
import re
|
|
6
|
+
import sys
|
|
7
|
+
import unicodedata
|
|
8
|
+
from . import __version__
|
|
9
|
+
|
|
10
|
+
_SWITCH = re.compile(r"(?<![\w/\-])--?[A-Za-z][A-Za-z0-9-]*")
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def enabled(stream=None):
|
|
14
|
+
stream = sys.stdout if stream is None else stream
|
|
15
|
+
return stream.isatty() and not os.environ.get("NO_COLOR") and os.environ.get("TERM") != "dumb"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def paint(text, color, enabled):
|
|
19
|
+
return f"\033[{color}m{text}\033[0m" if enabled else text
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def syntax(text: str, base_color: str = "36", enabled: bool = True) -> str:
|
|
23
|
+
if not enabled or not text:
|
|
24
|
+
return text
|
|
25
|
+
colors = [base_color] * len(text)
|
|
26
|
+
italic = [False] * len(text)
|
|
27
|
+
groups: list[tuple[int, int, str, bool]] = []
|
|
28
|
+
opened: list[tuple[int, str]] = []
|
|
29
|
+
quote = -1
|
|
30
|
+
for i, ch in enumerate(text):
|
|
31
|
+
if ch == "'":
|
|
32
|
+
if quote < 0:
|
|
33
|
+
quote = i
|
|
34
|
+
else:
|
|
35
|
+
colors[quote + 1:i] = ["33"] * (i - quote - 1)
|
|
36
|
+
quote = -1
|
|
37
|
+
if ch in "<([":
|
|
38
|
+
opened.append((i, ch))
|
|
39
|
+
elif ch in ">)]":
|
|
40
|
+
expected = {">": "<", ")": "(", "]": "["}[ch]
|
|
41
|
+
if opened and opened[-1][1] == expected:
|
|
42
|
+
start, kind = opened.pop()
|
|
43
|
+
depth = 0
|
|
44
|
+
choice = False
|
|
45
|
+
if kind == "(":
|
|
46
|
+
for inner in text[start + 1:i]:
|
|
47
|
+
if inner in "<([": depth += 1
|
|
48
|
+
elif inner in ">)]": depth -= 1
|
|
49
|
+
elif inner == "|" and depth == 0: choice = True
|
|
50
|
+
groups.append((start, i, kind, choice))
|
|
51
|
+
for start, end, kind, choice in sorted(groups, key=lambda g: g[1] - g[0], reverse=True):
|
|
52
|
+
if kind == "<":
|
|
53
|
+
in_choice = any(c and a < start and b > end for a, b, _, c in groups)
|
|
54
|
+
colors[start + 1:end] = ["35" if in_choice else "96"] * (end - start - 1)
|
|
55
|
+
italic[start + 1:end] = [True] * (end - start - 1)
|
|
56
|
+
elif kind == "[" or choice:
|
|
57
|
+
colors[start:end + 1] = ["35" if choice else "94"] * (end - start + 1)
|
|
58
|
+
for i, ch in enumerate(text):
|
|
59
|
+
if ch in "<>|":
|
|
60
|
+
colors[i], italic[i] = base_color, False
|
|
61
|
+
for match in _SWITCH.finditer(text):
|
|
62
|
+
colors[match.start():match.end()] = ["32"] * len(match.group())
|
|
63
|
+
result: list[str] = []
|
|
64
|
+
start = 0
|
|
65
|
+
while start < len(text):
|
|
66
|
+
end = start + 1
|
|
67
|
+
while end < len(text) and colors[end] == colors[start] and italic[end] == italic[start]: end += 1
|
|
68
|
+
result.append(paint(text[start:end], colors[start] + (";3" if italic[start] else ""), True))
|
|
69
|
+
start = end
|
|
70
|
+
return "".join(result)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def width(text):
|
|
75
|
+
cells = 0; previous = 0
|
|
76
|
+
for character in text:
|
|
77
|
+
if character == "\ufe0f":
|
|
78
|
+
# Emoji presentation widens a text-default symbol such as the shield.
|
|
79
|
+
if previous == 1: cells += 1
|
|
80
|
+
continue
|
|
81
|
+
if unicodedata.combining(character) or character == "\u200d": continue
|
|
82
|
+
previous = 2 if unicodedata.east_asian_width(character) in {"W", "F"} else 1
|
|
83
|
+
cells += previous
|
|
84
|
+
return cells
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def banner(color):
|
|
88
|
+
heading = f"🛡️ Vikela Python Mutation Guardrails (vikela v{__version__}) on {platform.node()}"
|
|
89
|
+
rule = " " + "─" * max(0, width(heading) - 2)
|
|
90
|
+
return "\n".join([paint(rule, "36", color), paint(heading, "1;36", color), paint(rule, "36", color)])
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def help_text():
|
|
94
|
+
color = enabled()
|
|
95
|
+
rows = [
|
|
96
|
+
("-h, --help", "", "32", "print options and examples"),
|
|
97
|
+
("-v, --version", "", "36", "print version information"),
|
|
98
|
+
("-n, --nologo", "", "95", "do not display the banner"),
|
|
99
|
+
("--json", "", "38;5;117", "write pure JSON findings to stdout"),
|
|
100
|
+
("--fix, --qondisa", "", "38;5;208", "apply only proven safe fixes; unavailable fixes remain suggestions"),
|
|
101
|
+
("--config <file>", "", "35", "read shared [tool.vikela] project configuration"),
|
|
102
|
+
("--disable <rule>", "🛡️", "38;5;75", "disable RAI011 or RAI012 (repeatable)"),
|
|
103
|
+
]
|
|
104
|
+
result = [banner(color), syntax("Usage: vikela <file.py|notebook.ipynb|directory> [--json] [--fix|--qondisa]", enabled=color), ""]
|
|
105
|
+
label_width = max(len(row[0]) for row in rows)
|
|
106
|
+
for label, glyph, base, description in rows:
|
|
107
|
+
result.append(syntax(label.ljust(label_width), base, color) + " " + paint(glyph, base, color) + " " * (4 - width(glyph)) + syntax(description, base, color))
|
|
108
|
+
result.extend(["", "Exit codes: 0 clean, 1 findings, 2 syntax/configuration, 4 internal/environment failure.",
|
|
109
|
+
"Checks never execute the inspected code. JSON and notebook checks never add a banner."])
|
|
110
|
+
return "\n".join(result)
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: vikela
|
|
3
|
+
Version: 4.6.0
|
|
4
|
+
Summary: Python mutation guardrails for JsonPit
|
|
5
|
+
Project-URL: Repository, https://github.com/Burkhardt/vikela
|
|
6
|
+
Project-URL: Documentation, https://github.com/Burkhardt/vikela/blob/main/docs/rules.md
|
|
7
|
+
Author: Dr. Rainer Burkhardt
|
|
8
|
+
License-Expression: Apache-2.0
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Requires-Python: >=3.12
|
|
11
|
+
Provides-Extra: dev
|
|
12
|
+
Requires-Dist: build; extra == 'dev'
|
|
13
|
+
Requires-Dist: ipython>=8; extra == 'dev'
|
|
14
|
+
Requires-Dist: pylint<5,>=3.3; extra == 'dev'
|
|
15
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
16
|
+
Requires-Dist: twine; extra == 'dev'
|
|
17
|
+
Provides-Extra: notebook
|
|
18
|
+
Requires-Dist: ipython>=8; extra == 'notebook'
|
|
19
|
+
Provides-Extra: pylint
|
|
20
|
+
Requires-Dist: pylint<5,>=3.3; extra == 'pylint'
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
|
|
23
|
+
<p align="center">
|
|
24
|
+
<img src="https://raw.githubusercontent.com/Burkhardt/vikela/main/assets/vikela-logo.svg" width="160" height="160" alt="Vikela Logo" />
|
|
25
|
+
</p>
|
|
26
|
+
|
|
27
|
+
<h1 align="center">Vikela 🛡️</h1>
|
|
28
|
+
|
|
29
|
+
<p align="center">
|
|
30
|
+
<strong>Python mutation guardrails and AST linter for JsonPit.</strong><br>
|
|
31
|
+
<em>The defensive shield protecting distributed state from concurrent cloud replica stomps.</em>
|
|
32
|
+
</p>
|
|
33
|
+
|
|
34
|
+
<p align="center">
|
|
35
|
+
<a href="https://pypi.org/project/vikela/"><img src="https://img.shields.io/badge/PyPI-vikela-D4AF37?style=flat-square&logo=pypi" alt="PyPI"></a>
|
|
36
|
+
<a href="https://github.com/Burkhardt/RAIkeep/blob/main/doc/CR077_AIA_and_AfricaStage_to_RAIkeep_Vikela_and_JsonPit_Mutation_Guardrails.md"><img src="https://img.shields.io/badge/CR-CR077-blue?style=flat-square" alt="Specification"></a>
|
|
37
|
+
<a href="docs/VIKELA_VISUAL_IDENTITY_AND_ICON_SPEC.md"><img src="https://img.shields.io/badge/Identity-Modernist%20Ihawu-AA8214?style=flat-square" alt="Design Spec"></a>
|
|
38
|
+
</p>
|
|
39
|
+
|
|
40
|
+
---
|
|
41
|
+
|
|
42
|
+
## Overview
|
|
43
|
+
|
|
44
|
+
**Vikela** (*isiZulu: "to protect / shield"*) provides static analysis and mutation guardrails for `JsonPit` and its surrounding framework across the fleet. It functions both as a standalone CLI (`vikela`) and as a native Pylint checker plugin (`pylint --load-plugins=vikela`).
|
|
45
|
+
|
|
46
|
+
### The Twin-Shield Doctrine
|
|
47
|
+
* **C# development (.NET):** Checked by `RaiGuard`.
|
|
48
|
+
* **Python development:** Checked by `vikela`; JsonPit itself enforces runtime mutation guards.
|
|
49
|
+
* **The Straightening Action (`--qondisa`):** An official first-class alias for `--fix` (*isiZulu: "to straighten out / rectify"*), reserved for proven safe repairs. Version 4.6.0 provides suggestions and has no approved automatic rewrites.
|
|
50
|
+
|
|
51
|
+
---
|
|
52
|
+
|
|
53
|
+
## Core Rules
|
|
54
|
+
|
|
55
|
+
| Rule ID | Diagnostic Symbol | Description |
|
|
56
|
+
| :--- | :--- | :--- |
|
|
57
|
+
| **`RAI011`** | `vikela-full-snapshot-write` | Prevents full-snapshot read-modify-writes that erase concurrent cloud replica fields. |
|
|
58
|
+
| **`RAI012`** | `vikela-protected-attribute` | Protects immutable lifecycle and schema attributes from unauthorized client modification. |
|
|
59
|
+
|
|
60
|
+
---
|
|
61
|
+
|
|
62
|
+
## Terminal & CLI Experience
|
|
63
|
+
|
|
64
|
+
```bash
|
|
65
|
+
# Standard Scan
|
|
66
|
+
vikela .
|
|
67
|
+
|
|
68
|
+
# Request safe fixes (v4.6.0 reports suggestions and leaves source unchanged)
|
|
69
|
+
vikela src/ --qondisa
|
|
70
|
+
|
|
71
|
+
# Pure JSON for CI/CD audit pipelines
|
|
72
|
+
vikela src/ --json
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
---
|
|
76
|
+
|
|
77
|
+
## IDE & Editor Integration
|
|
78
|
+
|
|
79
|
+
### VS Code
|
|
80
|
+
Configure in `.vscode/settings.json`:
|
|
81
|
+
```json
|
|
82
|
+
{
|
|
83
|
+
"pylint.args": [
|
|
84
|
+
"--load-plugins=vikela"
|
|
85
|
+
]
|
|
86
|
+
}
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
### JupyterLab
|
|
90
|
+
```python
|
|
91
|
+
%load_ext vikela
|
|
92
|
+
|
|
93
|
+
%%vikela
|
|
94
|
+
# Checks this cell WITHOUT executing it
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
---
|
|
98
|
+
|
|
99
|
+
## Visual Identity & Heraldry
|
|
100
|
+
Vikela's emblem is the **Modernist Ihawu**—drawing from the elliptical geometry of the traditional Nguni shield, anchored by the central **Qondisa Axis** (the plumb line that straightens crooked code).
|
|
101
|
+
|
|
102
|
+
* **Design Specification:** [`docs/VIKELA_VISUAL_IDENTITY_AND_ICON_SPEC.md`](docs/VIKELA_VISUAL_IDENTITY_AND_ICON_SPEC.md)
|
|
103
|
+
* **Master Vector:** [`assets/logo.svg`](assets/logo.svg)
|
|
104
|
+
* **Curator:** Koyo (Chief Marketing & Web Design Assistant)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
## Version 4.6.0 installation and contracts
|
|
108
|
+
|
|
109
|
+
Vikela is optional development tooling alongside RAIkeep 4.6.0. Neither jsonpit nor
|
|
110
|
+
jpit depends on it. Until publication, install from this checkout in a development
|
|
111
|
+
virtual environment:
|
|
112
|
+
|
|
113
|
+
```sh
|
|
114
|
+
python -m pip install -e '.[dev]'
|
|
115
|
+
python -m pytest
|
|
116
|
+
vikela -v
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
After publication, install `vikela==4.6.0` for the independent CLI, or
|
|
120
|
+
`vikela[pylint]==4.6.0` inside the project's interpreter for editor checks.
|
|
121
|
+
`vikela[notebook]==4.6.0` adds IPython support in the chosen kernel interpreter.
|
|
122
|
+
A global CLI environment alone does not expose the checker in another venv.
|
|
123
|
+
|
|
124
|
+
Exit codes: **0** clean; **1** findings; **2** syntax/configuration;
|
|
125
|
+
**4** internal/environment failure. Pylint retains its own native exit codes.
|
|
126
|
+
`--json` emits a pure array; operational errors go to stderr. Scans do not import
|
|
127
|
+
or execute the inspected application. `--fix` and `--qondisa` are exact aliases;
|
|
128
|
+
no speculative field-dropping rewrite is available in 4.6.0.
|
|
129
|
+
|
|
130
|
+
- [Rules, shared project configuration and analysis limits](docs/rules.md)
|
|
131
|
+
- [VS Code, PyCharm and JupyterLab setup](docs/editors.md)
|
|
132
|
+
|
|
133
|
+
The CLI and plugin share `[tool.vikela]` configuration in pyproject.toml, with a
|
|
134
|
+
`disable` array of logical rule IDs. Checks are bounded and conservative: no
|
|
135
|
+
findings does not prove arbitrary dynamic code safe. Notebook scans follow
|
|
136
|
+
source-cell document order, not previous kernel execution order.
|
|
137
|
+
|
|
138
|
+
Publication/provisioning is orchestrated by Engenho; production server nodes do
|
|
139
|
+
not receive development lint tooling by default. Native PyCharm inspections are
|
|
140
|
+
milestone 2; milestone 1 supplies an External Tool configuration.
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
vikela/__init__.py,sha256=RHuOX-acH6_MeUZu18ZAeP7au-OEzXu0stQkrgFJKWQ,557
|
|
2
|
+
vikela/__main__.py,sha256=ee5vE0xcUZM3fPmxicvcw-IJXkm6nOwxARREHBWpF8Q,47
|
|
3
|
+
vikela/analysis.py,sha256=GBgKgKVWVDaq0q6B8KWMp4p4s0gNrewnbe2TM6zJL0I,16381
|
|
4
|
+
vikela/cli.py,sha256=xej58eMzs793nPh_6dNZv9aeDCsd_vqNAz3De90WztQ,5023
|
|
5
|
+
vikela/config.py,sha256=a7rYEIDNsRv30tS5OGq9X4RvCxZ4Hl6W3XqKP4FBIsI,1362
|
|
6
|
+
vikela/notebook.py,sha256=nhquCbM97WxyYBHiWhQiUw-p8dNdL9IIzwaD3c6kPzk,465
|
|
7
|
+
vikela/pylint_plugin.py,sha256=wJi4SGxnGN5QNwGnNbj6eL83NXF01JXJv_dwi4U1oGw,1111
|
|
8
|
+
vikela/style.py,sha256=bMAq6-Zins5yJhTOlQKId3WAapiMwlsM4kQyi3jJtw4,4234
|
|
9
|
+
vikela-4.6.0.dist-info/METADATA,sha256=6Q2mjo6dKNigqgzTfSe_42s3TeBCV-9dOJmp2iAmTS0,5445
|
|
10
|
+
vikela-4.6.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
11
|
+
vikela-4.6.0.dist-info/entry_points.txt,sha256=Y6TEu9LRqD0bsm-2rxs_B_2f6VPV7Fp3_Rg8HSMPWto,43
|
|
12
|
+
vikela-4.6.0.dist-info/licenses/LICENSE,sha256=44MnwGRgJIs4OmuNbHs7OvGgwlf_nj-d7DK9PRTtddM,9155
|
|
13
|
+
vikela-4.6.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,176 @@
|
|
|
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
|