fable-engine 1.3.1__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.
Files changed (104) hide show
  1. fable_compressor.py +356 -0
  2. fable_engine/__init__.py +1 -0
  3. fable_engine/actions/__init__.py +291 -0
  4. fable_engine/actions/cas.py +182 -0
  5. fable_engine/actions/deliberation.py +523 -0
  6. fable_engine/actions/fleet.py +807 -0
  7. fable_engine/actions/lifecycle.py +298 -0
  8. fable_engine/actions/scrapers.py +116 -0
  9. fable_engine/actions/system3.py +815 -0
  10. fable_engine/browser.py +824 -0
  11. fable_engine/cas.py +974 -0
  12. fable_engine/fable_session.json +510 -0
  13. fable_engine/guards.py +283 -0
  14. fable_engine/schema.py +714 -0
  15. fable_engine/scrapers/__init__.py +32 -0
  16. fable_engine/scrapers/arxiv.py +115 -0
  17. fable_engine/scrapers/base.py +386 -0
  18. fable_engine/scrapers/github.py +129 -0
  19. fable_engine/scrapers/reddit.py +154 -0
  20. fable_engine/scrapers/web.py +120 -0
  21. fable_engine/scrapers/x.py +125 -0
  22. fable_engine/scrapers/youtube.py +132 -0
  23. fable_engine/server.py +414 -0
  24. fable_engine/session.py +1819 -0
  25. fable_engine/test_server.py +1362 -0
  26. fable_engine/updater.py +541 -0
  27. fable_engine-1.3.1.dist-info/LICENSE +22 -0
  28. fable_engine-1.3.1.dist-info/METADATA +173 -0
  29. fable_engine-1.3.1.dist-info/RECORD +104 -0
  30. fable_engine-1.3.1.dist-info/WHEEL +5 -0
  31. fable_engine-1.3.1.dist-info/entry_points.txt +5 -0
  32. fable_engine-1.3.1.dist-info/top_level.txt +6 -0
  33. fable_mode/__init__.py +3 -0
  34. fable_mode/__main__.py +4 -0
  35. fable_mode/adapters.py +1014 -0
  36. fable_mode/installer.py +553 -0
  37. fable_mode/launcher.py +437 -0
  38. fable_mode/manifest.py +142 -0
  39. fable_mode/resources.json +114 -0
  40. fable_mode/safety.py +103 -0
  41. fable_mode_entry.py +10 -0
  42. fable_v2/__init__.py +146 -0
  43. fable_v2/adapters.py +151 -0
  44. fable_v2/coder_fleet/__init__.py +100 -0
  45. fable_v2/coder_fleet/ast_tools.py +158 -0
  46. fable_v2/coder_fleet/compute.py +199 -0
  47. fable_v2/coder_fleet/design_engine.py +1316 -0
  48. fable_v2/coder_fleet/diagnostics.py +293 -0
  49. fable_v2/coder_fleet/fleet_dispatcher.py +214 -0
  50. fable_v2/coder_fleet/mock_auditor.py +306 -0
  51. fable_v2/coder_fleet/mutation.py +216 -0
  52. fable_v2/coder_fleet/property_oracle.py +260 -0
  53. fable_v2/coder_fleet/receipt_attestor.py +122 -0
  54. fable_v2/coder_fleet/red_team_swarm.py +908 -0
  55. fable_v2/coder_fleet/test_harness.py +198 -0
  56. fable_v2/coder_fleet/vector_engine.py +1287 -0
  57. fable_v2/coder_fleet/visual.py +357 -0
  58. fable_v2/coder_fleet/workspace.py +153 -0
  59. fable_v2/cortical/__init__.py +20 -0
  60. fable_v2/cortical/plasticity_engine.py +992 -0
  61. fable_v2/execution_broker.py +811 -0
  62. fable_v2/proof_engine.py +1141 -0
  63. fable_v2/protocol.py +485 -0
  64. fable_v2/runtime.py +1010 -0
  65. fable_v2/system3/__init__.py +204 -0
  66. fable_v2/system3/causal.py +558 -0
  67. fable_v2/system3/dialectical.py +577 -0
  68. fable_v2/system3/evolution.py +503 -0
  69. fable_v2/system3/executive.py +338 -0
  70. fable_v2/system3/free_energy.py +479 -0
  71. fable_v2/system3/hyperbolic.py +555 -0
  72. fable_v2/system3/induction.py +336 -0
  73. fable_v2/system3/kripke.py +548 -0
  74. fable_v2/system3/oracle.py +745 -0
  75. fable_v2/verifiers.py +72 -0
  76. tests/__init__.py +1 -0
  77. tests/test_anti_loop_circuit_breaker.py +64 -0
  78. tests/test_auto_updater.py +407 -0
  79. tests/test_coder_fleet.py +535 -0
  80. tests/test_delegation_compiler.py +54 -0
  81. tests/test_descriptor_boundaries.py +126 -0
  82. tests/test_design_engine.py +603 -0
  83. tests/test_epistemic_evidence_validator.py +66 -0
  84. tests/test_execution_broker.py +233 -0
  85. tests/test_fable_v2.py +406 -0
  86. tests/test_fleet_transitions.py +116 -0
  87. tests/test_fsm_redteam_evolution.py +406 -0
  88. tests/test_goal_rubric_and_pipeline.py +367 -0
  89. tests/test_hebbian_plasticity.py +585 -0
  90. tests/test_packaging_runtime.py +194 -0
  91. tests/test_proof_engine.py +259 -0
  92. tests/test_red_team_swarm.py +645 -0
  93. tests/test_redteam_remediation.py +169 -0
  94. tests/test_registration_transaction.py +375 -0
  95. tests/test_requested_regressions.py +467 -0
  96. tests/test_scrapers.py +370 -0
  97. tests/test_server_actions.py +93 -0
  98. tests/test_server_frontier_actions.py +269 -0
  99. tests/test_server_protocol.py +88 -0
  100. tests/test_stealth_browser.py +970 -0
  101. tests/test_system3.py +381 -0
  102. tests/test_system3_deep_integration.py +385 -0
  103. tests/test_system3_frontier.py +436 -0
  104. tests/test_vector_engine.py +608 -0
@@ -0,0 +1,541 @@
1
+ """Autonomous Silent Self-Updater for Fable-Mode across client machines.
2
+
3
+ Enables silent upstream synchronization, non-destructive cortical experience
4
+ preservation (antibodies, synaptic weights, custom lobes), and hot-syncing
5
+ into active host skill and rule directories.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import logging
11
+ import os
12
+ from pathlib import Path
13
+ import shutil
14
+ import subprocess
15
+ import threading
16
+ from typing import Any, Optional
17
+
18
+ logger = logging.getLogger("fable-engine.updater")
19
+
20
+ BASELINE_LOBES: frozenset[str] = frozenset(
21
+ {"rust", "python", "design_3d", "research", "concurrency"}
22
+ )
23
+
24
+ _BG_LOCK = threading.Lock()
25
+ _BG_RUNNING = False
26
+
27
+
28
+ class AutoUpdater:
29
+ """Autonomous Silent Self-Updater and Hot-Sync Manager for Fable-Mode."""
30
+
31
+ def __init__(
32
+ self,
33
+ repo_root: Optional[Path] = None,
34
+ remote_url: str = "https://github.com/REX-codebase/fable-mode.git",
35
+ skills_dir: Optional[Path] = None,
36
+ ) -> None:
37
+ if repo_root is not None:
38
+ self.repo_root = Path(repo_root).resolve()
39
+ else:
40
+ # Default to repo root (parent directory of fable_engine)
41
+ self.repo_root = Path(__file__).resolve().parent.parent
42
+
43
+ self.remote_url = remote_url
44
+ self.skills_dir = Path(skills_dir).resolve() if skills_dir else None
45
+ self.host_targets = self.discover_host_targets()
46
+
47
+ def discover_host_targets(self) -> list[Path]:
48
+ """Detect active host skill paths across client environments."""
49
+ candidates: list[Path] = []
50
+ home = Path.home()
51
+
52
+ # 1. Explicit skills_dir if provided
53
+ if self.skills_dir:
54
+ candidates.append(self.skills_dir)
55
+
56
+ # 2. Environment override
57
+ env_skills = os.environ.get("FABLE_SKILLS_DIR")
58
+ if env_skills:
59
+ candidates.append(Path(env_skills).resolve())
60
+
61
+ # 3. Gemini / Antigravity skill directory
62
+ candidates.append(home / ".gemini" / "config" / "skills" / "fable-mode")
63
+
64
+ # 4. Claude Code / desktop skill directory
65
+ candidates.append(home / ".claude" / "skills" / "fable-mode")
66
+
67
+ # 5. Cursor skills directory (workspace and user home)
68
+ candidates.append(self.repo_root / ".cursor" / "skills" / "fable-mode")
69
+ candidates.append(home / ".cursor" / "skills" / "fable-mode")
70
+
71
+ # 6. Windsurf / Codeium skill directory
72
+ candidates.append(home / ".codeium" / "windsurf" / "skills" / "fable-mode")
73
+
74
+ # Return all candidate paths that either already exist or whose parent exists
75
+ discovered: list[Path] = []
76
+ for path in candidates:
77
+ try:
78
+ resolved = path.resolve()
79
+ if resolved not in discovered:
80
+ discovered.append(resolved)
81
+ except Exception:
82
+ pass
83
+
84
+ return discovered
85
+
86
+ def check_for_updates(self, timeout_seconds: float = 3.0) -> dict[str, Any]:
87
+ """Run a quick, safe check against remote upstream for new commits.
88
+
89
+ Fail-safe: if offline, timeout, or non-git, returns an informative dict
90
+ with zero unhandled exceptions.
91
+ """
92
+ git_dir = self.repo_root / ".git"
93
+ if not git_dir.exists():
94
+ return {
95
+ "update_available": False,
96
+ "local_commit": "",
97
+ "remote_commit": "",
98
+ "offline": True,
99
+ "message": f"Directory '{self.repo_root}' is not a git repository.",
100
+ }
101
+
102
+ local_commit = ""
103
+ try:
104
+ # 1. Query local HEAD commit
105
+ res_local = subprocess.run(
106
+ ["git", "rev-parse", "HEAD"],
107
+ cwd=str(self.repo_root),
108
+ capture_output=True,
109
+ text=True,
110
+ timeout=timeout_seconds,
111
+ )
112
+ if res_local.returncode != 0:
113
+ return {
114
+ "update_available": False,
115
+ "local_commit": "",
116
+ "remote_commit": "",
117
+ "offline": True,
118
+ "message": f"git rev-parse HEAD failed: {res_local.stderr.strip()}",
119
+ }
120
+ local_commit = res_local.stdout.strip()
121
+
122
+ # 2. Query remote main branch commit
123
+ remote_commit = ""
124
+ # Try origin first, fallback to remote_url
125
+ for target in ("origin", self.remote_url):
126
+ try:
127
+ res_remote = subprocess.run(
128
+ ["git", "ls-remote", target, "refs/heads/main"],
129
+ cwd=str(self.repo_root),
130
+ capture_output=True,
131
+ text=True,
132
+ timeout=timeout_seconds,
133
+ )
134
+ if res_remote.returncode == 0 and res_remote.stdout.strip():
135
+ parts = res_remote.stdout.strip().split()
136
+ if parts:
137
+ remote_commit = parts[0].strip()
138
+ break
139
+ except subprocess.TimeoutExpired:
140
+ raise
141
+ except Exception:
142
+ continue
143
+
144
+ if not remote_commit:
145
+ return {
146
+ "update_available": False,
147
+ "local_commit": local_commit,
148
+ "remote_commit": "",
149
+ "offline": True,
150
+ "message": "Unable to query upstream remote (offline or unreachable).",
151
+ }
152
+
153
+ update_available = (local_commit != remote_commit)
154
+ msg = (
155
+ f"Update available: {local_commit[:8]} -> {remote_commit[:8]}"
156
+ if update_available
157
+ else "Fable-Mode is up to date."
158
+ )
159
+ return {
160
+ "update_available": update_available,
161
+ "local_commit": local_commit,
162
+ "remote_commit": remote_commit,
163
+ "offline": False,
164
+ "message": msg,
165
+ }
166
+
167
+ except subprocess.TimeoutExpired:
168
+ return {
169
+ "update_available": False,
170
+ "local_commit": local_commit,
171
+ "remote_commit": "",
172
+ "offline": True,
173
+ "message": f"Upstream check timed out after {timeout_seconds}s.",
174
+ }
175
+ except Exception as exc:
176
+ return {
177
+ "update_available": False,
178
+ "local_commit": local_commit,
179
+ "remote_commit": "",
180
+ "offline": True,
181
+ "message": f"Check failed safely: {exc}",
182
+ }
183
+
184
+ def _snapshot_cortex(self) -> dict[str, Any]:
185
+ """Snapshot all local cortical lobes and synaptic weights before pull."""
186
+ cortex_dir = self.repo_root / "skills" / "fable-mode" / "cortex"
187
+ snapshot: dict[str, Any] = {
188
+ "lobes": {},
189
+ "raw_text": {},
190
+ "synaptic_matrix": None,
191
+ }
192
+ if not cortex_dir.exists():
193
+ return snapshot
194
+
195
+ # Try to import CorticalLobe
196
+ CorticalLobe = None
197
+ try:
198
+ from fable_v2.cortical.plasticity_engine import CorticalLobe as CL
199
+ CorticalLobe = CL
200
+ except Exception:
201
+ pass
202
+
203
+ for md_file in cortex_dir.glob("*.md"):
204
+ name = md_file.stem
205
+ try:
206
+ raw = md_file.read_text(encoding="utf-8")
207
+ snapshot["raw_text"][name] = raw
208
+ if CorticalLobe:
209
+ lobe_obj = CorticalLobe.load_from_disk(md_file)
210
+ snapshot["lobes"][name] = lobe_obj
211
+ except Exception as e:
212
+ logger.debug(f"Failed snapshotting lobe {name}: {e}")
213
+
214
+ matrix_file = cortex_dir / "synaptic_matrix.json"
215
+ if matrix_file.exists():
216
+ try:
217
+ snapshot["synaptic_matrix"] = json.loads(matrix_file.read_text(encoding="utf-8"))
218
+ except Exception:
219
+ pass
220
+
221
+ return snapshot
222
+
223
+ def _merge_and_restore_cortex(self, snapshot: dict[str, Any]) -> list[str]:
224
+ """Non-destructively merge preserved antibodies, synaptic weights, and custom lobes."""
225
+ cortex_dir = self.repo_root / "skills" / "fable-mode" / "cortex"
226
+ cortex_dir.mkdir(parents=True, exist_ok=True)
227
+ preserved_names: list[str] = []
228
+
229
+ CorticalLobe = None
230
+ try:
231
+ from fable_v2.cortical.plasticity_engine import CorticalLobe as CL
232
+ CorticalLobe = CL
233
+ except Exception:
234
+ pass
235
+
236
+ local_raw = snapshot.get("raw_text", {})
237
+ local_lobes = snapshot.get("lobes", {})
238
+
239
+ # 1. Restore Custom Lobes (non-baseline)
240
+ for name, raw in local_raw.items():
241
+ if name not in BASELINE_LOBES:
242
+ lobe_file = cortex_dir / f"{name}.md"
243
+ if not lobe_file.exists():
244
+ lobe_file.write_text(raw, encoding="utf-8")
245
+ preserved_names.append(name)
246
+ elif CorticalLobe and name in local_lobes:
247
+ # Lobe file exists after pull; merge antibodies and weights
248
+ try:
249
+ pulled = CorticalLobe.load_from_disk(lobe_file)
250
+ local = local_lobes[name]
251
+ self._merge_lobe_data(pulled, local)
252
+ pulled.save_to_disk(lobe_file)
253
+ preserved_names.append(name)
254
+ except Exception as e:
255
+ logger.debug(f"Error merging custom lobe {name}: {e}")
256
+
257
+ # 2. Merge Baseline Lobes (non-destructive antibody and weight union)
258
+ for base_name in BASELINE_LOBES:
259
+ if base_name in local_lobes and CorticalLobe:
260
+ lobe_file = cortex_dir / f"{base_name}.md"
261
+ if lobe_file.exists():
262
+ try:
263
+ pulled = CorticalLobe.load_from_disk(lobe_file)
264
+ local = local_lobes[base_name]
265
+ self._merge_lobe_data(pulled, local)
266
+ pulled.save_to_disk(lobe_file)
267
+ preserved_names.append(base_name)
268
+ except Exception as e:
269
+ logger.debug(f"Error merging baseline lobe {base_name}: {e}")
270
+
271
+ # 3. Merge Synaptic Matrix
272
+ local_matrix = snapshot.get("synaptic_matrix")
273
+ if local_matrix and isinstance(local_matrix, dict):
274
+ matrix_file = cortex_dir / "synaptic_matrix.json"
275
+ pulled_matrix: dict[str, Any] = {}
276
+ if matrix_file.exists():
277
+ try:
278
+ pulled_matrix = json.loads(matrix_file.read_text(encoding="utf-8"))
279
+ except Exception:
280
+ pulled_matrix = {}
281
+ # Non-destructively union local matrix weights with pulled matrix
282
+ for src, targets in local_matrix.items():
283
+ if src not in pulled_matrix:
284
+ pulled_matrix[src] = targets
285
+ elif isinstance(targets, dict) and isinstance(pulled_matrix.get(src), dict):
286
+ for tgt, weight in targets.items():
287
+ if tgt not in pulled_matrix[src]:
288
+ pulled_matrix[src][tgt] = weight
289
+ else:
290
+ try:
291
+ pulled_matrix[src][tgt] = max(
292
+ float(weight), float(pulled_matrix[src][tgt])
293
+ )
294
+ except (ValueError, TypeError):
295
+ pass
296
+ try:
297
+ matrix_file.write_text(json.dumps(pulled_matrix, indent=2), encoding="utf-8")
298
+ except Exception as e:
299
+ logger.debug(f"Error writing synaptic matrix: {e}")
300
+
301
+ return preserved_names
302
+
303
+ def _merge_lobe_data(self, target_lobe: Any, source_lobe: Any) -> None:
304
+ """Merge source antibodies, synaptic weights, and heuristics into target."""
305
+ # 1. Merge Antibodies by antibody_id
306
+ target_ids = {ab.antibody_id for ab in getattr(target_lobe, "antibodies", [])}
307
+ for ab in getattr(source_lobe, "antibodies", []):
308
+ if ab.antibody_id not in target_ids:
309
+ target_lobe.antibodies.append(ab)
310
+ target_ids.add(ab.antibody_id)
311
+ else:
312
+ # If both have antibody, adopt source counterfactual/defense if target is missing it
313
+ for idx, t_ab in enumerate(target_lobe.antibodies):
314
+ if t_ab.antibody_id == ab.antibody_id:
315
+ if getattr(ab, "verified_counterfactual", "") and not getattr(
316
+ t_ab, "verified_counterfactual", ""
317
+ ):
318
+ target_lobe.antibodies[idx] = ab
319
+ break
320
+
321
+ # 2. Merge Synaptic Weights (max retention)
322
+ source_weights = getattr(source_lobe, "synaptic_weights", {})
323
+ target_weights = getattr(target_lobe, "synaptic_weights", {})
324
+ for node, weight in source_weights.items():
325
+ if node not in target_weights:
326
+ target_weights[node] = weight
327
+ else:
328
+ try:
329
+ target_weights[node] = max(float(weight), float(target_weights[node]))
330
+ except (ValueError, TypeError):
331
+ pass
332
+
333
+ # 3. Merge Activation Count
334
+ target_lobe.activation_count = max(
335
+ getattr(target_lobe, "activation_count", 0),
336
+ getattr(source_lobe, "activation_count", 0),
337
+ )
338
+
339
+ # 4. Merge Specialized Heuristics
340
+ target_heuristics = set(getattr(target_lobe, "specialized_heuristics", []))
341
+ for h in getattr(source_lobe, "specialized_heuristics", []):
342
+ if h not in target_heuristics:
343
+ target_lobe.specialized_heuristics.append(h)
344
+ target_heuristics.add(h)
345
+
346
+ def _sync_host_targets(self) -> list[str]:
347
+ """Hot-sync skills, rules, and MCP session manifests into host environments."""
348
+ synced: list[str] = []
349
+ source_skill = self.repo_root / "skills" / "fable-mode"
350
+ source_rule = self.repo_root / "rules" / "fable-mode.md"
351
+ source_mcp_json = self.repo_root / "fable_engine" / "fable_session.json"
352
+
353
+ # 1. Sync skills into discovered host paths
354
+ for target_skill_dir in self.discover_host_targets():
355
+ try:
356
+ is_explicit = bool(self.skills_dir and target_skill_dir == self.skills_dir.resolve())
357
+ target_parent = target_skill_dir.parent
358
+ if is_explicit or target_parent.exists() or target_skill_dir.exists():
359
+ target_skill_dir.mkdir(parents=True, exist_ok=True)
360
+ if source_skill.exists():
361
+ for root, _, files in os.walk(source_skill):
362
+ rel = Path(root).relative_to(source_skill)
363
+ dest_dir = target_skill_dir / rel
364
+ dest_dir.mkdir(parents=True, exist_ok=True)
365
+ for f in files:
366
+ s_file = Path(root) / f
367
+ d_file = dest_dir / f
368
+ shutil.copy2(s_file, d_file)
369
+ synced.append(str(target_skill_dir))
370
+ except Exception as e:
371
+ logger.debug(f"Failed syncing skill target {target_skill_dir}: {e}")
372
+
373
+ # 2. Sync rule file into host rules directories (e.g. ~/.gemini/config/rules)
374
+ gemini_rules = Path.home() / ".gemini" / "config" / "rules"
375
+ claude_rules = Path.home() / ".claude" / "rules"
376
+ cursor_rules = self.repo_root / ".cursor" / "rules"
377
+ for rule_dir in (gemini_rules, claude_rules, cursor_rules):
378
+ try:
379
+ if rule_dir.exists() and source_rule.exists():
380
+ dest_rule = rule_dir / "fable-mode.md"
381
+ shutil.copy2(source_rule, dest_rule)
382
+ synced.append(str(dest_rule))
383
+ except Exception as e:
384
+ logger.debug(f"Failed syncing rule to {rule_dir}: {e}")
385
+
386
+ # 3. Sync MCP tool schema into antigravity MCP dir if present
387
+ mcp_dest = Path.home() / ".gemini" / "antigravity" / "mcp" / "fable-engine"
388
+ try:
389
+ if mcp_dest.exists() and source_mcp_json.exists():
390
+ shutil.copy2(source_mcp_json, mcp_dest / "fable_session.json")
391
+ synced.append(str(mcp_dest / "fable_session.json"))
392
+ except Exception as e:
393
+ logger.debug(f"Failed syncing MCP schema: {e}")
394
+
395
+ # 4. Sync antigravity server executables and runtime
396
+ agy_server_dest = Path.home() / ".gemini" / "antigravity" / "fable-engine"
397
+ try:
398
+ if agy_server_dest.exists():
399
+ server_py_src = self.repo_root / "fable_engine" / "server.py"
400
+ if server_py_src.exists():
401
+ shutil.copy2(server_py_src, agy_server_dest / "server.py")
402
+ if source_mcp_json.exists():
403
+ shutil.copy2(source_mcp_json, agy_server_dest / "fable_session.json")
404
+ fleet_json = self.repo_root / "fable_engine" / "fable_coder_fleet.json"
405
+ if fleet_json.exists():
406
+ shutil.copy2(fleet_json, agy_server_dest / "fable_coder_fleet.json")
407
+ v2_src = self.repo_root / "fable_v2"
408
+ if v2_src.exists():
409
+ shutil.copytree(v2_src, agy_server_dest / "fable_v2", dirs_exist_ok=True)
410
+ synced.append(str(agy_server_dest / "server.py"))
411
+ except Exception as e:
412
+ logger.debug(f"Failed syncing antigravity server dest: {e}")
413
+
414
+ return synced
415
+
416
+ def apply_update(self, preserve_cortex: bool = True) -> dict[str, Any]:
417
+ """Pull latest upstream changes via git --ff-only, preserve cortex, and hot-sync."""
418
+ git_dir = self.repo_root / ".git"
419
+ if not git_dir.exists():
420
+ # If not git repo, still attempt hot-sync
421
+ synced = self._sync_host_targets()
422
+ return {
423
+ "success": True,
424
+ "updated": False,
425
+ "message": "Standalone non-git installation. Host skills hot-synced successfully.",
426
+ "preserved_lobes": [],
427
+ "synced_targets": synced,
428
+ }
429
+
430
+ # 1. Snapshot cortex if requested
431
+ snapshot = self._snapshot_cortex() if preserve_cortex else {}
432
+
433
+ # 2. Revert any local test-run modifications in cortex to allow ff-only git pull
434
+ try:
435
+ cortex_rel = "skills/fable-mode/cortex"
436
+ subprocess.run(
437
+ ["git", "checkout", "--", cortex_rel],
438
+ cwd=str(self.repo_root),
439
+ capture_output=True,
440
+ text=True,
441
+ timeout=5.0,
442
+ )
443
+ except Exception:
444
+ pass
445
+
446
+ # 3. Run git pull --ff-only
447
+ pull_successful = False
448
+ pull_output = ""
449
+ try:
450
+ pull_res = subprocess.run(
451
+ ["git", "pull", "--ff-only", "origin", "main"],
452
+ cwd=str(self.repo_root),
453
+ capture_output=True,
454
+ text=True,
455
+ timeout=15.0,
456
+ )
457
+ pull_successful = (pull_res.returncode == 0)
458
+ pull_output = pull_res.stdout.strip() or pull_res.stderr.strip()
459
+
460
+ if not pull_successful and self.remote_url:
461
+ # Try fetching directly from remote_url
462
+ fetch_res = subprocess.run(
463
+ ["git", "fetch", self.remote_url, "main"],
464
+ cwd=str(self.repo_root),
465
+ capture_output=True,
466
+ text=True,
467
+ timeout=15.0,
468
+ )
469
+ if fetch_res.returncode == 0:
470
+ merge_res = subprocess.run(
471
+ ["git", "merge", "--ff-only", "FETCH_HEAD"],
472
+ cwd=str(self.repo_root),
473
+ capture_output=True,
474
+ text=True,
475
+ timeout=10.0,
476
+ )
477
+ pull_successful = (merge_res.returncode == 0)
478
+ pull_output = merge_res.stdout.strip() or merge_res.stderr.strip()
479
+ except Exception as e:
480
+ pull_output = f"Git pull error: {e}"
481
+
482
+ # 4. Merge & restore preserved cortex experience
483
+ preserved: list[str] = []
484
+ if preserve_cortex and snapshot:
485
+ try:
486
+ preserved = self._merge_and_restore_cortex(snapshot)
487
+ except Exception as e:
488
+ logger.error(f"Error restoring cortex: {e}")
489
+
490
+ # 5. Hot-sync to host skill targets
491
+ synced = self._sync_host_targets()
492
+
493
+ updated = pull_successful and "Already up to date" not in pull_output
494
+ msg = f"Update applied: {pull_output}." if pull_successful else f"Update check/pull note: {pull_output}."
495
+
496
+ return {
497
+ "success": pull_successful or (len(synced) > 0),
498
+ "updated": updated,
499
+ "message": msg,
500
+ "preserved_lobes": preserved,
501
+ "synced_targets": synced,
502
+ }
503
+
504
+ def _background_worker(self) -> None:
505
+ """Background thread worker running silent update check and hot-sync."""
506
+ global _BG_RUNNING
507
+ with _BG_LOCK:
508
+ _BG_RUNNING = True
509
+ try:
510
+ status = self.check_for_updates(timeout_seconds=4.0)
511
+ if status.get("update_available"):
512
+ logger.info(
513
+ f"Auto-update: detected upstream commit {status.get('remote_commit')[:8]}. Silently updating..."
514
+ )
515
+ res = self.apply_update(preserve_cortex=True)
516
+ logger.info(f"Auto-update completed: {res.get('message')}")
517
+ else:
518
+ logger.debug(f"Auto-update check: {status.get('message')}")
519
+ except Exception as e:
520
+ logger.debug(f"Silent auto-update worker non-fatal exception: {e}")
521
+ finally:
522
+ with _BG_LOCK:
523
+ _BG_RUNNING = False
524
+
525
+ def trigger_silent_background_update(self) -> threading.Thread:
526
+ """Spawn a non-blocking daemon thread to silently check and hot-sync updates."""
527
+ global _BG_RUNNING
528
+ with _BG_LOCK:
529
+ if _BG_RUNNING:
530
+ # Already running in background
531
+ dummy = threading.Thread(target=lambda: None, daemon=True)
532
+ dummy.start()
533
+ return dummy
534
+
535
+ thread = threading.Thread(
536
+ target=self._background_worker,
537
+ name="FableAutoUpdaterDaemon",
538
+ daemon=True,
539
+ )
540
+ thread.start()
541
+ return thread
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 REX-codebase contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+