Skip to content

Commit 2c964db

Browse files
luisleo526claude
andcommitted
Repair the source-host writer surface, restore generic trail/fold context, drop the dead Pine declarations and add real native witnesses (R4-C L5)
Repair A33/A34 Pine risk writer semantics and cover direction plus sticky percent state. Restore A37 generic trail/fold ownership and hash folds, update the v15→v16 relocation manifest, and remove F8/F10/S28. Apply A35 waiver coverage enforcement, A36 source-only declaration cleanup and guard, and A38/A39 native and metadata witnesses/surface repairs. Contract rules: A33, A34, A35, A36, A37, A38, A39, A40. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_016iF71UAEuQ7F6eqWgecAHm
1 parent 6e9b908 commit 2c964db

24 files changed

Lines changed: 782 additions & 655 deletions

‎include/pineforge/engine.hpp‎

Lines changed: 136 additions & 418 deletions
Large diffs are not rendered by default.

‎include/pineforge/source/pine_strategy_host.hpp‎

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,22 @@
88
#include <pineforge/source/pine_policy_support.hpp>
99
#include <pineforge/compat/pine/intraday_cap.hpp>
1010

11+
// Generated constructors can explicitly select Pine cap compatibility before
12+
// any host metadata setter. These capability macros belong to the source host
13+
// surface; the generic engine header remains source-free.
14+
#define PINEFORGE_HAS_EXPLICIT_PINE_CAP_V1 1
15+
#define PINEFORGE_HAS_EXPLICIT_PINE_EXECUTION_ADAPTER_V1 1
16+
17+
namespace pineforge {
18+
19+
void fill_pending_order_mirror(const source::PendingOrder& src,
20+
const MarketAdmissionJournal* journal,
21+
pf_pending_order_v1_t* out);
22+
void fill_pending_order_mirror(const source::PendingOrder& src,
23+
pf_pending_order_v1_t* out);
24+
25+
} // namespace pineforge
26+
1127
namespace pineforge::source {
1228

1329
// Intermediate source-layer host. The remaining source ownership surface is
@@ -67,13 +83,12 @@ class PineStrategyHost : public BacktestEngine, protected PineLanguageState {
6783
int pine_last_bar_index() const;
6884
double prev_chart_close() const;
6985
int last_bar_dual_entry_path() const;
70-
double trail_best_price() const;
7186
double live_position_size() const override;
7287
int pending_order_count() const;
7388
MarketAdmissionJournal& market_admission_journal();
7489
const MarketAdmissionJournal& market_admission_journal() const;
7590
std::vector<admission::Field> market_admission_fields() const;
76-
const PendingOrder& pending_order_at(int index) const;
91+
const PendingOrder& pending_order_at(int i) const;
7792
int probe_fill_qty(int index, double fill_price, double* qty,
7893
int* close_only, int* partition) const;
7994
int pending_order_level_resolved(int index) const;
@@ -193,8 +208,6 @@ class PineStrategyHost : public BacktestEngine, protected PineLanguageState {
193208
std::vector<uint64_t> scratch_filled_incarnations_;
194209
internal::DualEntryStopPathWinner dual_entry_path_{};
195210
internal::DualEntryStopPathWinner last_bar_dual_entry_decision_{};
196-
double trail_best_price_ = std::numeric_limits<double>::quiet_NaN();
197-
int trail_close_restart_bar_ = -1;
198211
double trail_best_before_bar_ = std::numeric_limits<double>::quiet_NaN();
199212
int trail_best_before_bar_index_ = -1;
200213
int64_t trail_best_before_bar_position_cycle_ = 0;
@@ -269,11 +282,8 @@ class PineStrategyHost : public BacktestEngine, protected PineLanguageState {
269282
void apply_source_pending_removals(
270283
const std::vector<execution::PendingRemoval>& removals);
271284
void reset_source_exit_activations_before_flatten();
272-
void reset_source_trail_after_flatten();
273285
void reset_source_position_ledgers_after_book_clear();
274-
void on_source_append_quoted_lot_before_book(const PyramidEntry& lot);
275286
void on_source_append_quoted_lot_after_book(const PyramidEntry& lot);
276-
void reset_source_open_position_trail_before_book_clear(const PyramidEntry& lot);
277287
void reset_source_open_position_ledgers_before_book(const PyramidEntry& lot);
278288
void on_source_open_position_booked(const PyramidEntry& lot);
279289
enum class ExitLegTransitionResult {

‎scripts/broker_state_hash_waivers.txt‎

Lines changed: 0 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -10,31 +10,17 @@
1010
# the same configured engine agree on these by construction.
1111
calc_on_order_fills_ # config: strategy(calc_on_order_fills=...)
1212
chart_ema_na_warmup_ # config: opt-in chart-TF ta.ema warmup selector
13-
close_entries_rule_any_ # config: strategy(close_entries_rule=...)
1413
commission_type_ # config: strategy(commission_type=...)
1514
commission_value_ # config: strategy(commission_value=...)
16-
default_qty_type_ # config: strategy(default_qty_type=...)
17-
default_qty_value_ # config: strategy(default_qty_value=...)
1815
historical_security_lookahead_projection_ # config: opt-in request.security selector
1916
initial_capital_ # config: strategy(initial_capital=...)
2017
margin_call_enabled_ # config: set_margin_call_enabled toggle
21-
margin_long_ # config: strategy(margin_long=...)
22-
margin_short_ # config: strategy(margin_short=...)
23-
margin_zero_cover_full_liquidation_ # config: opt-in margin-call oracle candidate
2418
path_order_mode_ # config: set_path_order(), persistent op-set selector
2519
probe_suppress_tail_logic_ # config: set_probe_suppress_tail_logic(), persistent selector
2620
process_orders_on_close_ # config: strategy(process_orders_on_close=...)
27-
pyramiding_ # config: strategy(pyramiding=...)
2821
qty_step_ # config: injected per-instrument lot step
2922
realtime_tail_ # config: set_realtime_tail(), persistent live-runtime selector
3023
realtime_tail_horizon_bars_ # config: companion horizon for realtime_tail_
31-
risk_direction_ # config: strategy.risk.allow_entry_in(...)
32-
risk_max_cons_loss_days_ # config: strategy.risk.max_cons_loss_days(...)
33-
risk_max_drawdown_ # config: strategy.risk.max_drawdown(...)
34-
risk_max_drawdown_is_pct_ # config: companion unit selector for risk_max_drawdown_
35-
risk_max_intraday_loss_ # config: strategy.risk.max_intraday_loss(...)
36-
risk_max_intraday_loss_is_pct_ # config: companion unit selector for risk_max_intraday_loss_
37-
risk_max_position_size_ # config: strategy.risk.max_position_size(...)
3824
security_range_start_na_warmup_ # config: opt-in HTF warmup selector
3925
security_range_start_ms_ # config: injected HTF warmup range-start epoch
4026
slippage_ # config: strategy(slippage=...)
@@ -44,7 +30,6 @@ trade_start_time_ # config: strategy_set_trade_start_time
4430
account_currency_fx_ # config: injected scalar FX fallback (the broker CLOCK that consumes it is hashed)
4531
account_currency_fx_rates_ # config: injected timestamped FX provider series
4632
account_currency_fx_timestamps_ # config: injected timestamped FX provider series
47-
bar_index_offset_ # config: script-visible Pine bar_index cosmetic offset
4833

4934
# --- syminfo/chart/input injection: config surface for the script, not
5035
# broker decision state.
@@ -55,18 +40,6 @@ inputs_ # config: injected input.* values
5540
# --- Feed/input.source backing series and chart-close tracking: script or
5641
# indicator computation context (ta.*, request.security bucketing), never
5742
# read by broker/fill logic.
58-
_src_series_active_ # input.source backing-series activation flag
59-
_src_open_ # input.source backing series
60-
_src_high_ # input.source backing series
61-
_src_low_ # input.source backing series
62-
_src_close_ # input.source backing series
63-
_src_volume_ # input.source backing series
64-
_src_hl2_ # input.source backing series
65-
_src_hlc3_ # input.source backing series
66-
_src_ohlc4_ # input.source backing series
67-
_src_hlcc4_ # input.source backing series
68-
prev_chart_close_ # ta.atr/ta.tr chart-close tracking, script-visible only
69-
last_chart_close_ # companion to prev_chart_close_
7043
security_first_chart_bar_ms_ # run-start constant (first chart bar epoch), fixed once a run begins
7144
security_next_input_ms_ # feed/dispatch context: next input bar's timestamp, recomputed every bar from feed position
7245
security_calling_close_ms_ # feed/dispatch context: calling chart bar's nominal close
@@ -85,14 +58,6 @@ last_bar_time_ # feed metadata: last bar's timestamp (script-visi
8558
# directly, and each is always resolved (cleared) within the same call that
8659
# set it, before any other code -- let alone a later bar's dispatch -- reads
8760
# it again.
88-
current_fill_is_limit_ # doc: "Transient: true only while dispatching a LIMIT-triggered fill"
89-
fold_exit_path_extremes_ # doc: "Transient: true only while applying a priced ... fill"
90-
fold_exit_trail_peak_ # doc: "Transient companion for TRAIL exits"; NaN outside a trail fill
91-
last_exit_fill_was_trail_ # set by evaluate_fill_price, consumed same call chain by apply_filled_order_to_state
92-
intraday_loss_evaluating_ # transient evaluation flag: reentrancy guard, true only inside evaluate_max_intraday_loss, always false on return
93-
scratch_skip_ids_ # doc: "Not state -- must be empty across calls"
94-
scratch_filled_incarnations_ # doc: "Always cleared before use"
95-
named_entry_cancelled_incarnation_in_current_eval_ # doc: "invoke_chart_on_bar clears the map before each script execution"
9661

9762
# --- Per-source-bar same-bar strategy.close batching scratch: the code's
9863
# own comment on the sibling cross-bar maps ("Per-source-bar only") applies
@@ -102,19 +67,6 @@ named_entry_cancelled_incarnation_in_current_eval_ # doc: "invoke_chart_on_bar
10267
# reservation/provenance ledgers these feed (close_reserved_qty_,
10368
# close_two_call_first_qty_, callsite_close_reserved_qty_,
10469
# callsite_close_two_call_first_qty_) ARE hashed.
105-
sb_close_active_ # per-source-bar batching scratch
106-
sb_close_bar_ # per-source-bar batching scratch
107-
sb_close_calls_ # per-source-bar batching scratch
108-
sb_close_first_id_ # per-source-bar batching scratch
109-
sb_close_first_target_ # per-source-bar batching scratch
110-
sb_close_first_carry_valid_ # per-source-bar batching scratch
111-
sb_close_first_carry_qty_ # per-source-bar batching scratch
112-
sb_close_id_ # per-source-bar batching scratch
113-
sb_close_comment_ # per-source-bar batching scratch
114-
callsite_close_bar_ # per-source-bar scratch, same "== bar_index_" dead-once-advanced pattern
115-
callsite_close_callsites_ # doc: "Per-source-bar only"
116-
callsite_close_queue_seq_ # monotonic counter only compared within the same source bar's discarded batch
117-
callsite_close_admitted_total_ # doc: "claimed by the currently surviving nonzero-site instructions on this source bar"
11870

11971
# --- Report/diagnostic accumulators that are NOT reachable through any
12072
# strategy.* script accessor -- pure internal report plumbing (verified by
@@ -134,7 +86,6 @@ broker_state_hashes_ # report-only recording of the hash itself; hashin
13486

13587
# --- Per-pass dual-entry-stop working state (task brief instruction: waive
13688
# this one, hash the per-bar snapshot instead).
137-
dual_entry_path_ # per-PASS arbitration working state; last_bar_dual_entry_decision_ (hashed) is the per-bar snapshot that survives it
13889

13990
# --- struct PendingOrder (task 7): every scalar/string member must be hashed
14091
# as o.<name> inside broker_state_hash()'s pending_orders_ loop or waived

‎scripts/check_broker_state_hash_coverage.py‎

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -634,6 +634,28 @@ def main(root: Path = ROOT) -> int:
634634
f"in any // @broker-state region: {orphans}", file=sys.stderr)
635635
return 1
636636

637+
# A waiver is only valid while the named field is genuinely absent from
638+
# both hash owners. In particular, source-layer fields that were moved
639+
# out of engine.hpp must not retain their old v15 waiver: the source
640+
# extension is the authoritative fold for those fields.
641+
source_hashed_waivers = sorted(
642+
name for name in waivers
643+
if re.search(rf"\b{re.escape(name)}\b", source_hash)
644+
)
645+
if source_hashed_waivers:
646+
print("check_broker_state_hash_coverage: waiver(s) naming a field "
647+
"hashed by the source extension: "
648+
f"{source_hashed_waivers}", file=sys.stderr)
649+
return 1
650+
already_hashed_waivers = sorted(
651+
name for name in waivers
652+
if re.search(rf"\b{re.escape(name)}\b", all_hash)
653+
)
654+
if already_hashed_waivers:
655+
print("check_broker_state_hash_coverage: waiver(s) naming an already "
656+
f"hashed field: {already_hashed_waivers}", file=sys.stderr)
657+
return 1
658+
637659
missing = sorted(
638660
m for m in members
639661
if not re.search(rf"\b{re.escape(m)}\b", all_hash) and m not in waivers
@@ -656,10 +678,14 @@ def main(root: Path = ROOT) -> int:
656678
m for m in po_members
657679
if not re.search(rf"\bo\.{re.escape(m)}\b", loop) and m not in po_waivers
658680
)
659-
if po_missing:
681+
po_redundant = sorted(
682+
m for m in po_waivers
683+
if re.search(rf"\bo\.{re.escape(m)}\b", loop)
684+
)
685+
if po_missing or po_redundant:
660686
print("check_broker_state_hash_coverage: PendingOrder members neither hashed "
661-
"(o.<name> in the pending_orders_ loop) nor waived (pending_order.<name>):",
662-
po_missing)
687+
"(o.<name> in the pending_orders_ loop) nor waived (pending_order.<name>): "
688+
f"missing={po_missing}, redundant_waivers={po_redundant}")
663689
return 1
664690
# --- struct PyramidEntry: inspect every physical-lot field recursively ---
665691
pe_members = struct_members(hpp, "PyramidEntry")

‎scripts/test_broker_state_hash_coverage.py‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,33 @@ def test_source_marker_members_need_folds(self):
6565
"f.b(missing_risk_halted_);"),))
6666
self.assertEqual(result, 1, output)
6767

68+
def test_waiver_cannot_name_source_hashed_field(self):
69+
result, output = self.check((
70+
("scripts/broker_state_hash_waivers.txt",
71+
"calc_on_order_fills_ # config: strategy(calc_on_order_fills=...)",
72+
"calc_on_order_fills_ # config: strategy(calc_on_order_fills=...)\n"
73+
"risk_direction_ # test source fold must not be waived"),))
74+
self.assertEqual(result, 1, output)
75+
self.assertIn("hashed by the source extension", output)
76+
77+
def test_waiver_cannot_name_generic_hashed_field(self):
78+
result, output = self.check((
79+
("scripts/broker_state_hash_waivers.txt",
80+
"calc_on_order_fills_ # config: strategy(calc_on_order_fills=...)",
81+
"calc_on_order_fills_ # config: strategy(calc_on_order_fills=...)\n"
82+
"fold_exit_path_extremes_ # test generic fold must not be waived"),))
83+
self.assertEqual(result, 1, output)
84+
self.assertIn("already hashed field", output)
85+
86+
def test_pending_order_waiver_cannot_duplicate_fold(self):
87+
result, output = self.check((
88+
("scripts/broker_state_hash_waivers.txt",
89+
"pending_order.comment # trade-report label only: copied into the Trade row's entry/exit comment at fill and never read by any fill, admission, sizing or eligibility path -- it cannot change a future fill",
90+
"pending_order.comment # trade-report label only: copied into the Trade row's entry/exit comment at fill and never read by any fill, admission, sizing or eligibility path -- it cannot change a future fill\n"
91+
"pending_order.id # test duplicate pending fold"),))
92+
self.assertEqual(result, 1, output)
93+
self.assertIn("redundant_waivers", output)
94+
6895
def test_pending_parser_uses_source_intent(self):
6996
pending = ROOT / "include/pineforge/source/pine_pending_intent.hpp"
7097
self.assertGreater(len(members(pending.read_text())), 0)

0 commit comments

Comments
 (0)