gdp-wired 0.50.3 → 0.50.5
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.
- package/README.md +4 -0
- package/dist/core/agent-consult/cli.d.ts +2 -0
- package/dist/core/agent-consult/cli.js +19 -0
- package/dist/core/agent-consult/protocol.d.ts +93 -0
- package/dist/core/agent-consult/protocol.js +154 -0
- package/dist/core/agent-consult/service.d.ts +435 -0
- package/dist/core/agent-consult/service.js +84 -0
- package/dist/core/agent-consult/session.d.ts +13 -0
- package/dist/core/agent-consult/session.js +163 -0
- package/dist/core/agent-consult/source-service.d.ts +83 -0
- package/dist/core/agent-consult/source-service.js +51 -0
- package/dist/core/agent-consult/tsconfig.json +5 -0
- package/dist/core/agent-consult/worker.d.ts +1 -0
- package/dist/core/agent-consult/worker.js +17 -0
- package/dist/core/agent-consult/workspace.d.ts +27 -0
- package/dist/core/agent-consult/workspace.js +66 -0
- package/dist/core/agent-consult.d.ts +8 -0
- package/dist/core/agent-consult.js +6 -0
- package/dist/core/cli.d.ts +5 -0
- package/dist/core/cli.js +118 -49
- package/dist/core/extract-check.d.ts +1 -0
- package/dist/core/extract-check.js +4 -4
- package/dist/core/extract-py.js +11 -1
- package/dist/core/extract-step.js +3 -3
- package/dist/core/py/harness.py +125 -16
- package/docs/agent-consult-workspace-check.md +118 -0
- package/docs/agent-consult.md +151 -0
- package/examples/agent-consult.json +22 -0
- package/package.json +11 -3
package/dist/core/py/harness.py
CHANGED
|
@@ -13,6 +13,11 @@ EFF = {}
|
|
|
13
13
|
HIT = set()
|
|
14
14
|
S = {}
|
|
15
15
|
NATIVE_OBJECTS = {}
|
|
16
|
+
NATIVE_INVOCATION = [0]
|
|
17
|
+
NATIVE_EVENTS = [None]
|
|
18
|
+
NATIVE_EVENT_ERROR = [None]
|
|
19
|
+
NATIVE_CALL_TYPES = {}
|
|
20
|
+
NATIVE_SOURCE_CODES = {}
|
|
16
21
|
|
|
17
22
|
def datetime_in(v, unit):
|
|
18
23
|
epoch = datetime.datetime(1970, 1, 1, tzinfo=datetime.timezone.utc if unit == 'datetime-utc' else None)
|
|
@@ -524,6 +529,26 @@ def raised(r):
|
|
|
524
529
|
except Exception:
|
|
525
530
|
e = cls.__new__(cls); e.args = ('gdp: raised where the request says',); return e
|
|
526
531
|
|
|
532
|
+
# Only actual, invocation-local outcomes are evidence. Repeated calls must agree.
|
|
533
|
+
def native_record(key, value=None, error=None):
|
|
534
|
+
events = NATIVE_EVENTS[0]
|
|
535
|
+
if events is None: return
|
|
536
|
+
try:
|
|
537
|
+
if error is not None:
|
|
538
|
+
outcome, kind = {'kind': 'raised', 'raised': type(error).__name__}, type(error)
|
|
539
|
+
else:
|
|
540
|
+
if type(value) not in (type(None), bool, str, int, float):
|
|
541
|
+
raise ValueError('unsupported native external-call value')
|
|
542
|
+
if type(value) in (int, float) and (not (-9007199254740991 <= value <= 9007199254740991) or int(value) != value):
|
|
543
|
+
raise ValueError('native external-call value is outside exact integer range')
|
|
544
|
+
outcome, kind = {'kind': 'returned', 'value': value}, type(value)
|
|
545
|
+
if key in events['calls'] and (events['calls'][key] != outcome or NATIVE_CALL_TYPES[key] is not kind):
|
|
546
|
+
raise ValueError('native external call returned inconsistent values in one invocation')
|
|
547
|
+
events['calls'][key] = outcome
|
|
548
|
+
NATIVE_CALL_TYPES[key] = kind
|
|
549
|
+
except Exception as e:
|
|
550
|
+
NATIVE_EVENT_ERROR[0] = NATIVE_EVENT_ERROR[0] or f'{type(e).__name__}: {e}'[:300]
|
|
551
|
+
|
|
527
552
|
def stub(key, is_async, orig=None):
|
|
528
553
|
# (orig: a call left out, run as it is unless the request says it raises)
|
|
529
554
|
def value(a_, k_):
|
|
@@ -534,10 +559,22 @@ def stub(key, is_async, orig=None):
|
|
|
534
559
|
return build(a, {})
|
|
535
560
|
if is_async:
|
|
536
561
|
async def f(*a, **k):
|
|
537
|
-
|
|
538
|
-
|
|
562
|
+
try:
|
|
563
|
+
v = value(a, k)
|
|
564
|
+
v = (await v) if orig is not None and inspect.isawaitable(v) else v
|
|
565
|
+
except Exception as e:
|
|
566
|
+
native_record(key, error=e)
|
|
567
|
+
raise
|
|
568
|
+
native_record(key, value=v)
|
|
569
|
+
return v
|
|
539
570
|
return f
|
|
540
|
-
def g(*a, **k):
|
|
571
|
+
def g(*a, **k):
|
|
572
|
+
try: v = value(a, k)
|
|
573
|
+
except Exception as e:
|
|
574
|
+
native_record(key, error=e)
|
|
575
|
+
raise
|
|
576
|
+
native_record(key, value=v)
|
|
577
|
+
return v
|
|
541
578
|
return g
|
|
542
579
|
|
|
543
580
|
def patch_target(p):
|
|
@@ -558,7 +595,7 @@ def hello(req):
|
|
|
558
595
|
S['root'] = os.path.realpath(req['root'])
|
|
559
596
|
# Only files the reader actually used, including imported bases; never arbitrary repository imports.
|
|
560
597
|
S['sources'] = {os.path.realpath(os.path.join(S['root'], name)): name for name, _ in req['arms']}
|
|
561
|
-
REAL.clear(); HIT.clear()
|
|
598
|
+
REAL.clear(); HIT.clear(); NATIVE_SOURCE_CODES.clear()
|
|
562
599
|
sys.path.insert(0, req['root'])
|
|
563
600
|
if os.environ.get('DJANGO_SETTINGS_MODULE'):
|
|
564
601
|
import django
|
|
@@ -592,7 +629,7 @@ def hello(req):
|
|
|
592
629
|
S['cls'] = getattr(mod, req['cls'].rpartition('.')[2]) if req.get('cls') else None
|
|
593
630
|
S['loop'] = asyncio.new_event_loop()
|
|
594
631
|
asyncio.set_event_loop(S['loop'])
|
|
595
|
-
return {'ok': True, 'nativeSnapshot': 1, 'nativeBindings': 1, 'nativeEquality': 'scalar'}
|
|
632
|
+
return {'ok': True, 'nativeSnapshot': 1, 'nativeBindings': 1, 'nativeObservations': 1, 'nativeEquality': 'scalar'}
|
|
596
633
|
|
|
597
634
|
def make(args):
|
|
598
635
|
global OBJ_STORES
|
|
@@ -626,6 +663,47 @@ def set_globals(stores):
|
|
|
626
663
|
if isinstance(table, ORMTable): table.install()
|
|
627
664
|
for g in S.get('globals') or []: setattr(importlib.import_module(g['mod']), g['name'], stores[g['name']])
|
|
628
665
|
|
|
666
|
+
def native_callable(fn, method):
|
|
667
|
+
native_fn = fn.__func__ if isinstance(fn, types.MethodType) else fn
|
|
668
|
+
seen = set()
|
|
669
|
+
while True:
|
|
670
|
+
if not isinstance(native_fn, types.FunctionType):
|
|
671
|
+
raise ValueError('unsupported native callable for parameter capture')
|
|
672
|
+
if id(native_fn) in seen or len(seen) >= 32:
|
|
673
|
+
raise ValueError('customized native signature metadata is unsupported')
|
|
674
|
+
seen.add(id(native_fn))
|
|
675
|
+
if any(dict.__contains__(native_fn.__dict__, name) for name in ('__signature__', '__text_signature__')):
|
|
676
|
+
raise ValueError('customized native signature metadata is unsupported')
|
|
677
|
+
if not dict.__contains__(native_fn.__dict__, '__wrapped__'): break
|
|
678
|
+
native_fn = dict.__getitem__(native_fn.__dict__, '__wrapped__')
|
|
679
|
+
expected = (S.get('nativeMethods') or {}).get(method)
|
|
680
|
+
if len(seen) > 1 and expected is None:
|
|
681
|
+
raise ValueError('customized native signature metadata is unsupported')
|
|
682
|
+
if expected is not None and (os.path.realpath(native_fn.__code__.co_filename) != os.path.realpath(os.path.join(S['root'], expected['file'])) or native_fn.__code__.co_name != method or native_fn.__code__.co_firstlineno != expected['line']):
|
|
683
|
+
raise ValueError('customized native signature metadata is unsupported')
|
|
684
|
+
if len(seen) > 1:
|
|
685
|
+
file = os.path.realpath(native_fn.__code__.co_filename)
|
|
686
|
+
if file not in NATIVE_SOURCE_CODES:
|
|
687
|
+
with open(file, 'rb') as source: compiled = compile(source.read(), native_fn.__code__.co_filename, 'exec', dont_inherit=True)
|
|
688
|
+
codes = []
|
|
689
|
+
def collect(code):
|
|
690
|
+
codes.append(code)
|
|
691
|
+
for value in code.co_consts:
|
|
692
|
+
if isinstance(value, types.CodeType): collect(value)
|
|
693
|
+
collect(compiled)
|
|
694
|
+
NATIVE_SOURCE_CODES[file] = codes
|
|
695
|
+
candidates = [code for code in NATIVE_SOURCE_CODES[file] if code.co_name == method and code.co_firstlineno == expected['line']]
|
|
696
|
+
if len(candidates) != 1 or candidates[0] != native_fn.__code__:
|
|
697
|
+
raise ValueError('customized native signature metadata is unsupported')
|
|
698
|
+
# A wrapper chain nominates a candidate only. Inspect genuine code/defaults;
|
|
699
|
+
# invocation below must observe this exact code with unchanged arguments.
|
|
700
|
+
fresh = types.FunctionType(native_fn.__code__, native_fn.__globals__, native_fn.__name__, native_fn.__defaults__, native_fn.__closure__)
|
|
701
|
+
fresh.__kwdefaults__ = native_fn.__kwdefaults__
|
|
702
|
+
receiver = fn.__self__ if isinstance(fn, types.MethodType) else None
|
|
703
|
+
receiver_name = next(iter(inspect.signature(fresh).parameters), None) if isinstance(fn, types.MethodType) else None
|
|
704
|
+
signature = inspect.signature(types.MethodType(fresh, receiver) if receiver_name is not None else fresh, follow_wrapped=False)
|
|
705
|
+
return native_fn.__code__, signature, receiver_name, receiver
|
|
706
|
+
|
|
629
707
|
def call(req):
|
|
630
708
|
obj, stores = OBJS[req['id']]
|
|
631
709
|
global OBJ_STORES
|
|
@@ -640,22 +718,41 @@ def call(req):
|
|
|
640
718
|
try: kwargs = fixed_args(req['a'], {})
|
|
641
719
|
except OverflowError as e:
|
|
642
720
|
return {'outside': f'argument outside the declared runtime domain: {e}'}
|
|
643
|
-
#
|
|
644
|
-
#
|
|
721
|
+
# Snapshot call-bound values before a wrapper/body can mutate them. Admission
|
|
722
|
+
# also requires the source method's real entry frame, never just __wrapped__.
|
|
723
|
+
target, entered = None, None
|
|
645
724
|
try:
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
raise ValueError('unsupported native callable for parameter capture')
|
|
649
|
-
if any(dict.__contains__(native_fn.__dict__, name) for name in ('__signature__', '__wrapped__', '__text_signature__')):
|
|
650
|
-
raise ValueError('customized native signature metadata is unsupported')
|
|
651
|
-
bound = inspect.signature(fn, follow_wrapped=False).bind(**kwargs)
|
|
725
|
+
target, signature, receiver_name, receiver = native_callable(fn, req['m'])
|
|
726
|
+
bound = signature.bind(**kwargs)
|
|
652
727
|
bound.apply_defaults()
|
|
653
728
|
native_bindings = {'snapshot': native_state(types.SimpleNamespace(**bound.arguments), select=False)}
|
|
654
729
|
except Exception as e:
|
|
730
|
+
target = None
|
|
655
731
|
native_bindings = {'error': f'{type(e).__name__}: {e}'[:300]}
|
|
732
|
+
def capture(frame, event, arg):
|
|
733
|
+
nonlocal entered, native_bindings
|
|
734
|
+
if event == 'call' and frame.f_code is target:
|
|
735
|
+
if entered is not None and frame is not entered:
|
|
736
|
+
native_bindings = {'error': 'native source method entered more than once in one invocation'}
|
|
737
|
+
elif entered is None:
|
|
738
|
+
entered = frame
|
|
739
|
+
try:
|
|
740
|
+
if receiver_name is not None and frame.f_locals.get(receiver_name) is not receiver:
|
|
741
|
+
raise ValueError('native source method receiver differs from the called receiver')
|
|
742
|
+
values = {name: frame.f_locals[name] for name in bound.arguments}
|
|
743
|
+
actual = native_state(types.SimpleNamespace(**values), select=False)
|
|
744
|
+
if json.dumps(actual['root']['items']) != json.dumps(native_bindings['snapshot']['root']['items']):
|
|
745
|
+
raise ValueError('decorator changed native arguments before source method entry')
|
|
746
|
+
except Exception as e:
|
|
747
|
+
native_bindings = {'error': f'{type(e).__name__}: {e}'[:300]}
|
|
748
|
+
return tracer(frame, event, arg)
|
|
656
749
|
before = frames(obj if S['cls'] is not None else None)
|
|
657
750
|
snap = state_of(obj, stores) if S.get('discard') and S['cls'] is not None else None
|
|
658
|
-
|
|
751
|
+
NATIVE_INVOCATION[0] += 1
|
|
752
|
+
NATIVE_EVENTS[0] = {'invocation': NATIVE_INVOCATION[0], 'calls': {}}
|
|
753
|
+
NATIVE_EVENT_ERROR[0] = None
|
|
754
|
+
NATIVE_CALL_TYPES.clear()
|
|
755
|
+
sys.settrace(capture)
|
|
659
756
|
try:
|
|
660
757
|
with pinned(): out = run(fn(**kwargs))
|
|
661
758
|
err = None
|
|
@@ -667,11 +764,22 @@ def call(req):
|
|
|
667
764
|
with open(os.environ['GDP_HARNESS_LOG'], 'a') as f: f.write(f"{req['m']} {json.dumps(req.get('answers'))}\n{traceback.format_exc()}\n")
|
|
668
765
|
finally:
|
|
669
766
|
sys.settrace(None)
|
|
767
|
+
if target is not None and entered is None:
|
|
768
|
+
native_bindings = {'error': 'native source method entry was not observed'}
|
|
769
|
+
try:
|
|
770
|
+
if NATIVE_EVENT_ERROR[0]: native_observations = {'error': NATIVE_EVENT_ERROR[0]}
|
|
771
|
+
else:
|
|
772
|
+
events = NATIVE_EVENTS[0]
|
|
773
|
+
calls = types.SimpleNamespace(**{key: types.SimpleNamespace(**value) for key, value in events['calls'].items()})
|
|
774
|
+
native_observations = {'snapshot': native_state(types.SimpleNamespace(invocation=events['invocation'], calls=calls), select=False)}
|
|
775
|
+
except Exception as e:
|
|
776
|
+
native_observations = {'error': f'{type(e).__name__}: {e}'[:300]}
|
|
777
|
+
finally: NATIVE_EVENTS[0] = None
|
|
670
778
|
if err is not None and snap is not None: set_state(obj, stores, snap)
|
|
671
779
|
after = frames(obj if S['cls'] is not None else None)
|
|
672
780
|
for k in before:
|
|
673
781
|
if after.get(k) != before[k]: return {'frame': k}
|
|
674
|
-
return {'out': tag(out), 'nativeBindings': native_bindings, **({'err': err} if err is not None else {}), **({'effects': dict(EFF)} if EFF else {})}
|
|
782
|
+
return {'out': tag(out), 'nativeBindings': native_bindings, 'nativeObservations': native_observations, **({'err': err} if err is not None else {}), **({'effects': dict(EFF)} if EFF else {})}
|
|
675
783
|
|
|
676
784
|
# Native observation transport for ordered containers. Retain real references
|
|
677
785
|
# so Python cannot recycle an address and manufacture cross-snapshot identity.
|
|
@@ -679,6 +787,7 @@ def native_state(obj, select=True):
|
|
|
679
787
|
seen = set()
|
|
680
788
|
count = [0]
|
|
681
789
|
def encode(value, names=None):
|
|
790
|
+
if type(value) is FakeStore: value = value.data
|
|
682
791
|
count[0] += 1
|
|
683
792
|
if count[0] > 10000: raise ValueError('native snapshot exceeds node bound')
|
|
684
793
|
if value is None or isinstance(value, (str, bool)): return value
|
|
@@ -706,7 +815,7 @@ def native_state(obj, select=True):
|
|
|
706
815
|
fields = vars(value)
|
|
707
816
|
if names is not None: fields = {name: fields[name] for name in names}
|
|
708
817
|
return {'kind': 'object', 'id': ident, 'items': [[k, encode(v)] for k, v in fields.items()]}
|
|
709
|
-
roots = sorted({l['path'][0] for l in S['leaves'] if l.get('path') and l['kind'] != 'frame'})
|
|
818
|
+
roots = sorted({l['path'][0] for l in S['leaves'] if l.get('path') and l['kind'] != 'frame'} | {l['store'].split('.')[0] for l in S['leaves'] if l.get('store')})
|
|
710
819
|
return {'version': 1, 'root': encode(obj, roots if select else None)}
|
|
711
820
|
|
|
712
821
|
def main():
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
# Workspace `check`
|
|
2
|
+
|
|
3
|
+
Use `check` to read laws from a trusted Python or plain TypeScript/JavaScript
|
|
4
|
+
workspace through the same engine as the CLI. The default remains data-only;
|
|
5
|
+
filesystem access requires explicit server configuration.
|
|
6
|
+
|
|
7
|
+
The native edit/check fixture exercises both Python and TypeScript through the
|
|
8
|
+
built Node MCP server: a bounded implementation is proven, a conservative edit
|
|
9
|
+
remains proven, and a bad edit is broken with a real run. These results retain
|
|
10
|
+
`translation: sampled`; they are not exhaustive native equivalence certificates.
|
|
11
|
+
|
|
12
|
+
## Server-owned authority; data-only default
|
|
13
|
+
|
|
14
|
+
`createConsultation()` and the stdio executable with no root configuration keep
|
|
15
|
+
the old data-only default. All six tools are listed; `check` returns the typed
|
|
16
|
+
`workspace-unconfigured` refusal until the server explicitly opts in:
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
import {createConsultation} from 'gdp-wired/agent-consult'
|
|
20
|
+
|
|
21
|
+
const session = createConsultation({workspaceRoots: ['/absolute/trusted/project']})
|
|
22
|
+
const receipt = await session.call('check', {
|
|
23
|
+
file: '/absolute/trusted/project/counter.py',
|
|
24
|
+
budget: {work: 5000000, apiCalls: 64, candidates: 2}
|
|
25
|
+
})
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
For the stdio server, the operator sets `GDP_AGENT_CONSULT_ROOTS` to a JSON array
|
|
29
|
+
of absolute directories in its startup environment. CLI arguments still cannot
|
|
30
|
+
choose roots, source modules, flags or interpreters. Root configuration is never
|
|
31
|
+
accepted in tool arguments, including nested `options`, `root`, `roots`, `python`
|
|
32
|
+
or `workspaceRoots`. The existing five tools remain data-only.
|
|
33
|
+
|
|
34
|
+
The server canonicalizes/freezes at most16 roots once. Requests must name absolute
|
|
35
|
+
local regular files (no URLs, directories, devices, relative paths or `..`).
|
|
36
|
+
Containment uses `path.relative`, not a string prefix. Both root and file symlinks
|
|
37
|
+
are realpathed; out-of-root results and sibling-prefix paths are refused. Source
|
|
38
|
+
reads used by the guard use a no-follow/nonblocking read-only FD and fstat; each
|
|
39
|
+
file is capped at128KiB. Root dev/inode and file identity/content are rechecked
|
|
40
|
+
before/after the pipeline; source and relative TS dependency hashes bind the
|
|
41
|
+
returned revision. Replacements or edits observed during a check refuse rather
|
|
42
|
+
than silently bind another revision.
|
|
43
|
+
|
|
44
|
+
**Not an OS sandbox:** the configured root is a trust grant to execute the existing
|
|
45
|
+
extractor/runtime/project code. Python may import dependencies; TypeScript native
|
|
46
|
+
replay may execute code. Those runtimes can read dependencies and access resources
|
|
47
|
+
outside the root with the worker's OS permissions. No claim of transitive import
|
|
48
|
+
confinement, hostile-code containment, or atomic filesystem snapshots is made.
|
|
49
|
+
An adversarial process can race mutable files between rechecks. Use a stable,
|
|
50
|
+
trusted checkout and externally enforced OS isolation for untrusted code. Cancellation
|
|
51
|
+
joins the direct worker; this is not a descendant-process sandbox/reaper guarantee.
|
|
52
|
+
No arbitrary shell launcher is added; only the installed fixed-path worker runs.
|
|
53
|
+
|
|
54
|
+
## Shared engine, explicit initial scope
|
|
55
|
+
|
|
56
|
+
`packages/cli/bin.js` delegates to `core/cli.ts`. The latter now has one generator
|
|
57
|
+
pipeline for entry enumeration, initializer expansion, laws, proof/replay and
|
|
58
|
+
proposals. Ordinary CLI calls drive it asynchronously; workspace check preloads
|
|
59
|
+
Python/plainTS extractor modules as initialization and then drives that **same**
|
|
60
|
+
pipeline synchronously inside the counted root. No copied extraction/proof engine
|
|
61
|
+
and no `withBudget(Promise)`.
|
|
62
|
+
|
|
63
|
+
Supported initially: Python and plain TypeScript/JavaScript (`.py`, `.ts`, `.mts`,
|
|
64
|
+
`.tsx`, `.js`, `.mjs`). Effect/XState, async lemma expansion and other CLI language
|
|
65
|
+
frontends are explicitly refused. The initial workspace profile does **not** read
|
|
66
|
+
project GDP configuration: no ancestor search, no config-specified interpreters,
|
|
67
|
+
root overrides, certificate writes or CLI switches. Ordinary CLI defaults/config
|
|
68
|
+
behavior remain unchanged. Rules needing config receive the extractor's refusal
|
|
69
|
+
or unknown rather than substituted modeling choices.
|
|
70
|
+
|
|
71
|
+
The returned `result.rules` is the existing structured CLI `RuleOut[]`: stated
|
|
72
|
+
laws, refusal reasons, replayed runs where available, and proposals with paste-ready
|
|
73
|
+
language comments in `where`. `proven` requires a nonempty stated law set all
|
|
74
|
+
reported proven by that engine; `broken` requires a stated broken law with a real
|
|
75
|
+
run; otherwise the aggregate is `unknown` with a reason. Each rule/law retains its
|
|
76
|
+
own detailed verdict. `check` does not populate the scalar-model `status` registry.
|
|
77
|
+
|
|
78
|
+
**Evidence boundary:** a model-only result with `translation: unchecked` remains
|
|
79
|
+
unknown even when `kernelProven: true`. When the existing engine supplies a native
|
|
80
|
+
law journal, its `sampled` or `exhaustive` profile and observation count are retained.
|
|
81
|
+
The current Python/TypeScript demo uses sampled journals. A checked symbolic proof
|
|
82
|
+
plus sampled native observations does not establish universal source equivalence.
|
|
83
|
+
This adapter neither upgrades unchecked results nor invents counterexample runs.
|
|
84
|
+
|
|
85
|
+
## Budget coverage
|
|
86
|
+
|
|
87
|
+
One `withBudget` root and sticky capacity-refusal boundary surround synchronous
|
|
88
|
+
extraction, law parsing, proofs, replay, proposals, source receipt construction and
|
|
89
|
+
serialization validation. Each extraction and top-level proof/step/liveness/two-run
|
|
90
|
+
API call is admitted against `apiCalls`. API exhaustion is also sticky, so existing
|
|
91
|
+
CLI catch-and-return-unknown handlers cannot turn exhaustion into a successful
|
|
92
|
+
partial proof receipt. Proposal candidates are finite and capped by the request
|
|
93
|
+
hint (at most40); CLI wall-clock stops/telemetry are disabled only for this counted
|
|
94
|
+
synchronous path. Ordinary CLI wall behavior is unchanged.
|
|
95
|
+
|
|
96
|
+
Exact work/counter deltas and profile identity are retained. Counted work means
|
|
97
|
+
**existing engine sinks**, not CPU instructions: module initialization, filesystem
|
|
98
|
+
bytes/identity/hash operations, unmetered frontend parsing, external interpreter
|
|
99
|
+
runtime and project execution are not charged to the work vector. Source-byte and
|
|
100
|
+
API caps are separate controls. These exclusions are explicit in every source
|
|
101
|
+
budget receipt; external runtime is not misrepresented as counted work.
|
|
102
|
+
|
|
103
|
+
## Development checks
|
|
104
|
+
|
|
105
|
+
After normal dependency preparation, run these checks in the project's test environment:
|
|
106
|
+
|
|
107
|
+
1. `bunx tsc -p core/agent-consult/tsconfig.json --noEmit`
|
|
108
|
+
2. `GDP_WORK_FULL=1 bun test core/agent-consult/workspace.test.ts core/agent-consult.test.ts research/agent-tools/protocol.test.ts research/agent-tools/service.test.ts`
|
|
109
|
+
3. The existing CLI, budget ownership, watchdog and package regression suites.
|
|
110
|
+
4. `bun scripts/build.ts`
|
|
111
|
+
5. `node scripts/agent-consult-workspace-demo.mjs > "$SUPERCOMPUTER_OUTPUT_DIR/workspace-check-transcript.jsonl"`
|
|
112
|
+
|
|
113
|
+
The last command creates temporary Python and TS files, initializes/lists the
|
|
114
|
+
built Node MCP server, edits each through good/good-edit/bad versions, and logs
|
|
115
|
+
actual edit/request/response/observation JSONL. It requires successful extraction,
|
|
116
|
+
changing source revisions, sampled native-law observations for the good edits,
|
|
117
|
+
and real runs for the bad edits. The server must close cleanly after stdin EOF.
|
|
118
|
+
The workspace suite is also registered in the default CI test roster.
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
# Agent consultation: MCP and library
|
|
2
|
+
|
|
3
|
+
The supported adapter asks the **existing** gdp-wired engines whether a scalar-natural
|
|
4
|
+
model law has a checked proof, a reachable counterexample, or a missing inductive
|
|
5
|
+
invariant. It adds no inference/proof algorithm. This is a package integration, not
|
|
6
|
+
a new proof capability or a native/source-conformance certification. The counted
|
|
7
|
+
work profile is still provisional research machinery. Do not use `ok: true` alone
|
|
8
|
+
as a proof: require each relevant `proven === true && checked === true`.
|
|
9
|
+
|
|
10
|
+
## Start and configure
|
|
11
|
+
|
|
12
|
+
After installing a version of `gdp-wired` containing this surface (this change does
|
|
13
|
+
not publish one), run `gdp-wired-agent-consult`. Node >=20 is sufficient; no Bun,
|
|
14
|
+
MCP SDK, credentials, network service or model provider is needed for the data-only tools.
|
|
15
|
+
Opt-in workspace extraction additionally needs TypeScript beside the package and the
|
|
16
|
+
source language runtime (Python for `.py`), exactly as the CLI does. In a source checkout the equivalent is
|
|
17
|
+
`bun core/agent-consult/cli.ts`; build with the repository's normal build before
|
|
18
|
+
running `node dist/core/agent-consult/cli.js`.
|
|
19
|
+
|
|
20
|
+
Generic MCP client configuration (configure your client explicitly; nothing is
|
|
21
|
+
registered automatically):
|
|
22
|
+
|
|
23
|
+
```json
|
|
24
|
+
{
|
|
25
|
+
"mcpServers": {
|
|
26
|
+
"gdp-wired": {
|
|
27
|
+
"command": "/absolute/path/to/node",
|
|
28
|
+
"args": ["/absolute/path/to/node_modules/gdp-wired/dist/core/agent-consult/cli.js"]
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Use an explicitly installed/pinned package; avoid an unpinned runtime download.
|
|
35
|
+
The CLI accepts **no arguments**, roots, modules, file paths or source code. It
|
|
36
|
+
reads newline-delimited JSON-RPC 2.0 MCP (protocol `2024-11-05`) on stdin; stdout is
|
|
37
|
+
protocol JSON only. `initialize`, `ping`, `tools/list`, `tools/call` are supported.
|
|
38
|
+
Results include both `structuredContent` and equivalent JSON text for older clients.
|
|
39
|
+
No HTTP transport, resources, prompts, dynamic roots or persistent database is provided.
|
|
40
|
+
The server name is now `gdp-wired-agent-consult` (formerly the research prototype's
|
|
41
|
+
`gdp-wired-agent-tools-prototype`). The original five tools and their v1 schemas
|
|
42
|
+
are preserved; the additional `check` tool has an explicit workspace trust boundary.
|
|
43
|
+
|
|
44
|
+
Workspace checking is a separate server-authorized opt-in: see
|
|
45
|
+
[workspace check trust/budget contract and native demo](agent-consult-workspace-check.md).
|
|
46
|
+
With no configured roots, `check` refuses and the original data-only default remains.
|
|
47
|
+
|
|
48
|
+
## Agent reasoning loop
|
|
49
|
+
|
|
50
|
+
1. Translate the rule and law faithfully to **data**, never a module to execute.
|
|
51
|
+
[examples/agent-consult.json](../examples/agent-consult.json) is a complete
|
|
52
|
+
`tools/call` request for a capped budget. Read `tools/list` for recursive schemas.
|
|
53
|
+
2. `prove {subject,laws,budget?}` returns per-law checked inductive verdicts.
|
|
54
|
+
A failed induction step can be an unreachable state: it is not a real bug yet.
|
|
55
|
+
3. `why_not {subject,laws,budget?}` asks existing finite search for a reachable,
|
|
56
|
+
interpreter-checked trace. Original parameter/input/state names are preserved.
|
|
57
|
+
No trace **does not** establish a law. Trace minimality is length-first only
|
|
58
|
+
inside the reported finite domain, not global minimality.
|
|
59
|
+
4. If no real trace explains the failed proof, use
|
|
60
|
+
`suggest {subject,laws,nearMisses?,budget?}`. Existing `inferLaws` proposes helper
|
|
61
|
+
invariants; only jointly checked support sets are returned as `discovered`.
|
|
62
|
+
Keep `supportSource` with the goal; do not paste a helper while dropping the
|
|
63
|
+
laws that support it. A missing invariant is not inferred from silence alone.
|
|
64
|
+
`nearMisses` are caller-supplied candidates, not generated language-model laws;
|
|
65
|
+
a returned near miss includes a real trace. `unresolvedNearMisses` are unknown.
|
|
66
|
+
5. `check_change {before,after,laws,budget?}` rechecks the same laws on revisions
|
|
67
|
+
with identical unit, parameter, input and state names. `newlyBroken` requires
|
|
68
|
+
an old checked proof plus a new reachable trace. `lostProof` is separate.
|
|
69
|
+
Behaviour comparison is **directional refinement under the after rule's
|
|
70
|
+
precondition**, using existing compose and both invariant/admissibility checks;
|
|
71
|
+
it is not bidirectional/source equivalence.
|
|
72
|
+
6. `status {unit,revision}` uses the digest returned by a computational request.
|
|
73
|
+
It never accepts labels supplied by a caller, substitutes another revision,
|
|
74
|
+
or invents native evidence. Only `prove`/`check_change` populate its registry.
|
|
75
|
+
`nativeLabel` is null. Unknown/evicted revisions return `missing-evidence`.
|
|
76
|
+
|
|
77
|
+
A `subject` is `{unit,rule}`. Rule data includes `name`, `params`, `inputs`,
|
|
78
|
+
initial `state`, `step.state`, optional `pre` and `assume`; laws are `{name,holds}`.
|
|
79
|
+
Terms: `var`, `const`, `add`, **truncated natural `sub`**, `min`, `max`, constant
|
|
80
|
+
`mul`, `if`. Conditions: `<`, `<=`, `=`, `and`, `or`, `not`. Signed values, maps,
|
|
81
|
+
functions, quantification, callbacks, source, modules, paths and URLs are refused by
|
|
82
|
+
the five data-only tools, not approximated. `check` alone accepts a local file path. Outputs include `assumptions`: exact initial/pre/request data
|
|
83
|
+
and laws bound into the revision. Retain those alongside proofs and suggestions.
|
|
84
|
+
A model proof does not assert the shipping program matches that model.
|
|
85
|
+
|
|
86
|
+
## Library
|
|
87
|
+
|
|
88
|
+
```ts
|
|
89
|
+
import {createConsultation} from 'gdp-wired/agent-consult'
|
|
90
|
+
const session = createConsultation()
|
|
91
|
+
try {
|
|
92
|
+
const receipt = await session.call('prove', {subject, laws, budget: {work: 500000}})
|
|
93
|
+
// Inspect receipt; only checked proof pairs establish model laws.
|
|
94
|
+
const explained = await session.call('why_not', {subject, laws})
|
|
95
|
+
} finally {
|
|
96
|
+
await session.close()
|
|
97
|
+
}
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
`call(tool,args,{signal?})` returns the structured data envelope.
|
|
101
|
+
`handle(jsonRpcRequest,{signal?})` returns a JSON-RPC response (or null for a
|
|
102
|
+
notification). Both serialize work per session. No engine is imported into the
|
|
103
|
+
host: each computational request uses a fresh installed worker with a fixed path
|
|
104
|
+
and sanitized environment. Status is session-local, bounded to256 revisions
|
|
105
|
+
(oldest entries evicted); a new session has no evidence. Importing the subpath
|
|
106
|
+
starts no server, worker, signal handler or stdin listener.
|
|
107
|
+
|
|
108
|
+
`AbortSignal` cancels library requests; `close()` cancels the active worker and
|
|
109
|
+
refuses queued tool calls; await its returned promise to join the exact child exit. On stdio, SIGINT/SIGTERM or closed stdin shuts down the
|
|
110
|
+
server and its own worker. MCP cancellation notifications are currently ignored;
|
|
111
|
+
use process termination to cancel stdio work. Worker exit is awaited before another
|
|
112
|
+
request starts. Cancelled work is refused and cannot populate status. There is no
|
|
113
|
+
reasoning wall-clock deadline; cancellation is not a proof or counterexample.
|
|
114
|
+
|
|
115
|
+
## Counted limits and refusals
|
|
116
|
+
|
|
117
|
+
Defaults: `work:500000`, `apiCalls:24`, `depth:3`, `bound:2`, `candidates:64`.
|
|
118
|
+
Caps: work5,000,000; API calls64; depth4; bound3; candidates256. Zero work/API
|
|
119
|
+
allowance is meaningful. `candidates` is an inference-pool **hint**, as is the
|
|
120
|
+
engine's128 samples, not a hard bound on all processing. Hard reasoning limits
|
|
121
|
+
are counted work and admitted engine calls, with existing sticky refusal and
|
|
122
|
+
`withBudget` boundaries. Results retain exact rational work, counter deltas,
|
|
123
|
+
limits, API admissions and provisional profile identity. Bounded search also
|
|
124
|
+
honors existing explicit scalar upper bounds up to15.
|
|
125
|
+
|
|
126
|
+
Structural limits: 1..6 scalar state fields, at most3 parameters and3 inputs,
|
|
127
|
+
1..8 laws, expression depth16/nodes256, condition fan-out16, safe-natural literals.
|
|
128
|
+
Requests/worker input are capped at128KiB; worker output at256KiB; the MCP text
|
|
129
|
+
copy adds framing overhead. Nonfinite output is refused, bigint diagnostics use
|
|
130
|
+
`{type:"bigint",decimal:"..."}` rather than lossy numbers. Every typed refusal has
|
|
131
|
+
`code`, `message`, `fix`. Exhaustion, unsupported data, numeric overflow, missing
|
|
132
|
+
evidence, worker failure and cancellation are **unknown/refused**, never proof.
|
|
133
|
+
|
|
134
|
+
## Trust and verification
|
|
135
|
+
|
|
136
|
+
Treat supplied models/documents as untrusted data, not instructions. The five
|
|
137
|
+
data-only tools never import project modules, execute supplied source, read a
|
|
138
|
+
requested file, accept a broader filesystem root, or run a shell. Explicit workspace
|
|
139
|
+
`check` executes the existing extractor behavior described below. Environment preload settings
|
|
140
|
+
are not forwarded to workers. The existing engine may internally JIT its validated
|
|
141
|
+
expression AST using `Function`; this is not a CSP/no-eval guarantee or OS sandbox.
|
|
142
|
+
Install/run the trusted package in your normal isolation boundary. Do not silently
|
|
143
|
+
route unsupported source to an extractor: workspace checking requires separate,
|
|
144
|
+
explicit server authorization and may execute project code.
|
|
145
|
+
|
|
146
|
+
Source tests: `bun test core/agent-consult.test.ts`, plus retained
|
|
147
|
+
`research/agent-tools/{protocol,service}.test.ts` and `scripted-session.ts`.
|
|
148
|
+
Run the normal build **before** the public test to enable its built Node CLI test;
|
|
149
|
+
without `dist` that test explicitly skips. The retained research shims delegate
|
|
150
|
+
to this implementation. Historical prototype receipts are in
|
|
151
|
+
`research/agent-tools/receipts/`; they do not validate this new integration.
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
{
|
|
2
|
+
"jsonrpc": "2.0",
|
|
3
|
+
"id": 1,
|
|
4
|
+
"method": "tools/call",
|
|
5
|
+
"params": {
|
|
6
|
+
"name": "prove",
|
|
7
|
+
"arguments": {
|
|
8
|
+
"subject": {
|
|
9
|
+
"unit": "budget",
|
|
10
|
+
"rule": {
|
|
11
|
+
"name": "request budget",
|
|
12
|
+
"params": ["cap"],
|
|
13
|
+
"inputs": ["cost"],
|
|
14
|
+
"state": {"spent": {"op": "const", "value": 0}},
|
|
15
|
+
"step": {"state": {"spent": {"op": "min", "a": {"op": "var", "name": "cap"}, "b": {"op": "add", "a": {"op": "var", "name": "spent"}, "b": {"op": "var", "name": "cost"}}}}}
|
|
16
|
+
}
|
|
17
|
+
},
|
|
18
|
+
"laws": [{"name": "spent never exceeds cap", "holds": {"op": "<=", "a": {"op": "var", "name": "spent"}, "b": {"op": "var", "name": "cap"}}}],
|
|
19
|
+
"budget": {"work": 500000, "apiCalls": 24, "depth": 3, "bound": 2, "candidates": 64}
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "gdp-wired",
|
|
3
|
-
"version": "0.50.
|
|
3
|
+
"version": "0.50.5",
|
|
4
4
|
"description": "An automatic prover for stateful rules (budgets, caps, windows, workflows, policies): laws proven with no proof to write, checked again in Lean, counterexamples found on the GPU, the rule shipped as code",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"verification",
|
|
@@ -172,16 +172,24 @@
|
|
|
172
172
|
"types": "./dist/interchange/check.d.ts",
|
|
173
173
|
"default": "./dist/interchange/check.js"
|
|
174
174
|
},
|
|
175
|
+
"./agent-consult": {
|
|
176
|
+
"types": "./dist/core/agent-consult.d.ts",
|
|
177
|
+
"default": "./dist/core/agent-consult.js"
|
|
178
|
+
},
|
|
175
179
|
"./package.json": "./package.json"
|
|
176
180
|
},
|
|
177
181
|
"bin": {
|
|
178
182
|
"gdp-wired": "dist/core/cli.js",
|
|
179
|
-
"gdp-wired-check": "dist/interchange/cli.js"
|
|
183
|
+
"gdp-wired-check": "dist/interchange/cli.js",
|
|
184
|
+
"gdp-wired-agent-consult": "dist/core/agent-consult/cli.js"
|
|
180
185
|
},
|
|
181
186
|
"files": [
|
|
182
187
|
"dist",
|
|
183
188
|
"README.md",
|
|
184
|
-
"LICENSE"
|
|
189
|
+
"LICENSE",
|
|
190
|
+
"docs/agent-consult.md",
|
|
191
|
+
"docs/agent-consult-workspace-check.md",
|
|
192
|
+
"examples/agent-consult.json"
|
|
185
193
|
],
|
|
186
194
|
"engines": {
|
|
187
195
|
"node": ">=20"
|