Kolostov

NodePHP :: Liquid Prototype

Dec 31st, 2025 (edited)
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 372.09 KB | Software | 0 0
  1. <?php declare(strict_types=1);
  2.  
  3. const NAME = "node";
  4.  
  5. # Base framework name.
  6. define("FW_NAME", ucfirst(NAME) . "PHP");
  7. const FW_VERSION = 0.2;
  8.  
  9. # Paths
  10. const D = DIRECTORY_SEPARATOR;
  11. define("ROOT_PATH", realpath(getcwd() ?: __DIR__ . (file_exists("index.php") || file_exists("index.html") || !file_exists(basename(__FILE__)) ? "/.." : "")) . D);
  12.  
  13. # file begin: dev prod
  14. /*
  15.  * @param string $fn Complete path to file.
  16.  * @param string $action Which file action to preform, find by default.
  17.  * @param string $arg An argument for action, null by default.
  18.  * @param string $critical Throws if file does not exist.
  19.  *
  20.  * @return string Real path.
  21.  */
  22. function f(string $fn, string $action = "find", ?string $arg = null, bool $critical = true): mixed
  23. {
  24.     static $ops = [array_combine(p(":order"), array_map(fn($x) => [], p(":order")))];
  25.  
  26.     if ($fn === ":dump") {
  27.         return implode("\n", array_column($ops, "path"));
  28.     }
  29.  
  30.     # Disable all outofphase fileoprations (un-rollbackable)
  31.    if (p(":index") === -1) {
  32.         throw new RuntimeException("Attempting outofphase file operations.");
  33.     }
  34.  
  35.     # Rollback the entire stack of file operations.
  36.    if ($fn === ":rollback") {
  37.         if (!empty($ops[p(":name")])) {
  38.             foreach (array_reverse($ops[p(":name")]) as $op) {
  39.                 try {
  40.                     match ($op["action"]) {
  41.                         "write" => file_put_contents($op["path"], $op["old_content"] ?? ""),
  42.                         "append" => file_put_contents($op["path"], $op["old_content"] ?? ""),
  43.                         "delete" => !file_exists($op["path"]) && file_put_contents($op["path"], $op["content"]),
  44.                         "copy" => file_exists($op["new_path"]) && unlink($op["new_path"]),
  45.                         "move" => rename($op["new_path"], $op["old_path"]),
  46.                     };
  47.                 } catch (Exception $e) {
  48.                     return r($e->getMessage(), "RollbackException", false, ["op" => $op, "error" => (array) $e]);
  49.                 }
  50.             }
  51.  
  52.             # On success do reset internal stack.
  53.            $ops[p(":name")] = [];
  54.  
  55.             # Success.
  56.            return true;
  57.         }
  58.         return false;
  59.     }
  60.  
  61.     # We can wite/append to files that are not there.
  62.    if (!in_array($action, ["write", "append"])) {
  63.         # Try to set real path from multiple sources.
  64.        if (!($real_path = file_exists($fn) ? $fn : null)) {
  65.             /* TODO:
  66.             global $ROOT_PATHS;
  67.  
  68.             $fn = ltrim(str_replace(ROOT_PATH, "", $fn), D);
  69.             foreach ($ROOT_PATHS as $path) {
  70.                 $sfn = "{$path}{$fn}";
  71.                 if (file_exists($sfn)) {
  72.                     $real_path = h("f.realpath", $sfn);
  73.                     break;
  74.                 }
  75.             }
  76.             */
  77.         }
  78.  
  79.         # Throw early if critical file cannot be targeted.
  80.        $real_path ?? ($critical ? throw new RuntimeException("File not found: {$fn}") : null);
  81.     } else {
  82.         # Write into given path.
  83.        $real_path = h("f.realpath", $fn);
  84.     }
  85.  
  86.     # If we're just finding targeted file or the targeted file cannot
  87.    # proceed with any operation (it being null) return real_path as value.
  88.    if ($action === "find" || !isset($real_path) || $real_path === null) {
  89.         return $real_path ?? null;
  90.     }
  91.  
  92.     $old_content = !is_dir($real_path) ? (file_exists($real_path) ? file_get_contents($real_path) : null) : null;
  93.  
  94.     # Base parameters of this file action.
  95.    # this is to be added to depending on given action for future possible rollback.
  96.    $op_record = h("f.op.record", ["action" => $action, "path" => $real_path, "old_content" => $old_content]);
  97.  
  98.     switch ($action) {
  99.         case "write":
  100.             try {
  101.                 $r = file_put_contents(h("f.write.path", $real_path), h("f.write.content", $arg));
  102.             } catch (Exception $e) {
  103.                 return r("Write action: " . $e->getMessage(), "Exception", false, $op_record);
  104.             }
  105.             $ops[p(":name")][] = $op_record;
  106.             return $r;
  107.         case "append":
  108.             try {
  109.                 $r = file_put_contents(h("f.append.path", $real_path), h("f.append.content", $arg), FILE_APPEND);
  110.             } catch (Exception $e) {
  111.                 return r("Append action: " . $e->getMessage(), "Exception", false, $op_record);
  112.             }
  113.             $ops[p(":name")][] = $op_record;
  114.             return $r;
  115.         case "delete":
  116.             if (file_exists($real_path)) {
  117.                 try {
  118.                     $r = unlink(h("f.delete.path", $real_path));
  119.                 } catch (Exception $e) {
  120.                     return r("Delete action: " . $e->getMessage(), "Exception", false, $op_record);
  121.                 }
  122.                 $op_record["content"] = h("f.delete.content", $old_content);
  123.                 $ops[p(":name")][] = $op_record;
  124.                 return $r;
  125.             }
  126.             return null;
  127.         case "copy":
  128.             if (file_exists($real_path) && $arg !== null) {
  129.                 $new_path = h("f.copy.to", $arg);
  130.                 $op_record["new_path"] = $new_path;
  131.  
  132.                 try {
  133.                     $r = copy(h("f.copy.from", $real_path), $new_path);
  134.                 } catch (Exception $e) {
  135.                     return r("Copy action: " . $e->getMessage(), "Exception", false, $op_record);
  136.                 }
  137.                 $ops[p(":name")][] = $op_record;
  138.                 return $r;
  139.             }
  140.             return null;
  141.         case "move":
  142.             if (file_exists($real_path) && $arg !== null) {
  143.                 $new_path = h("f.move.to", $arg);
  144.                 $old_path = h("f.move.from", $real_path);
  145.                 $op_record["new_path"] = $new_path;
  146.                 $op_record["old_path"] = $old_path;
  147.  
  148.                 try {
  149.                     $r = rename($old_path, $new_path);
  150.                 } catch (Exception $e) {
  151.                     return r("Move action: " . $e->getMessage(), "Exception", false, $op_record);
  152.                 }
  153.  
  154.                 $ops[p(":name")][] = $op_record;
  155.                 $real_path = $new_path;
  156.                 return $r;
  157.             }
  158.             return null;
  159.         case "read":
  160.         default:
  161.             return file_get_contents(h("f.read.path", $real_path));
  162.     }
  163. }
  164. # file end;
  165.  
  166. # return begin: dev prod
  167. /**
  168.  * A return passtrough / logger.
  169.  *
  170.  * @method r
  171.  *
  172.  */
  173. function r(string $msg, string $type = "Internal", mixed $return = null, null|array|object $data = null): mixed
  174. {
  175.     static $runtimeLogs = [];
  176.  
  177.     $logFn = h("r.log.fn", _node_project("path") . "Log" . D);
  178.  
  179.     # Process logging commands.
  180.    if (str_starts_with($msg, ":") || $msg === "?" || $msg === "") {
  181.         $msgParts = explode(" ", $msg);
  182.         $command = count($msgParts) > 1 && $type === "Internal" ? [implode(" ", array_slice($msgParts, 1))] : explode(" ", $type);
  183.         $spacePos = strpos($msg, " ");
  184.         $type = substr($msg, 1, $spacePos ? $spacePos - 1 : null);
  185.  
  186.         # :types For getting list of defined types.
  187.        if ($type === "types") {
  188.             return array_map("basename", glob("{$logFn}*") ?? []);
  189.         }
  190.  
  191.         if ($type === "inbox") {
  192.             return array_filter(array_map(fn($t) => ":$t [" . count(glob($logFn . $t . D . "*.log")) . "]", r(":types")), fn($n) => strpos($n, "[0]") === false);
  193.         }
  194.  
  195.         if ($type === "runtime") {
  196.             return $runtimeLogs;
  197.         }
  198.  
  199.         if ($type === "clear") {
  200.             $r = [];
  201.             foreach (r(":types") as $type) {
  202.                 $r = [...$r, ...array_map("unlink", glob(_node_project("path") . "Log" . D . $type . D . "*.log"))];
  203.             }
  204.             return $r;
  205.         }
  206.  
  207.         # :last and :pop For first last in first non-empty type.
  208.        if (in_array($type, ["last", "pop"])) {
  209.             if ($typeFolders = r(":types")) {
  210.                 # Take first containing folder
  211.                foreach ($typeFolders as $t) {
  212.                     if (count(glob($logFn . $t . D . "*.log"))) {
  213.                         return r(":{$t}", $type);
  214.                     }
  215.                 }
  216.                 return "All types [" . implode(", ", $typeFolders) . "] are empty.\n";
  217.             }
  218.             return "No logs exist.\n";
  219.         }
  220.  
  221.         # Help
  222.        if (in_array($type, h("r.list.types", ["help", ""]))) {
  223.             # List of types to string.
  224.            $types = implode("\n", r(":inbox"));
  225.             return "List of logged types:\n{$types}\n\nCall :<type>, <action>\nAction: archive, clear, last, pop";
  226.         }
  227.     }
  228.  
  229.     # Path from local root.
  230.    $path = h("r.path", $logFn . $type . D);
  231.  
  232.     $print = function (string $file, int $n, array $data): string {
  233.         $out = "\033[1;36m" . basename($file) . "\033[0m";
  234.         $out .= " (\033[1;33m{$n} lines\033[0m)\n";
  235.         $out .= "Path: \033[0;90m{$file}\033[0m\n\n";
  236.  
  237.         if ($t = $data["t"] ?? null) {
  238.             $out .= "\033[1;37mTimestamp:\033[0m \033[0;33m" . date("Y-m-d H:i:s", $t) . "\033[0m (\033[0;90m{$t}\033[0m)\n";
  239.         }
  240.  
  241.         isset($data["p"]) && ($out .= "\033[1;37mFile:\033[0m \033[0;32m{$data["p"]}\033[0m\n");
  242.         isset($data["l"]) && ($out .= "\033[1;37mLine:\033[0m \033[0;36m{$data["l"]}\033[0m\n");
  243.         isset($data["n"]) && ($out .= "\033[1;37mFunction:\033[0m \033[0;35m{$data["n"]}\033[0m\n");
  244.  
  245.         isset($data["m"]) && ($out .= "\n\033[1;37mMessage:\033[0m\n" . "\033[1;31m{$data["m"]}\033[0m\n");
  246.  
  247.         if ($err = $data["d"]["error"] ?? null) {
  248.             foreach ($err as $k => $v) {
  249.                 if (str_contains($k, "\0")) {
  250.                     $ck = str_replace(["\0*\0", "\0Exception\0"], "", $k);
  251.                     $map = [
  252.                         "message" => "Exception Message",
  253.                         "string" => "Exception String",
  254.                         "code" => "Exception Code",
  255.                         "file" => "Exception File",
  256.                         "line" => "Exception Line",
  257.                         "trace" => "Stack Trace",
  258.                         "previous" => "Previous Exception",
  259.                     ];
  260.                     $err[$map[$ck] ?? $ck] = $v;
  261.                     unset($err[$k]);
  262.                 }
  263.             }
  264.  
  265.             $out .= "\n\033[1;37mError Details:\033[0m\n";
  266.  
  267.             foreach ($err as $k => $v) {
  268.                 if ($k === "Stack Trace") {
  269.                     $out .= "\033[1;34m{$k}:\033[0m\n";
  270.                     foreach ($v as $i => $t) {
  271.                         $t["file"] ??= "Unknown file";
  272.                         $t["line"] ??= -1;
  273.  
  274.                         $out .= "  \033[0;90m[{$i}]\033[0m ";
  275.                         $out .= "\033[0;35m" . ($t["class"] ?? "") . ($t["type"] ?? "") . $t["function"] . "\033[0m\n";
  276.                         $out .= "      \033[0;90m{$t["file"]}:{$t["line"]}\033[0m\n";
  277.                     }
  278.                 } else {
  279.                     $out .= "\033[1;34m{$k}:\033[0m ";
  280.                     $out .= $v === null || $v === "" ? "\033[0;90m(empty)\033[0m\n" : "\033[0;37m" . (is_array($v) ? json_encode($v, JSON_PRETTY_PRINT) : $v) . "\033[0m\n";
  281.                 }
  282.             }
  283.         }
  284.  
  285.         if ($d = $data["d"] ?? null) {
  286.             unset($d["error"]);
  287.             if ($d) {
  288.                 $out .= "\n\033[1;37mAdditional Data:\033[0m\n";
  289.                 foreach ($d as $k => $v) {
  290.                     $out .= "\033[1;34m{$k}:\033[0m ";
  291.                     $out .= empty($v)
  292.                         ? "\033[0;90m(empty)\033[0m\n"
  293.                         : (is_array($v)
  294.                             ? "\n\033[0;90m" . json_encode($v, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . "\033[0m\n"
  295.                             : "\033[0;37m{$v}\033[0m\n");
  296.                 }
  297.             }
  298.         }
  299.  
  300.         if (array_key_exists("r", $data)) {
  301.             $ok = (bool) $data["r"];
  302.             $out .= "\n\033[1;37mResult:\033[0m \033[" . ($ok ? "1;32" : "1;31") . "m" . ($ok ? "true" : "false") . "\033[0m\n";
  303.         }
  304.  
  305.         return $out;
  306.     };
  307.  
  308.     if (isset($command)) {
  309.         # Command dirs must exist beforehand.
  310.        if (!is_dir($path)) {
  311.             return "E: No logs found at: {$path}\n";
  312.         }
  313.         switch ($command[0]) {
  314.             case "archive":
  315.                 $return = "Archivation routine executed.\n";
  316.                 break;
  317.             case "clear":
  318.                 $files = array_map("unlink", glob("{$path}*.log"));
  319.                 return rmdir($path) && "Nothing was deleted.\n";
  320.             case "last":
  321.                 if ($files = glob("{$path}*.log")) {
  322.                     $logs = array_combine($files, array_map("filemtime", $files));
  323.                     arsort($logs);
  324.  
  325.                     $file = array_key_first($logs);
  326.                     $last = file($file);
  327.                     $n = count($last);
  328.  
  329.                     $data = json_decode(end($last), true);
  330.  
  331.                     return $print($file, $n, $data ?? []);
  332.                 }
  333.             case "pop":
  334.                 if ($files = glob("{$path}*.log")) {
  335.                     $logs = array_combine($files, array_map("filemtime", $files));
  336.                     arsort($logs);
  337.  
  338.                     $file = array_key_first($logs);
  339.                     $logs = array_filter(file($file, FILE_IGNORE_NEW_LINES), fn($x) => !empty($x));
  340.                     array_pop($logs);
  341.                     if (!empty($logs)) {
  342.                         f($file, "write", implode(PHP_EOL, $logs));
  343.                     } else {
  344.                         # Removal of last log unlinks the file.
  345.                        unlink($file);
  346.                     }
  347.                     return r(":{$type}", "last");
  348.                 }
  349.             default:
  350.                 return implode("\n", array_map("dump", glob("{$path}*.log")));
  351.         }
  352.     } else {
  353.         if (!is_dir($path)) {
  354.             mkdir($path, 0777, true);
  355.         }
  356.     }
  357.  
  358.     # Current date and logfile path.
  359.    $day = h("r.day", date("Y-m-d"));
  360.     $lf = h("r.log.file", "{$path}{$day}.log");
  361.  
  362.     # Main trace.
  363.    $trace = h("r.log.trace", debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3));
  364.  
  365.     $entry = [
  366.         "t" => time(), // timestamp
  367.         "p" => str_replace([ROOT_PATH, _node_project("path")], ["", ""], $trace[0]["file"] ?? "unknown"),
  368.         "l" => $trace[0]["line"] ?? 0, // line number
  369.         "n" => $trace[1]["function"] ?? "#rootcode", // function
  370.         "m" => $msg, // message
  371.         "d" => $data ? (array) $data : null, // data
  372.         "r" => $return, // result
  373.     ];
  374.  
  375.     if (PHP_SAPI !== "cli") {
  376.         $entry["i"] = $_SERVER["REMOTE_ADDR"] ?? "cli"; // ip
  377.         $entry["h"] = $_SERVER["REQUEST_METHOD"] ?? "cli"; // method
  378.         $entry["u"] = $_SERVER["REQUEST_URI"] ?? "cli"; // url
  379.     }
  380.  
  381.     # Allow entry hooking.
  382.    $entry = h("r.log.entry", $entry);
  383.  
  384.     f($lf, "append", json_encode($entry, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n");
  385.  
  386.     $part = ["Y", "m"];
  387.     while (!empty($part)) {
  388.         $prev = date(implode("-", $part), strtotime("-1 " . (end($part) === "m" ? "month" : "year")));
  389.  
  390.         $files = glob("{$path}{$prev}-*.log");
  391.         if ($files) {
  392.             $merged = [];
  393.             foreach ($files as $fp) {
  394.                 $c = trim(f($fp, "read", null, false) ?? "");
  395.                 if ($c === "") {
  396.                     continue;
  397.                 }
  398.                 if ($c[0] === "[") {
  399.                     $c = trim($c, "[] \n\r\t");
  400.                     if ($c !== "") {
  401.                         $merged[] = $c;
  402.                     }
  403.                 } else {
  404.                     $merged[] = $c;
  405.                 }
  406.             }
  407.  
  408.             if ($merged) {
  409.                 f("{$path}{$prev}.log", "write", "[\n" . implode(",\n", $merged) . "\n]");
  410.                 foreach ($files as $fp) {
  411.                     unlink($fp);
  412.                 }
  413.             }
  414.         }
  415.         array_pop($part);
  416.     }
  417.  
  418.     # Set every log to runtime log.
  419.    $logOnFn = str_replace([ROOT_PATH, _node_project("path")], ["", ""], $entry["p"]);
  420.     $runtimeLogs[$type][] = $msg . (is_int($return) ? " Exit: {$return}" : "") . " @{$logOnFn}:{$entry["l"]}";
  421.  
  422.     return $return;
  423. }
  424. # return end;
  425.  
  426. # hook begin: dev prod
  427. /**
  428.  * @param ?string $name Hook name for runnig or registration.
  429.  * @param mixed $arg Hook function or argument to run registred hooks as filters.
  430.  * @param array $allowedin # array of phases this hooking is allowed in.
  431.  */
  432. function h(?string $name = null, mixed $arg = null, array $allowedin = []): mixed
  433. {
  434.     static $hooks = [];
  435.  
  436.     if ($name === null) {
  437.         return array_map("count", $hooks);
  438.     }
  439.  
  440.     if (!is_string($arg) && is_callable($arg)) {
  441.         $hooks[$name][] = $arg;
  442.         return true;
  443.     }
  444.  
  445.     if (!isset($hooks[$name])) {
  446.         return $arg;
  447.     }
  448.  
  449.     if (empty($allowedin) || in_array(p(":phase"), $allowedin)) {
  450.         if ($arg === null) {
  451.             foreach ($hooks[$name] as $fn) {
  452.                 try {
  453.                     $fn();
  454.                 } catch (Throwable $e) {
  455.                     r($e->getMessage(), "Throwable", null, [
  456.                         "exception" => get_class($e),
  457.                         "code" => $e->getCode(),
  458.                         "file" => $e->getFile(),
  459.                         "line" => $e->getLine(),
  460.                         "trace" => $e->getTraceAsString(),
  461.                         "hook" => $name,
  462.                     ]);
  463.                 }
  464.             }
  465.             return null;
  466.         }
  467.  
  468.         foreach ($hooks[$name] as $fn) {
  469.             try {
  470.                 $arg = $fn($arg);
  471.             } catch (Throwable $e) {
  472.                 r($e->getMessage(), "Throwable", $arg, [
  473.                     "exception" => get_class($e),
  474.                     "code" => $e->getCode(),
  475.                     "file" => $e->getFile(),
  476.                     "line" => $e->getLine(),
  477.                     "trace" => $e->getTraceAsString(),
  478.                     "hook" => $name,
  479.                 ]);
  480.             }
  481.         }
  482.         return $arg;
  483.     }
  484.     return null;
  485. }
  486. # hook end;
  487.  
  488. # phase begin: dev prod
  489. class Context
  490. {
  491.     private array $owner = [];
  492.     private array $closures = [];
  493.  
  494.     /**
  495.      * @param string $phase Context phase name.
  496.      * @param array $state Local state array.
  497.      * @param string $fid function identifier for variable mutation constraint.
  498.      */
  499.     public function __construct(public string $phase, public array &$state, public string $fid) {}
  500.  
  501.     /**
  502.      * Passes modified $key trough __set function and checks ownership.
  503.      */
  504.     private function __define(string $scope, string $k, mixed $v = "\0"): mixed
  505.     {
  506.         $key = empty($scope) ? $k : "{$scope}:{$k}";
  507.         return $v === "\0"
  508.             ? $this->{$key}
  509.             : (isset($this->state[$key])
  510.                 ? ($this->fid === $this->owner[$key]
  511.                     ? ($this->{$key} = $v)
  512.                     : throw new Exception("Cannot set variable {$key} owned by other scope {$this->owner[$key]}."))
  513.                 : ($this->{$key} = $v));
  514.     }
  515.  
  516.     /*
  517.      * Sets once/gets constant value available globally.
  518.      * All global values are treated as constants.
  519.      */
  520.     public function global(string $k, mixed $v = "\0"): mixed
  521.     {
  522.         # Reading
  523.        if ($v === "\0") {
  524.             return $this->__define("", $k, $v);
  525.         }
  526.  
  527.         # Writing
  528.        if (in_array($this->phase, ["boot"])) {
  529.             if (array_key_exists($k, $this->state)) {
  530.                 throw new Exception("Global constant {$k} already set.");
  531.             }
  532.             return $this->__define("", $k, $v);
  533.         }
  534.         throw new Exception("Constant {$k} should be set during boot phase.");
  535.     }
  536.  
  537.     /*
  538.      * Sets/gets value available within same phase.
  539.      */
  540.     public function public(string $k, mixed $v = "\0"): mixed
  541.     {
  542.         # Return
  543.        return $this->__define($this->phase, $k, $v);
  544.     }
  545.  
  546.     /*
  547.      * Sets/gets value available within same scope.
  548.      */
  549.     public function private(string $k, mixed $v = "\0"): mixed
  550.     {
  551.         # Return
  552.        return $this->__define($this->fid, $k, $v);
  553.     }
  554.  
  555.     /**
  556.      * Registres self to public list of closures.
  557.      */
  558.     public function register(string $name): bool|string
  559.     {
  560.         if (array_key_exists($name, $this->closures)) {
  561.             return false;
  562.         }
  563.         return $this->closures[$name] = $this->fid;
  564.     }
  565.  
  566.     /*
  567.      * Takes targeted closure key.
  568.      */
  569.     public function take(string $closure, string $key): mixed
  570.     {
  571.         if (array_key_exists($closure, $this->closures)) {
  572.             return $this->__define($this->closures[$closure], $key);
  573.         }
  574.         throw new Exception("Closure {$closure} is not registred.");
  575.     }
  576.  
  577.     # ["boot", "discover", "resolve", "execute", "mutate", "persist", "finalize"]
  578.    public function __set(string $k, mixed $v): void
  579.     {
  580.         if (in_array($this->phase, ["boot", "discover", "resolve", "mutate"])) {
  581.             if (array_key_exists($k, $this->state)) {
  582.                 if ($this->owner[$k] === $this->fid) {
  583.                     $this->state[$k] = $v;
  584.                 } else {
  585.                     throw new Exception("Trying to __set {$k} in {$this->phase} owned by other scope.");
  586.                 }
  587.             } else {
  588.                 $this->owner[$k] = $this->fid;
  589.                 $this->state[$k] = $v;
  590.             }
  591.         } else {
  592.             throw new Exception("Declaration of variables in {$this->phase} is forbidden.");
  593.         }
  594.     }
  595.  
  596.     public function __get(string $k): mixed
  597.     {
  598.         return $this->state[$k] ?? null;
  599.     }
  600. }
  601.  
  602. /**
  603.  * @param int|string|null $phase Phase index or name of the addressed phase.
  604.  * Leave this param empty if running all phases in sequence.
  605.  *
  606.  * @param object|string|null $action Expecting relative path from ROOT_PATH
  607.  * to file w/o extension or function declaration fn($name, &$state_copy):object {...}
  608.  *
  609.  * IMPORTANT! Every $action must return $this; object.
  610.  *
  611.  * @return mixed Operation success status or resulted state array.
  612.  */
  613. function p(int|string|null $phase = null, object|string|null $action = null): mixed
  614. {
  615.     # Active record Declarations.
  616.    static $phases = [],
  617.         $state = [],
  618.         $backups = [];
  619.     static $depLoading = false;
  620.  
  621.     # Phase cursor.
  622.    static $cursor = 0;
  623.  
  624.     # Order of phases and the list of available phases.
  625.    static $order = h("p.order", ["boot", "discover", "resolve", "execute", "mutate", "persist", "finalize"]);
  626.  
  627.     # List all available phases in order of execution.
  628.    if ($phase === ":order") {
  629.         return $order;
  630.     }
  631.  
  632.     if ($phase === ":index" || $phase === ":cursor") {
  633.         return $cursor;
  634.     }
  635.  
  636.     if ($phase === ":name") {
  637.         return $order[$cursor] ?? "outofphase";
  638.     }
  639.  
  640.     if ($phase === ":state") {
  641.         return $state;
  642.     }
  643.  
  644.     if ($phase === ":depload") {
  645.         if ($action !== null) {
  646.             $depLoading = !empty($action);
  647.         }
  648.         return $depLoading;
  649.     }
  650.  
  651.     # Dump phase orchestrator.
  652.    if ($phase === ":dump") {
  653.         return h("p.dump", [
  654.             "phases" => $phases,
  655.             "state" => $state,
  656.             "backups" => $backups,
  657.             "cursor" => $cursor,
  658.             "name" => $order[$cursor] ?? "outofphase",
  659.             "deploading" => $depLoading,
  660.         ]);
  661.     }
  662.  
  663.     # Try to target evolution to given phase.
  664.    if ($phase !== null) {
  665.         # Decide the name from given index or given name.
  666.        $targetName = is_int($phase) ? $order[$phase] ?? null : $phase;
  667.  
  668.         # Invalid phase?
  669.        if ($targetName === null || !in_array($targetName, $order)) {
  670.             throw new InvalidArgumentException("Unknown phase: {$phase}");
  671.         }
  672.     }
  673.  
  674.     if ($phase === null || ($targetName && $action === null)) {
  675.         if ($depLoading) {
  676.             return $state; // silently no-op during dep loading
  677.         }
  678.  
  679.         # We got name w/o action or we have no phase (targeting entire run).
  680.        $targetIndex = isset($targetName) ? array_search($targetName, $order) : null;
  681.  
  682.         # Trying to run phase that's already processed.
  683.        if (isset($targetName) && $targetIndex <= $cursor) {
  684.             return $state;
  685.         }
  686.  
  687.         foreach ($order as $index => $name) {
  688.             # Skipping all processed and empty/unutilized phases.
  689.            if ($index < $cursor || empty($phases[$name] ?? [])) {
  690.                 continue;
  691.             }
  692.  
  693.             # Begin processing.
  694.            $copy = $state;
  695.  
  696.             # Give extract $copy to $handler closure via $this
  697.            # array_map(fn($k) => ($context->{$k} = $copy[$k]), array_keys($copy));
  698.  
  699.             try {
  700.                 foreach ($phases[$name] ?? [] as $handler) {
  701.                     # New context for each phase context.
  702.                    $context = new Context($name, $copy, spl_object_hash($handler));
  703.  
  704.                     $boundFunc = $handler->bindTo($context, Context::class);
  705.                     $handlerResult = (array) ($boundFunc($name, $copy) ?? []);
  706.  
  707.                     if ($handlerResult !== null && !empty($handlerResult)) {
  708.                         $copy = [...$copy, ...$handlerResult];
  709.                     }
  710.                 }
  711.                 $state = $copy;
  712.                 $backups[$name] = $state;
  713.             } catch (Throwable $e) {
  714.                 # Rollback current phase file actions.
  715.                f(":rollback");
  716.  
  717.                 # Set previous state to current phase.
  718.                $state = $backups[$order[$index - 1]] ?? [];
  719.  
  720.                 # Log error.
  721.                return r($e->getMessage(), "PhaseException", false, [
  722.                     "phase" => $name,
  723.                     "state" => $state,
  724.                     "error" => (array) $e,
  725.                 ]);
  726.             }
  727.  
  728.             # Set cursor to have done this index.
  729.            $cursor = $index + 1;
  730.  
  731.             # Check if we have just processed our desired target phase.
  732.            if ($targetIndex !== null && $index === $targetIndex) {
  733.                 break;
  734.             }
  735.         }
  736.  
  737.         # Phase reached.
  738.        return $state;
  739.     }
  740.  
  741.     # Set action inside phase if it is a string or callable.
  742.    if ($action instanceof Closure || is_callable($action)) {
  743.         $phases[$targetName][] = $action;
  744.  
  745.         # Closure set.
  746.        return true;
  747.     } elseif (is_string($action)) {
  748.         # If requested file was not found, throw softly without immediate die.
  749.        if ($file = f("{$action}.php", "find", null, false)) {
  750.             # File inclusion given.
  751.            $phases[$targetName][] = function ($name, &$copy) use ($file) {
  752.                 # Actual file to run.
  753.                include_once $file;
  754.  
  755.                 /**
  756.                  * @var object $this given by bindTo from p() phase runner.
  757.                  */
  758.                 return $this;
  759.             };
  760.         }
  761.  
  762.         # Log.
  763.        return r("Phase file not found: $action.php", "Exception", false, ["phase" => $targetName, "file" => $action]);
  764.     }
  765.  
  766.     # Nothing got set in phase.
  767.    return null;
  768. }
  769. # phase end;
  770.  
  771. # dump begin dev
  772. $ALLOWED_DUMP_EXTENSIONS = ["php", "js", "css"];
  773.  
  774. /**
  775.  * Generate the introductory header with ground rules for LLM
  776.  *
  777.  * @param string|null $searchQuery Optional search query context
  778.  * @return string Formatted header text
  779.  */
  780. function _node_dump_generate_header($searchQuery = null)
  781. {
  782.     global $ALLOWED_DUMP_EXTENSIONS;
  783.  
  784.     $h = "# NODEPHP FRAMEWORK INTERACTION CONTEXT\n\n";
  785.  
  786.     if ($searchQuery !== null) {
  787.         $h .= "## CURRENT CONTEXT: FILTERED DUMP\n";
  788.         $h .= "The following content is a subset of the project, filtered by the query: '{$searchQuery}'.\n\n";
  789.     } else {
  790.         $h .= "## CURRENT CONTEXT: FULL PROJECT DUMP\n";
  791.         $h .= "The following represents the complete state of the project files.\n\n";
  792.     }
  793.  
  794.     $h .= "### Framework Architecture\n";
  795.     $h .=
  796.         "This project operates on NodePHP, a phase-oriented framework. Execution flows through strict phases: boot, discover, resolve, execute, mutate, persist, finalize. The architecture treats code not as monolithic scripts, but as a collection of independent, addressable blocks. This modularity enables granular state management and surgical updates.\n\n";
  797.  
  798.     $h .= "### The Feed/Dump Cycle\n";
  799.     $h .= "Communication with this system is a synchronization process between the codebase state and your context window:\n\n";
  800.     $h .=
  801.         "1. **The Dump (Input)**: You receive a serialized view of the project. To optimize token usage, the system strips non-essential comments while preserving structural markers (`/* begin id */ ... /* end id */`). This provides a clean functional logic map.\n\n";
  802.     $h .=
  803.         "2. **The Feed (Output)**: Your response is parsed by the `feed()` function. You are expected to return code using the specific block markers. The system uses these markers to locate the exact insertion or replacement points within the target files.\n\n";
  804.  
  805.     $h .= "### Block Syntax Specification\n";
  806.     $h .= "To modify code, you must use the following delimiter formats:\n\n";
  807.     $h .= "**PHP/JS/CSS Blocks:**\n";
  808.     $h .= "```\n";
  809.     $h .= "/* begin unique_identifier */\n";
  810.     $h .= "// Code content\n";
  811.     $h .= "/* end unique_identifier */\n";
  812.     $h .= "```\n\n";
  813.  
  814.     $h .= "**CRITICAL CONSTRAINTS:**\n";
  815.     $h .=
  816.         "- **Placement**: Block markers are C-style comments. They must be placed *inside* code regions (after `<?php` in PHP files). Never use them before the opening `<?php` tag or in files that do not support comments (e.g., `.htaccess`, `.env`).\n";
  817.     $h .=
  818.         "- **Usage**: Use block markers frequently to segment logical units within files. Every distinct logical section (method, conditional block, configuration array) should ideally be wrapped in a block.\n\n";
  819.  
  820.     $h .= "### Response Formatting Rules\n";
  821.     $h .= "When returning code blocks, strictly adhere to the following file header format:\n";
  822.     $h .= "```\n";
  823.     $h .= "## Path/To/File.php\n";
  824.     $h .= "```\n";
  825.     $h .= "- **No Prefix**: Do not prefix paths with `./`.\n";
  826.     $h .= "- **No Annotations**: Do not append comments like `(edited)`, `(new)`, or `(completed)` to the path line.\n";
  827.     $h .= "- **Clean Path**: The path must be relative to the project root.\n\n";
  828.  
  829.     $h .= "### Operational Logic\n";
  830.     $h .= "The system processes your response with the following logic:\n";
  831.     $h .= "- **Replacement**: If the identifier exists in the file, the corresponding block content is overwritten.\n";
  832.     $h .= "- **Append**: If the file exists but the identifier is new, the block is appended to the end of the file.\n";
  833.     $h .= "- **Creation**: If the file does not exist, it is created containing the block.\n";
  834.     $h .= "- **Safety**: Automatic backups (`.backup.json`) are generated for modified files.\n\n";
  835.  
  836.     $h .= "### Project Structure Map\n";
  837.     $h .=
  838.         "The following is a map of defined structures in this project. Use these paths to locate resources correctly. If structural changes are required, update `structure.json` first and feed it as the initial file.\n\n";
  839.  
  840.     # Retrieve and format structure list
  841.    $structs = struct(":dump");
  842.     if (!empty($structs)) {
  843.         $h .= "```\n";
  844.         foreach ($structs as $s) {
  845.             $h .= "{$s}\n";
  846.         }
  847.         $h .= "```\n\n";
  848.     } else {
  849.         $h .= "No structure definitions found (or struct() not yet available).\n\n";
  850.     }
  851.  
  852.     $h .= "### Instructions for the LLM\n";
  853.     $h .= "- **Structure First**: If creating new directories or file types, output `structure.json` first to define the new paths.\n";
  854.     $h .= "- **Surgical Updates**: Return only the specific blocks that need modification. Avoid returning full files unless creating new ones.\n";
  855.     $h .= "- **Identifier Integrity**: Preserve existing identifiers to update logic. Use new, descriptive identifiers for new features.\n";
  856.     $h .= "- **Formatting**: Adhere to the indentation style of the surrounding code. The parser preserves the whitespace within the block.\n";
  857.     $h .= "- **File Scope**: Identifiers must be unique within the file scope.\n";
  858.     $h .= "- **Supported Extensions**: " . implode(", ", $ALLOWED_DUMP_EXTENSIONS) . "\n\n";
  859.  
  860.     $h .= "---\n\n";
  861.  
  862.     return $h;
  863. }
  864.  
  865. /**
  866.  * Recursively scan directory and generate formatted output with comments removed
  867.  *
  868.  * @param string|null $searchQuery Optional text to search for in files
  869.  * @return string Formatted output with all comments stripped (except begin/end blocks)
  870.  */
  871. function _node_dump_generate_dump($searchQuery = null)
  872. {
  873.     global $ALLOWED_DUMP_EXTENSIONS;
  874.  
  875.     // Get paths to exclude from processing
  876.     $currentScript = ROOT_PATH . "node.php";
  877.     $outputFile = _node_project("path") . "dump.txt";
  878.  
  879.     // Create recursive directory iterator to scan all subdirectories
  880.     $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(_node_project("path"), RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST);
  881.  
  882.     $output = _node_dump_generate_header($searchQuery);
  883.     $rootPathLen = strlen(ROOT_PATH);
  884.  
  885.     // First, collect all files for inventory
  886.     $allFiles = [];
  887.     $contentFiles = [];
  888.  
  889.     foreach ($iterator as $file) {
  890.         if ($file->isDir()) {
  891.             continue;
  892.         }
  893.  
  894.         // Skip the script itself and output file
  895.         if ($file->getRealPath() === $currentScript || $file->getRealPath() === $outputFile) {
  896.             continue;
  897.         }
  898.  
  899.         $extension = strtolower($file->getExtension());
  900.         $filename = $file->getFilename();
  901.         $path = substr($file->getPathname(), $rootPathLen);
  902.  
  903.         if (substr($path, 0, 2) === "./") {
  904.             $path = substr($path, 2);
  905.         }
  906.  
  907.         $allFiles[] = [
  908.             "path" => $path,
  909.             "extension" => $extension,
  910.             "filename" => $filename,
  911.             "realpath" => $file->getRealPath(),
  912.         ];
  913.     }
  914.  
  915.     // Sort files by path for consistent output
  916.     usort($allFiles, fn($a, $b) => strcmp($a["path"], $b["path"]));
  917.  
  918.     $count = 1;
  919.     $inventoryCount = 1;
  920.  
  921.     // Process each file
  922.     foreach ($allFiles as $file) {
  923.         $path = $file["path"];
  924.         $extension = $file["extension"];
  925.         $filename = $file["filename"];
  926.         $realpath = $file["realpath"];
  927.  
  928.         // Check if this is a content file (allowed extension)
  929.         $validExtension = in_array($extension, $ALLOWED_DUMP_EXTENSIONS);
  930.         $isHtaccess = $filename === ".htaccess" && in_array("htaccess", $ALLOWED_DUMP_EXTENSIONS);
  931.         $isContentFile = $validExtension || $isHtaccess;
  932.  
  933.         // For search queries, only include files that match the query in content
  934.         if ($searchQuery !== null && $isContentFile) {
  935.             $content = file_get_contents($realpath);
  936.             if (strpos($content, $searchQuery) === false) {
  937.                 // Skip content files that don't match the query
  938.                 continue;
  939.             }
  940.         }
  941.  
  942.         if ($isContentFile) {
  943.             // Full content processing for allowed extensions
  944.             $content = file_get_contents($realpath);
  945.  
  946.             // Remove all comments based on file type, but preserve special begin/end comments
  947.             $content = _node_dump_remove_all_comments($content, $extension);
  948.  
  949.             // Apply simple minification to CSS files only
  950.             $content = $extension === "css" ? _node_dump_minify_css($content) : _node_dump_cleanup_whitespace($content);
  951.  
  952.             // Build formatted output with full content
  953.             $output .= "## {$path}\n"; // File {$count}:
  954.             $output .= "```\n";
  955.             $output .= $content;
  956.             if (substr($content, -1) !== "\n") {
  957.                 $output .= "\n";
  958.             }
  959.             $output .= "```\n\n";
  960.  
  961.             $count++;
  962.         } else {
  963.             // For non-allowed extensions, just list the filename as inventory
  964.             // But only include in inventory if no search query or if filename matches query
  965.             if ($searchQuery === null || stripos($path, $searchQuery) !== false) {
  966.                 $output .= "## {$path} \n\n"; // Inventory {$inventoryCount}: ... (filename for reference only)
  967.                 $inventoryCount++;
  968.             }
  969.         }
  970.     }
  971.  
  972.     // Add summary at the end
  973.     $output .= "---\n";
  974.     $output .= "Summary: " . ($count - 1) . " files with full content, " . ($inventoryCount - 1) . " additional files in inventory.\n";
  975.  
  976.     return $output;
  977. }
  978.  
  979. /**
  980.  * Remove all comments based on file type, but preserve special begin/end comments
  981.  *
  982.  * @param string $content The file content
  983.  * @param string $extension File extension to determine comment style
  984.  * @return string Content with comments removed (except begin/end blocks)
  985.  */
  986. function _node_dump_remove_all_comments($content, $extension)
  987. {
  988.     if ($extension === "php") {
  989.         $content = _node_dump_remove_php_comments($content);
  990.     } elseif ($extension === "js" || $extension === "css") {
  991.         $content = _node_dump_remove_js_css_comments($content);
  992.     }
  993.     return $content;
  994. }
  995.  
  996. /**
  997.  * Remove PHP comments but preserve /* begin ... * / and /* ... end * / blocks
  998.  *
  999.  * @param string $content PHP code content
  1000.  * @return string PHP code with comments removed (except begin/end blocks)
  1001.  */
  1002. function _node_dump_remove_php_comments($content)
  1003. {
  1004.     // First, extract and protect special begin/end comment blocks
  1005.     $protected = [];
  1006.     $counter = 0;
  1007.  
  1008.     // Protect /* begin ... */ blocks
  1009.     $content = preg_replace_callback(
  1010.         '/\/\*\s*begin\s+([^\s]+)\s*\*\/.*?\/\*\s*end\s+\1\s*\*\//ms',
  1011.         function ($matches) use (&$protected, &$counter) {
  1012.             $key = "___PROTECTED_BLOCK_" . $counter++ . "___";
  1013.             $protected[$key] = $matches[0];
  1014.             return $key;
  1015.         },
  1016.         $content,
  1017.     );
  1018.  
  1019.     // Use tokenizer for regular comment removal
  1020.     $tokens = token_get_all($content);
  1021.     $result = "";
  1022.  
  1023.     foreach ($tokens as $token) {
  1024.         if (is_array($token)) {
  1025.             // Check if this token is a protected block placeholder
  1026.             if ($token[0] === T_STRING && isset($protected[$token[1]])) {
  1027.                 $result .= $protected[$token[1]];
  1028.             }
  1029.             // Skip regular comment tokens
  1030.             elseif ($token[0] !== T_COMMENT && $token[0] !== T_DOC_COMMENT) {
  1031.                 $result .= $token[1];
  1032.             }
  1033.         } else {
  1034.             $result .= $token;
  1035.         }
  1036.     }
  1037.  
  1038.     // Restore any protected blocks that might have been missed
  1039.     foreach ($protected as $key => $value) {
  1040.         $result = str_replace($key, $value, $result);
  1041.     }
  1042.  
  1043.     // Additional regex pass for any remaining regular comments
  1044.     $result = preg_replace('/^\s*\/\/.*$/m', "", $result); // Remove // comments
  1045.     $result = preg_replace('/^\s*#.*$/m', "", $result); // Remove # comments
  1046.  
  1047.     return $result;
  1048. }
  1049.  
  1050. /**
  1051.  * Remove JavaScript and CSS comments but preserve /* begin ... * / and /* ... end * / blocks
  1052.  *
  1053.  * @param string $content JS or CSS content
  1054.  * @return string Content with comments removed (except begin/end blocks)
  1055.  */
  1056. function _node_dump_remove_js_css_comments($content)
  1057. {
  1058.     // First, extract and protect special begin/end comment blocks
  1059.     $protected = [];
  1060.     $counter = 0;
  1061.  
  1062.     // Protect /* begin ... */ blocks
  1063.     $content = preg_replace_callback(
  1064.         '/\/\*\s*begin\s+([^\s]+)\s*\*\/.*?\/\*\s*end\s+\1\s*\*\//ms',
  1065.         function ($matches) use (&$protected, &$counter) {
  1066.             $key = "___PROTECTED_BLOCK_" . $counter++ . "___";
  1067.             $protected[$key] = $matches[0];
  1068.             return $key;
  1069.         },
  1070.         $content,
  1071.     );
  1072.  
  1073.     // Remove regular multi-line comments (/* */)
  1074.     $content = preg_replace("/\/\*[\s\S]*?\*\//", "", $content);
  1075.  
  1076.     // Remove single-line comments (//)
  1077.     $lines = explode("\n", $content);
  1078.     $result = [];
  1079.  
  1080.     foreach ($lines as $line) {
  1081.         // Check if line contains // comment, but handle special cases
  1082.         $commentPos = strpos($line, "//");
  1083.         if ($commentPos !== false) {
  1084.             $preceding = substr($line, $commentPos - 1, 1);
  1085.             if ($preceding !== ":" && $preceding !== "/" && $preceding !== "\\") {
  1086.                 $line = substr($line, 0, $commentPos);
  1087.             }
  1088.         }
  1089.  
  1090.         // Check if line contains a protected block placeholder
  1091.         foreach ($protected as $key => $value) {
  1092.             if (strpos($line, $key) !== false) {
  1093.                 $line = str_replace($key, $value, $line);
  1094.             }
  1095.         }
  1096.  
  1097.         if (trim($line) !== "") {
  1098.             $result[] = $line;
  1099.         }
  1100.     }
  1101.  
  1102.     $content = implode("\n", $result);
  1103.  
  1104.     // Restore any protected blocks that might have been split across lines
  1105.     foreach ($protected as $key => $value) {
  1106.         $content = str_replace($key, $value, $content);
  1107.     }
  1108.  
  1109.     return $content;
  1110. }
  1111.  
  1112. /**
  1113.  * Apply simple minification to CSS content
  1114.  * Removes unnecessary whitespace while preserving functionality
  1115.  *
  1116.  * @param string $content CSS content to minify
  1117.  * @return string Minified CSS
  1118.  */
  1119. function _node_dump_minify_css($content)
  1120. {
  1121.     // Remove regular comments (but protected blocks are already preserved)
  1122.     $content = preg_replace("/\/\*[\s\S]*?\*\//", "", $content);
  1123.  
  1124.     // Remove whitespace around symbols: { } : ; ,
  1125.     $content = preg_replace("/\s*([\{\}\:;,])\s*/", '$1', $content);
  1126.  
  1127.     // Remove whitespace around > + ~ selectors
  1128.     $content = preg_replace("/\s*([>+~])\s*/", '$1', $content);
  1129.  
  1130.     // Remove unnecessary spaces in selectors (multiple spaces to single space)
  1131.     $content = preg_replace("/\s+/", " ", $content);
  1132.  
  1133.     // Remove spaces before !important
  1134.     $content = str_replace(" !important", "!important", $content);
  1135.  
  1136.     // Remove leading/trailing whitespace from each line and collapse
  1137.     $lines = explode("\n", $content);
  1138.     $minified = "";
  1139.     foreach ($lines as $line) {
  1140.         $trimmed = trim($line);
  1141.         if ($trimmed !== "") {
  1142.             $minified .= $trimmed;
  1143.         }
  1144.     }
  1145.  
  1146.     // Add a single newline at the end for readability in the dump
  1147.     return "$minified\n";
  1148. }
  1149.  
  1150. /**
  1151.  * Clean up excessive whitespace after comment removal
  1152.  *
  1153.  * @param string $content Content with comments removed
  1154.  * @return string Cleaned content with normalized line breaks
  1155.  */
  1156. function _node_dump_cleanup_whitespace($content)
  1157. {
  1158.     // Remove lines that are empty or contain only whitespace
  1159.     $lines = explode("\n", $content);
  1160.     $result = [];
  1161.     $prevEmpty = false;
  1162.  
  1163.     foreach ($lines as $line) {
  1164.         $trimmed = trim($line);
  1165.         if ($trimmed === "") {
  1166.             // Skip consecutive empty lines (keep at most one)
  1167.             if (!$prevEmpty) {
  1168.                 $result[] = "";
  1169.                 $prevEmpty = true;
  1170.             }
  1171.         } else {
  1172.             $result[] = $line;
  1173.             $prevEmpty = false;
  1174.         }
  1175.     }
  1176.  
  1177.     // Remove leading/trailing empty lines
  1178.     while (!empty($result) && trim($result[0]) === "") {
  1179.         array_shift($result);
  1180.     }
  1181.     while (!empty($result) && trim($result[count($result) - 1]) === "") {
  1182.         array_pop($result);
  1183.     }
  1184.  
  1185.     return implode("\n", $result);
  1186. }
  1187.  
  1188. function dump(string $rn): string
  1189. {
  1190.     # Prepare dump file name & save search results.
  1191.    $searchFn = h("dump.search.filename", sys_get_temp_dir() . D . "dump_search");
  1192.  
  1193.     # Open search result.
  1194.    if (is_numeric($rn) && file_exists($searchFn)) {
  1195.         $results = json_decode(f($searchFn, "read", null, false), true);
  1196.         if (is_array($results) && isset($results[$rn])) {
  1197.             return dump($results[$rn]);
  1198.         } else {
  1199.             throw new Exception("Dump did not contain {$rn} : " . var_export($results, true));
  1200.         }
  1201.     }
  1202.  
  1203.     $o = h("dump.initial.output", []);
  1204.  
  1205.     $allPhpini = array_combine(array_keys($raw = ini_get_all(null, false)), array_values($raw));
  1206.     if (isset($allPhpini[$rn])) {
  1207.         return "{$rn} = {$allPhpini[$rn]}\n";
  1208.     }
  1209.  
  1210.     if (is_file($rn)) {
  1211.         $f = h("dump.filetime.format", "Y-m-d H:i");
  1212.  
  1213.         $group = posix_getgrgid(filegroup($rn))[h("dump.file.group.key", "name")];
  1214.         $owner = posix_getpwuid(fileowner($rn))[h("dump.file.owner.key", "name")];
  1215.         $owner = $group === $owner ? $owner : "{$group}:{$owner}";
  1216.  
  1217.         $fz = filesize($rn);
  1218.         $units = ["bytes", "Kb", "Mb", "Gb", "Tb"];
  1219.         for ($i = 0; $fz >= 1024 && $i < 4; $i++) {
  1220.             $fz /= 1024;
  1221.         }
  1222.         $fz = round($fz, $i ? 2 : 0);
  1223.         $fu = $units[$i];
  1224.  
  1225.         $typeDifferent = function (string $base, string $me): string {
  1226.             $diff = false;
  1227.             $r = "";
  1228.             if (!empty($base)) {
  1229.                 $basep = explode(" ", $base);
  1230.                 foreach (explode(" ", $me) as $n => $p) {
  1231.                     if ($diff) {
  1232.                         $r .= $p;
  1233.                         continue;
  1234.                     }
  1235.                     for ($i = 0; $i < strlen($p); $i++) {
  1236.                         if ($basep[$n][$i] !== $p[$i]) {
  1237.                             $diff = true;
  1238.                             $r .= $p;
  1239.                             break;
  1240.                         }
  1241.                     }
  1242.                 }
  1243.             }
  1244.             return $r;
  1245.         };
  1246.  
  1247.         $o[] = h("dump.fileperms", substr(sprintf("%o", fileperms($rn)), -4));
  1248.         $o[] = h("dump.fileowner", $owner);
  1249.         $o[] = h("dump.filehash", md5_file($rn));
  1250.         $o[] = h("dump.filesize", $fz) . " " . h("dump.filesize.unit", $fu);
  1251.         $ctime = date($f, filectime($rn));
  1252.         $mtime = $typeDifferent($ctime, date($f, filemtime($rn)));
  1253.         $atime = $typeDifferent(date($f, filemtime($rn)), date($f, fileatime($rn)));
  1254.         if ($ctime === $mtime || empty($mtime)) {
  1255.             $o[] = h("dump.filecmtime.prefix", "c/m") . $ctime;
  1256.         } else {
  1257.             $o[] = h("dump.filectime.prefix", "c") . $ctime;
  1258.             !empty($mtime) && ($o[] = h("dump.filemtime.prefix", "m") . $mtime);
  1259.         }
  1260.         !empty($atime) && ($o[] = h("dump.fileatime.prefix", "a") . $atime);
  1261.  
  1262.         $o[] = basename($rn);
  1263.         return implode(" ", $o);
  1264.     }
  1265.  
  1266.     $allFiles = _node_gitignore(":list:all");
  1267.  
  1268.     $staticId = h("dump.class.static.accessor", "::");
  1269.     $publicId = h("dump.class.static.accessor", "->");
  1270.  
  1271.     $allFuncs = [...get_defined_functions()["user"], ...get_defined_functions()["internal"]];
  1272.  
  1273.     if (str_contains($rn, $staticId) || str_contains($rn, $publicId) || in_array($rn, $allFuncs)) {
  1274.         [$class, $method] = str_contains($rn, $staticId) ? explode($staticId, $rn, 2) : (str_contains($rn, $publicId) ? explode($publicId, $rn, 2) : [null, $rn]);
  1275.  
  1276.         $r = $class ? new ReflectionMethod($class, $method) : new ReflectionFunction($method);
  1277.  
  1278.         $params = array_map(
  1279.             fn($p) => ($p->getType() ? $p->getType() . " " : "") .
  1280.                 ($p->isPassedByReference() ? "&" : "") .
  1281.                 ($p->isVariadic() ? "..." : "") .
  1282.                 "$" .
  1283.                 $p->getName() .
  1284.                 ($p->isDefaultValueAvailable() ? " = " . var_export($p->getDefaultValue(), true) : ""),
  1285.             $r->getParameters(),
  1286.         );
  1287.  
  1288.         $o[] = $r->getName() . "(" . implode(", ", $params) . ")" . ($r->getReturnType() ? ": " . $r->getReturnType() : "");
  1289.  
  1290.         return implode("\n", $o);
  1291.     }
  1292.  
  1293.     $allClasses = get_declared_classes();
  1294.     $allInterfaces = get_declared_interfaces();
  1295.     $allTraits = get_declared_traits();
  1296.  
  1297.     if (in_array($rn, $allClasses) || in_array($rn, $allInterfaces) || in_array($rn, $allTraits) || (function_exists("enum_exists") && enum_exists($rn))) {
  1298.         $r = new ReflectionClass($rn);
  1299.  
  1300.         $kind = $r->isInterface() ? "interface " : ($r->isTrait() ? "trait " : (method_exists($r, "isEnum") && $r->isEnum() ? "enum " : "class "));
  1301.  
  1302.         $hdr =
  1303.             (!$r->isInterface() && $r->isAbstract() ? "abstract " : "") .
  1304.             ($r->isFinal() ? "final " : "") .
  1305.             (method_exists($r, "isReadOnly") && $r->isReadOnly() ? "readonly " : "") .
  1306.             $kind .
  1307.             $rn;
  1308.  
  1309.         if ($r->isInterface()) {
  1310.             if ($i = $r->getInterfaceNames()) {
  1311.                 $hdr .= " extends " . implode(", ", $i);
  1312.             }
  1313.         } else {
  1314.             if ($p = $r->getParentClass()) {
  1315.                 $hdr .= " extends " . $p->getName();
  1316.             }
  1317.             if ($i = $r->getInterfaceNames()) {
  1318.                 $hdr .= " implements " . implode(", ", $i);
  1319.             }
  1320.         }
  1321.  
  1322.         $o[] = $hdr;
  1323.  
  1324.         foreach ($r->getMethods() as $m) {
  1325.             $o[] =
  1326.                 "\t" .
  1327.                 ($m->isPublic() ? "public " : ($m->isProtected() ? "protected " : "private ")) .
  1328.                 ($m->isStatic() ? "static " : "") .
  1329.                 "function " .
  1330.                 dump($rn . ($m->isStatic() ? $staticId : $publicId) . $m->getName());
  1331.         }
  1332.  
  1333.         return implode("\n", $o);
  1334.     }
  1335.  
  1336.     $allConstants = [...get_defined_constants()];
  1337.  
  1338.     if (defined($rn)) {
  1339.         return var_export(constant($rn), true);
  1340.     }
  1341.  
  1342.     $allVars = $GLOBALS;
  1343.  
  1344.     if (isset($GLOBALS[$rn])) {
  1345.         return var_export($GLOBALS[$rn], true);
  1346.     }
  1347.  
  1348.     $allStructs = struct(":dump");
  1349.  
  1350.     foreach ($allStructs as $struct) {
  1351.         $sp = explode(" ", $struct);
  1352.         if ($struct === $rn || $sp[0] === $rn) {
  1353.             return struct(":documentation", $rn);
  1354.         }
  1355.     }
  1356.  
  1357.     $rn = strtolower($rn);
  1358.  
  1359.     # Empty dump dumps the entire project and unmatched commands acts as dump-filter.
  1360.    if ($rn === "" || $rn[0] === ":") {
  1361.         $result = _node_dump_generate_dump(strlen($rn) ? substr($rn, 1) : "");
  1362.         file_put_contents(_node_project("path") . "dump.txt", $result);
  1363.         return "dump.txt updated (dump of '$rn' with content + inventory)\n";
  1364.     }
  1365.  
  1366.     # Operations further down are not of LLM interaction but rather
  1367.    # a developer tooling.
  1368.  
  1369.     # When no match was dumped do create a query on all resources.
  1370.    $r = "Searching for '{$rn}'";
  1371.     $f = [];
  1372.     $s = [];
  1373.     $i = 0;
  1374.     foreach ($allFiles as $fn) {
  1375.         if (strpos(strtolower(basename($fn)), $rn) !== false) {
  1376.             $f[] = "[file]:{$i} " . str_replace(ROOT_PATH, "", $fn);
  1377.             $s[] = $fn;
  1378.             $i++;
  1379.         }
  1380.     }
  1381.  
  1382.     # All resources.
  1383.    $z = [
  1384.         "php.ini" => array_keys($allPhpini),
  1385.         "function" => $allFuncs,
  1386.         "class" => $allClasses,
  1387.         "interface" => $allInterfaces,
  1388.         "trait" => $allTraits,
  1389.         "constant" => array_keys($allConstants),
  1390.         "var" => array_keys($allVars),
  1391.         "structure" => $allStructs,
  1392.     ];
  1393.  
  1394.     foreach ($z as $t => $a) {
  1395.         foreach ($a as $k => $fn) {
  1396.             if (strpos(strtolower((string) $fn), $rn) !== false) {
  1397.                 $f[] = "[{$t}]:{$i} {$fn}";
  1398.                 $s[] = $fn;
  1399.                 $i++;
  1400.             }
  1401.         }
  1402.     }
  1403.  
  1404.     f($searchFn, "write", h("dump.search.results", json_encode($s)));
  1405.  
  1406.     $r .= ", found: " . count($f) . " result(s):\n";
  1407.  
  1408.     return empty($f)
  1409.         ? r("Could not dump '{$rn}'.", "Info", h("dump.undefined.message", "Undefined resource: ") . h("dump.undefined.resourcename", $rn) . "\n")
  1410.         : $r . implode("\n", $f) . "\nQuick focus: dump <n>";
  1411. }
  1412. # dump end
  1413.  
  1414. # feed begin dev
  1415. function _node_feed_backup(string $path, string $content): void
  1416. {
  1417.     $supportedFiletypes = [".php", ".js", ".css", ".html", ".md"];
  1418.     foreach ($supportedFiletypes as $ext) {
  1419.         if (substr($path, strlen($ext) * -1) === $ext) {
  1420.             $backupFn = str_replace($ext, ".backup.json", $path);
  1421.             $backupArray = file_exists($backupFn) ? json_decode(file_get_contents($backupFn), true) : [];
  1422.  
  1423.             if (empty($backupArray) || array_last($backupArray) !== $content) {
  1424.                 $backupArray[] = $content;
  1425.                 file_put_contents($backupFn, json_encode($backupArray, JSON_PRETTY_PRINT));
  1426.             }
  1427.             break;
  1428.         }
  1429.     }
  1430. }
  1431.  
  1432. /**
  1433.  * Calculate the indentation of a line (spaces or tabs)
  1434.  */
  1435. function _node_feed_get_indent(string $line): string
  1436. {
  1437.     preg_match("/^(\s+)/", $line, $matches);
  1438.     return $matches[1] ?? "";
  1439. }
  1440.  
  1441. /**
  1442.  * Apply indentation to each line of a block
  1443.  */
  1444. function _node_feed_apply_indent(string $block, string $indent): string
  1445. {
  1446.     $lines = explode("\n", $block);
  1447.     $result = [];
  1448.     foreach ($lines as $line) {
  1449.         $result[] = "$indent$line";
  1450.     }
  1451.     return implode("\n", $result);
  1452. }
  1453.  
  1454. /*
  1455.  * @return string Response from feed operation
  1456.  */
  1457. function feed(): string
  1458. {
  1459.     echo "Enter code (Ctrl+D to finish):\n";
  1460.     $input = "";
  1461.     while (($line = fgets(STDIN)) !== false) {
  1462.         $input .= $line;
  1463.     }
  1464.  
  1465.     clearstatcache();
  1466.  
  1467.     if (trim($input) === "") {
  1468.         return "No input provided. Returning.\n\n";
  1469.     }
  1470.  
  1471.     $re = '/^#{2,3}\s+([^\s]+)[^\n]*\R```[^\n]*\R(.*?)```/ms';
  1472.     preg_match_all($re, $input, $matches1, PREG_SET_ORDER);
  1473.  
  1474.     $processed = [];
  1475.     $files = [];
  1476.  
  1477.     foreach ($matches1 as $m1) {
  1478.         $path = $m1[1];
  1479.         $code = $m1[2];
  1480.  
  1481.         $files[] = $path;
  1482.  
  1483.         # Try to escape as early as possible.
  1484.        $exists = file_exists($path);
  1485.         if (!$exists && ($dir = dirname($path))) {
  1486.             # Make
  1487.            !is_dir($dir) && mkdir($dir, 0777, true);
  1488.             _node_gitignore($path, "write");
  1489.  
  1490.             # On initial creation of the file unsescape any escaped codeblocks of md notaiton.
  1491.            $processed[] = file_put_contents($path, str_replace("\`\`\`", "```", $code));
  1492.  
  1493.             continue; // jump.
  1494.         }
  1495.  
  1496.         $body = $exists ? file_get_contents($path) : "";
  1497.         $originalBody = $body; // Keep original for backup comparison
  1498.  
  1499.         # Comment-style blocks
  1500.        $reBlock = '/\/\*\s*begin\s+([^\s]+)\s*\*\/\R(.*?)\/\*\s*end\s+\1\s*\*\//ms';
  1501.         preg_match_all($reBlock, $code, $matches2, PREG_SET_ORDER);
  1502.  
  1503.         foreach ($matches2 as $m2) {
  1504.             $id = $m2[1];
  1505.             $block = $m2[2];
  1506.  
  1507.             // Find existing block to preserve its indentation
  1508.             $existingIndent = "";
  1509.             if ($exists) {
  1510.                 $pId = preg_quote($id, "/");
  1511.                 $reFind = "/^(\\s*)\\/\\*\\s*begin\\s+{$pId}\\s*\\*\\/.*?\$/m";
  1512.                 if (preg_match($reFind, $body, $matches)) {
  1513.                     $existingIndent = $matches[1] ?? "";
  1514.                 }
  1515.             }
  1516.  
  1517.             // Apply the found indentation to the block
  1518.             if (!empty($existingIndent)) {
  1519.                 $block = _node_feed_apply_indent($block, $existingIndent);
  1520.             }
  1521.  
  1522.             if ($exists) {
  1523.                 $pId = preg_quote($id, "/");
  1524.                 $reBlock = "/\/\*\s*begin\s+{$pId}\s*\*\/\R.*?\/\*\s*end\s+{$pId}\s*\*\//ms";
  1525.                 if (preg_match($reBlock, $body)) {
  1526.                     $body = preg_replace($reBlock, "/* begin $id */\n$block\n/* end $id */", $body);
  1527.                 } else {
  1528.                     $body .= "\n/* begin $id */\n$block\n/* end $id */\n";
  1529.                 }
  1530.             } else {
  1531.                 $body .= "/* begin $id */\n$block\n/* end $id */\n";
  1532.             }
  1533.         }
  1534.  
  1535.         # HTML-style blocks - similar indentation preservation
  1536.        $reHtml = '/<([a-z][a-z0-9-]*)[^>]*data-section="([^"]+)"[^>]*>(.*?)<\/\1>/ms';
  1537.         preg_match_all($reHtml, $code, $matchesHtml, PREG_SET_ORDER);
  1538.  
  1539.         foreach ($matchesHtml as $mHtml) {
  1540.             $tag = $mHtml[1];
  1541.             $id = $mHtml[2];
  1542.             $block = $mHtml[3];
  1543.  
  1544.             // Find existing HTML block to preserve its indentation
  1545.             $existingIndent = "";
  1546.             if ($exists) {
  1547.                 $pId = preg_quote($id, "/");
  1548.                 $reFind = "/^(\\s*)<{$tag}[^>]*data-section=\"{$pId}\"[^>]*>.*?\$/m";
  1549.                 if (preg_match($reFind, $body, $matches)) {
  1550.                     $existingIndent = $matches[1] ?? "";
  1551.                 }
  1552.             }
  1553.  
  1554.             // Apply the found indentation to each line of the block
  1555.             if (!empty($existingIndent)) {
  1556.                 $blockLines = explode("\n", $block);
  1557.                 $block = implode("\n", array_map(fn($line) => "$existingIndent$line", $blockLines));
  1558.             }
  1559.  
  1560.             if ($exists) {
  1561.                 $reBlock = "/<{$tag}" . '[^>]*data-section="' . preg_quote($id, "/") . '"[^>]*>.*?<\/' . "{$tag}>/ms";
  1562.                 if (preg_match($reBlock, $body)) {
  1563.                     $body = preg_replace($reBlock, "<$tag data-section=\"$id\">\n$block\n</$tag>", $body);
  1564.                 } else {
  1565.                     $body .= "\n<$tag data-section=\"$id\">\n$block\n</$tag>\n";
  1566.                 }
  1567.             } else {
  1568.                 $body .= "<$tag data-section=\"$id\">\n$block\n</$tag>\n";
  1569.             }
  1570.         }
  1571.  
  1572.         if (empty($matches2) && empty($matchesHtml)) {
  1573.             $body .= $code;
  1574.         }
  1575.  
  1576.         if ($body !== "" && $body !== $originalBody) {
  1577.             file_exists($path) && _node_feed_backup($path, $originalBody);
  1578.             // Create path recursively if it does not exist
  1579.             $dir = dirname($path);
  1580.             !is_dir($dir) && mkdir($dir, 0777, true);
  1581.             _node_gitignore($path, "write");
  1582.             $processed[] = file_put_contents($path, $body);
  1583.         }
  1584.     }
  1585.  
  1586.     if (empty($processed)) {
  1587.         return "No changes applied (all files [" . implode(", ", $files) . "] already up to date).\n\n";
  1588.     }
  1589.  
  1590.     return "Feed processed: " . implode(", ", $processed) . "\n\n";
  1591. }
  1592. # feed end
  1593.  
  1594. # wrap begin dev
  1595. function wrap(?string $rn = null, ?string $env = null): array
  1596. {
  1597.     $rn ??= h("wrap.resourcename.fallback", ROOT_PATH . $_SERVER["SCRIPT_FILENAME"] ?? __FILE__);
  1598.     $rp = explode(" ", $rn);
  1599.     $rn = h("wrap.resourcename", $rp[0]);
  1600.  
  1601.     if ($ls = file($rn, FILE_IGNORE_NEW_LINES)) {
  1602.         $files = h("wrap.initial.files", []);
  1603.         $main = []; // target lines
  1604.         $skip = 0;
  1605.         $env = h("wrap.env", empty($env) ? implode(" ", array_slice($rp, 1)) : $env);
  1606.         $ext = h("wrap.files.ext", "php");
  1607.  
  1608.         $fn = []; // file names
  1609.         $fi = -1; // file index
  1610.  
  1611.         $t = []; // tab depth counts
  1612.         foreach ($ls as $l) {
  1613.             $lp = h("wrap.lineparts", explode(" ", trim($l))); // line part
  1614.             $imarkers = h("wrap.include.markers", ["include", $lp[1] ?? null]);
  1615.             if (count($lp) === 3 && rtrim($lp[2], ";") === h("wrap.marker.end", "end")) {
  1616.                 if ($skip) {
  1617.                     $skip--;
  1618.                     continue;
  1619.                 }
  1620.                 $if = h("wrap.includefile.name", ROOT_PATH . NAME . ".{$lp[1]}" . ($env ? ".{$env}" : "") . ".{$ext}");
  1621.                 if (!array_filter($imarkers, fn(string $n): bool => !str_contains($files[$fn[$fi]][1], $n))) {
  1622.                     if (file_exists($if)) {
  1623.                         $file = h("wrap.includefile.lines", array_map(fn($x) => str_repeat("\t", $t[$fn[$fi]]) . $x, array_slice(wrap($if, $env), 2)));
  1624.                         $main = [...$main, ...$file];
  1625.                         unlink($if);
  1626.                     }
  1627.                     $files[$fn[$fi]] = null;
  1628.                 } else {
  1629.                     $main[] = h("wrap.include.operation", "include_once '{$if}';");
  1630.                 }
  1631.                 $main[] = $l;
  1632.  
  1633.                 $fi--;
  1634.                 array_pop($fn);
  1635.             } elseif (count($lp) >= 4 && rtrim($lp[2], ":") === h("wrap.marker.begin", "begin")) {
  1636.                 if ($env && !in_array($env, array_slice($lp, 3))) {
  1637.                     $skip++;
  1638.                     continue;
  1639.                 }
  1640.                 $main[] = $l;
  1641.  
  1642.                 $fn[] = $lp[1];
  1643.                 $fi++;
  1644.                 $files[$fn[$fi]] = ["{$ls[0]}\n"]; // slice 2
  1645.  
  1646.                 $t[$fn[$fi]] = strspn($l, "\t");
  1647.             } elseif ($fi >= 0) {
  1648.                 if ($skip) {
  1649.                     continue;
  1650.                 }
  1651.                 $files[$fn[$fi]][] = substr($l, min($t[$fn[$fi]], strspn($l, "\t")));
  1652.             } else {
  1653.                 if ($skip) {
  1654.                     continue;
  1655.                 }
  1656.                 $main[] = $l;
  1657.             }
  1658.         }
  1659.  
  1660.         foreach ($files as $fn => $ls) {
  1661.             if (is_array($ls)) {
  1662.                 $fn = h("wrap.wrapfile.name", ROOT_PATH . NAME . ".{$fn}" . ($env ? ".{$env}" : "") . ".{$ext}");
  1663.                 if (!file_exists($fn)) {
  1664.                     f($fn, "write", implode("\n", h("wrap.wrapfile.lines", $ls)));
  1665.                 }
  1666.             }
  1667.         }
  1668.         if ($env) {
  1669.             $info = pathinfo($rn);
  1670.             $name = h("wrap.envfile.name", $info["filename"]);
  1671.  
  1672.             # Get envfile extenson or fallback to mainfile extension.
  1673.            $ext = h("wrap.envfile.ext", $info["extension"] ?: $ext);
  1674.  
  1675.             # Update resourcename.
  1676.            $rn = (str_ends_with($name, ".{$env}") ? $name : "{$name}.{$env}") . ".{$ext}";
  1677.         }
  1678.  
  1679.         # Hook berfore applying main file lines.
  1680.        $main = h("wrap.mainfile.lines", $main);
  1681.  
  1682.         return f(h("wrap.mainfile.name", $rn), "write", implode("\n", $main)) ? $main : [];
  1683.     }
  1684.  
  1685.     return r("There was nothing to wrap.", "Info", []);
  1686. }
  1687. # wrap end
  1688.  
  1689. # lint begin dev
  1690. function lint(string $code): array
  1691. {
  1692.     $fn = h("lint.filename", tempnam(sys_get_temp_dir(), "lint_"));
  1693.     f($fn, "write", h("lint.code", str_starts_with($code, "<?") ? $code : "<?php {$code}"));
  1694.  
  1695.     $o = shell_exec("php -l $fn 2>&1");
  1696.     unlink($fn);
  1697.  
  1698.     if (str_starts_with(trim($o), h("lint.noerror", "No syntax errors detected"))) {
  1699.         return [];
  1700.     }
  1701.  
  1702.     return r("Linting errors.", "Info", h("lint.errors", [trim($o)]));
  1703. }
  1704. # lint end
  1705.  
  1706. # struct begin dev
  1707. function _node_argex(array $args, int $n, ?int $len = null): string
  1708. {
  1709.     return !$n || empty($args[$n]) ? implode(" ", array_slice(explode(" ", $args[0]), $n, $len)) : $args[$n];
  1710. }
  1711.  
  1712. function _node_spath(string $structure): ?string
  1713. {
  1714.     $o = array_key_exists($structure, struct(":keys")) ? $structure : struct(":structure:path", $structure);
  1715.     return is_int($o) && $o > 0 ? null : $o;
  1716. }
  1717.  
  1718. function _node_spex(string $structure): array
  1719. {
  1720.     $structKeys = struct(":keys");
  1721.     $structs = struct(":structs");
  1722.  
  1723.     return [($path = _node_spath($structure)) === $structure ? explode(" ", str_replace(["<", ">"], "", $structs[array_search($path, array_keys($structKeys))]))[1] : $structure, $path];
  1724. }
  1725.  
  1726. /**
  1727.  * Loads the flat keys array from a nested structure definition array.
  1728.  * Identical traversal logic to the one inside struct() — extracted so both
  1729.  * the built-in definition and the dynamic JSON can be flattened the same way.
  1730.  *
  1731.  * @param array $node  Nested structure definition (same format as $struct).
  1732.  * @param array $key   Accumulator for the current path segments (recursive).
  1733.  * @return array       Flat ["Path/To/Leaf" => ["class", ...]] map.
  1734.  */
  1735. function _node_struct_flatten(array $node, array $key = []): array
  1736. {
  1737.     $keys = [];
  1738.     foreach ($node as $name => $sub) {
  1739.         $nkey = [...$key, $name];
  1740.         if (!array_is_list($sub)) {
  1741.             $keys = [...$keys, ..._node_struct_flatten($sub, $nkey)];
  1742.         } else {
  1743.             $keys[implode(D, $nkey)] = $sub;
  1744.         }
  1745.     }
  1746.     return $keys;
  1747. }
  1748.  
  1749. /**
  1750.  * Loads structure.json from $projectPath and returns a flat keys array
  1751.  * in exactly the same format struct(":keys") returns for the built-in tree.
  1752.  *
  1753.  * structure.json mirrors the PHP nested array format:
  1754.  *   { "Views": { "Pages": ["class"], "Layouts": ["class"] }, "Modules": ["class"] }
  1755.  *
  1756.  * Returns [] when the file is absent or malformed — never throws.
  1757.  *
  1758.  * @param string $projectPath  Absolute path to the project root (with trailing D).
  1759.  * @return array               Flat ["Path/To/Leaf" => ["type", ...]] map.
  1760.  */
  1761. function _node_struct_load_dynamic(string $projectPath): array
  1762. {
  1763.     $file = rtrim($projectPath, D) . D . "structure.json";
  1764.     if (!file_exists($file)) {
  1765.         return [];
  1766.     }
  1767.     $raw = @file_get_contents($file);
  1768.     if ($raw === false || trim($raw) === "") {
  1769.         return [];
  1770.     }
  1771.     $decoded = json_decode($raw, true);
  1772.     if (!is_array($decoded)) {
  1773.         return [];
  1774.     }
  1775.     return _node_struct_flatten($decoded);
  1776. }
  1777.  
  1778. /**
  1779.  * Merges a flat ["Path/To/Leaf" => ["type"]] map into the structure.json
  1780.  * at $projectPath. Creates the file if absent. Always pretty-prints.
  1781.  * Existing entries are preserved; new entries are added. No removals.
  1782.  *
  1783.  * @param string $projectPath   Absolute path to the project root (with trailing D).
  1784.  * @param array  $newEntries    Flat keys map to merge in.
  1785.  * @return bool                 True on success.
  1786.  */
  1787. function _node_struct_save_dynamic(string $projectPath, array $newEntries): bool
  1788. {
  1789.     $file = rtrim($projectPath, D) . D . "structure.json";
  1790.  
  1791.     # Load existing nested tree (not the flat map).
  1792.    $existing = [];
  1793.     if (file_exists($file)) {
  1794.         $raw = @file_get_contents($file);
  1795.         if ($raw !== false && trim($raw) !== "") {
  1796.             $decoded = json_decode($raw, true);
  1797.             if (is_array($decoded)) {
  1798.                 $existing = $decoded;
  1799.             }
  1800.         }
  1801.     }
  1802.  
  1803.     # Merge each new flat key back into the nested tree.
  1804.    foreach ($newEntries as $flatPath => $types) {
  1805.         $segments = explode(D, $flatPath);
  1806.         $node = &$existing;
  1807.         foreach ($segments as $i => $seg) {
  1808.             if ($i === count($segments) - 1) {
  1809.                 # Leaf: merge types, preserve existing.
  1810.                $node[$seg] = array_values(array_unique(array_merge($node[$seg] ?? [], $types)));
  1811.             } else {
  1812.                 # Intermediate node: ensure it's an associative array.
  1813.                if (!isset($node[$seg]) || array_is_list($node[$seg] ?? [])) {
  1814.                     $node[$seg] = [];
  1815.                 }
  1816.                 $node = &$node[$seg];
  1817.             }
  1818.         }
  1819.         unset($node);
  1820.     }
  1821.  
  1822.     return (bool) file_put_contents($file, json_encode($existing, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
  1823. }
  1824.  
  1825. function struct(mixed ...$args): mixed
  1826. {
  1827.     if ($args[0] === ":declarations") {
  1828.         return ["class", "interface", "trait", "enum", "function"];
  1829.     }
  1830.  
  1831.     /*
  1832.     |--------------------------------------------------------------------------
  1833.     | NodePHP — Monolithic Structure Definition
  1834.     |--------------------------------------------------------------------------
  1835.     |
  1836.     | Drop-in replacement for the `static $struct` inside struct().
  1837.     |
  1838.     | Design axioms:
  1839.     |   1.  Every layer is orthogonal — no concept lives in two places.
  1840.     |   2.  Names are nouns, never verbs (Gateway not "GetUser").
  1841.     |   3.  File-extension leaves co-exist with class leaves at the same depth
  1842.     |       only when that folder genuinely holds both (e.g. Template views).
  1843.     |   4.  Depth never exceeds 5 segments — readability collapses beyond that.
  1844.     |   5.  "Escape hatches" (Custom, Misc) are intentionally absent;
  1845.     |       every artefact belongs to an explicit location.
  1846.     |   6.  Covers: monolith, API-first, CMS, e-commerce, SaaS, multi-tenant,
  1847.     |       event-driven, CLI-heavy, media-heavy, and micro-kernel apps.
  1848.     |
  1849.     | Layer overview
  1850.     | ──────────────
  1851.     |   Ai            — prompt engineering, RAG, agents, embeddings, semantic cache
  1852.     |   Config        — all configuration, environment, feature-flags
  1853.     |   App           — bootstrap, lifecycle, scheduling, events, localisation
  1854.     |   Domain        — pure business: models, logic, events, commands, queries
  1855.     |   Data          — persistence, caching, search, structure/transfer objects
  1856.     |   Api           — REST, GraphQL, RPC, Webhook — first-class citizens
  1857.     |   Compliance    — audit trail, privacy, legal, secrets management
  1858.     |   Import        — bulk ingestion, field mapping, execution, rollback
  1859.     |   Presentation  — Web UI, CLI UI, assets, templates, mail views
  1860.     |   Job           — background work: queues, workers, tasks, pipelines
  1861.     |   Notification  — every outbound channel (email, SMS, push, webhook fan-out)
  1862.     |   Auth          — authentication and authorisation as a domain
  1863.     |   Media         — upload, processing, storage, streaming of binary assets
  1864.     |   Report        — analytics, exports, aggregations, scheduled reports
  1865.     |   Integration   — third-party SDKs, payment gateways, external adapters
  1866.     |   Infrastructure — cross-cutting: messaging bus, file system, crypto, observability
  1867.     |   System        — DI container, extension points, utilities, meta-programming
  1868.     |   Quality       — tests, docs, translations, benchmarks, static analysis
  1869.     */
  1870.  
  1871.     static $struct = h(
  1872.         "struct.definiton",
  1873.         [
  1874.             "Ai" => [
  1875.                 "Prompt" => [
  1876.                     "Template" => ["class"],
  1877.                     "Registry" => ["class", "interface"],
  1878.                     "Compiler" => ["class", "interface"],
  1879.                     "Versioner" => ["class", "interface"],
  1880.                     "Chain" => ["class", "interface"],
  1881.                 ],
  1882.                 "Rag" => [
  1883.                     "Retriever" => ["class", "interface"],
  1884.                     "Reranker" => ["class", "interface"],
  1885.                     "Augmenter" => ["class", "interface"],
  1886.                     "Pipeline" => ["class", "interface"],
  1887.                 ],
  1888.                 "Embedding" => [
  1889.                     "Generator" => ["class", "interface"],
  1890.                     "Embedding" => ["class"],
  1891.                     "Distance" => ["class", "interface"],
  1892.                     "Normalizer" => ["class", "interface"],
  1893.                 ],
  1894.                 "Agent" => [
  1895.                     "Agent" => ["class", "interface"],
  1896.                     "Tool" => ["class", "interface"],
  1897.                     "Planner" => ["class", "interface"],
  1898.                     "Memory" => ["class", "interface"],
  1899.                     "Executor" => ["class", "interface"],
  1900.                     "Registry" => ["class", "interface"],
  1901.                 ],
  1902.                 "Cache" => [
  1903.                     "Store" => ["class", "interface"],
  1904.                     "Hasher" => ["class", "interface"],
  1905.                     "Threshold" => ["class"],
  1906.                 ],
  1907.                 "Output" => [
  1908.                     "Parser" => ["class", "interface"],
  1909.                     "Validator" => ["class", "interface"],
  1910.                     "Extractor" => ["class", "interface"],
  1911.                     "Guardrail" => ["class", "interface"],
  1912.                 ],
  1913.             ],
  1914.             "Config" => [
  1915.                 "App" => [".php", ".env", ".ini"],
  1916.                 "Database" => [".php", ".env"],
  1917.                 "Cache" => [".php"],
  1918.                 "Queue" => [".php"],
  1919.                 "Mail" => [".php"],
  1920.                 "Filesystem" => [".php"],
  1921.                 "Auth" => [".php"],
  1922.                 "Api" => [".php"],
  1923.                 "Logging" => [".php"],
  1924.                 "Search" => [".php"],
  1925.                 "Payment" => [".php"],
  1926.                 "Integration" => [".php"],
  1927.                 "Services" => [".php"],
  1928.                 "Environment" => [
  1929.                     "Loader" => ["class", "interface"],
  1930.                     "Detector" => ["class", "interface"],
  1931.                     "Resolver" => ["class", "interface"],
  1932.                 ],
  1933.                 "Feature" => [
  1934.                     "Flag" => ["class"],
  1935.                     "Registry" => ["class", "interface"],
  1936.                     "Evaluator" => ["class", "interface"],
  1937.                 ],
  1938.                 "Setting" => [
  1939.                     "Repository" => ["class", "interface"],
  1940.                     "Cache" => ["class", "interface"],
  1941.                     "Mutator" => ["class", "interface"],
  1942.                 ],
  1943.             ],
  1944.             "App" => [
  1945.                 "Kernel" => [
  1946.                     "Http" => ["class"],
  1947.                     "Console" => ["class"],
  1948.                     "Worker" => ["class"],
  1949.                     "Test" => ["class"],
  1950.                 ],
  1951.                 "Bootstrap" => [
  1952.                     "Bootstrapper" => ["class", "interface"],
  1953.                     "Provider" => ["class"],
  1954.                     "Registrar" => ["class", "interface"],
  1955.                     "Bootloader" => ["class"],
  1956.                 ],
  1957.                 "Schedule" => [
  1958.                     "Schedule" => ["class"],
  1959.                     "Expression" => ["class"],
  1960.                     "Runner" => ["class", "interface"],
  1961.                 ],
  1962.                 "Routes" => [
  1963.                     "Web" => [".php"],
  1964.                     "Api" => [".php"],
  1965.                     "Console" => [".php"],
  1966.                     "Channel" => [".php"],
  1967.                 ],
  1968.                 "Console" => [
  1969.                     "Command" => ["class"],
  1970.                     "Argument" => ["class"],
  1971.                     "Option" => ["class"],
  1972.                     "Signature" => ["class"],
  1973.                 ],
  1974.                 "Event" => [
  1975.                     "Dispatcher" => ["class", "interface"],
  1976.                     "Listener" => ["class", "interface"],
  1977.                     "Subscriber" => ["class", "interface"],
  1978.                     "Domain" => ["class"],
  1979.                     "Application" => ["class"],
  1980.                     "Integration" => ["class"],
  1981.                     "System" => ["class"],
  1982.                 ],
  1983.                 "Locale" => [
  1984.                     "Translator" => ["class", "interface"],
  1985.                     "Loader" => ["class", "interface"],
  1986.                     "Detector" => ["class", "interface"],
  1987.                     "Catalog" => ["class", "interface"],
  1988.                     "Pluralizer" => ["class", "interface"],
  1989.                     "Formatter" => ["class", "interface"],
  1990.                     "Bundle" => [".po", ".mo", ".json", ".yaml"],
  1991.                 ],
  1992.                 "Middleware" => [
  1993.                     "Stack" => ["class", "interface"],
  1994.                     "Middleware" => ["class", "interface"],
  1995.                     "Pipeline" => ["class", "interface"],
  1996.                 ],
  1997.                 "Tenant" => [
  1998.                     "Resolver" => ["class", "interface"],
  1999.                     "Context" => ["class"],
  2000.                     "Scope" => ["class", "interface"],
  2001.                     "Identifier" => ["class"],
  2002.                 ],
  2003.             ],
  2004.             "Domain" => [
  2005.                 "Model" => [
  2006.                     "Aggregate" => ["class"],
  2007.                     "Entity" => ["class"],
  2008.                     "ValueObject" => ["class"],
  2009.                     "Relationship" => ["class"],
  2010.                     "Identity" => ["class"],
  2011.                     "Collection" => ["class"],
  2012.                 ],
  2013.                 "Logic" => [
  2014.                     "Service" => ["class", "interface"],
  2015.                     "Policy" => ["class", "interface"],
  2016.                     "Rule" => ["class", "interface"],
  2017.                     "Specification" => ["class", "interface"],
  2018.                     "Strategy" => ["class", "interface"],
  2019.                     "Calculator" => ["class", "interface"],
  2020.                     "Workflow" => ["class", "interface"],
  2021.                     "Saga" => ["class", "interface"],
  2022.                 ],
  2023.                 "Event" => [
  2024.                     "Event" => ["class"],
  2025.                     "Handler" => ["class"],
  2026.                     "Listener" => ["class", "interface"],
  2027.                     "Subscriber" => ["class", "interface"],
  2028.                 ],
  2029.                 "Command" => [
  2030.                     "Command" => ["class"],
  2031.                     "Handler" => ["class"],
  2032.                     "Validator" => ["class", "interface"],
  2033.                     "Bus" => ["class", "interface"],
  2034.                     "Middleware" => ["class", "interface"],
  2035.                 ],
  2036.                 "Query" => [
  2037.                     "Query" => ["class"],
  2038.                     "Handler" => ["class"],
  2039.                     "Bus" => ["class", "interface"],
  2040.                     "Result" => ["class"],
  2041.                 ],
  2042.                 "Repository" => [
  2043.                     "Repository" => ["interface"],
  2044.                     "Criteria" => ["class"],
  2045.                     "Filter" => ["class", "interface"],
  2046.                     "Sorter" => ["class", "interface"],
  2047.                 ],
  2048.                 "Exception" => [
  2049.                     "DomainException" => ["class"],
  2050.                     "ValidationException" => ["class"],
  2051.                     "NotFoundException" => ["class"],
  2052.                     "ConflictException" => ["class"],
  2053.                     "AuthorizationException" => ["class"],
  2054.                 ],
  2055.                 "Orchestration" => [
  2056.                     "Service" => ["class", "interface"],
  2057.                     "Assembler" => ["class", "interface"],
  2058.                     "Facade" => ["class"],
  2059.                     "UseCase" => ["class", "interface"],
  2060.                 ],
  2061.                 "Factory" => [
  2062.                     "Factory" => ["class", "interface"],
  2063.                     "Rebuilder" => ["class", "interface"],
  2064.                 ],
  2065.                 "EventSourcing" => [
  2066.                     "EventStore" => ["class", "interface"],
  2067.                     "Snapshot" => ["class"],
  2068.                     "Projection" => ["class", "interface"],
  2069.                     "Reconstructor" => ["class", "interface"],
  2070.                     "Upcaster" => ["class", "interface"],
  2071.                 ],
  2072.                 "Shared" => [
  2073.                     "ValueObject" => ["class"],
  2074.                     "Enum" => ["enum"],
  2075.                     "Specification" => ["class", "interface"],
  2076.                 ],
  2077.             ],
  2078.             "Data" => [
  2079.                 "Persistence" => [
  2080.                     "Access" => [
  2081.                         "Repository" => ["class"],
  2082.                         "Gateway" => ["class", "interface"],
  2083.                         "DAO" => ["class", "interface"],
  2084.                         "Finder" => ["class", "interface"],
  2085.                         "Collector" => ["class", "interface"],
  2086.                         "Lock" => ["class", "interface"],
  2087.                     ],
  2088.                     "UnitOfWork" => [
  2089.                         "UnitOfWork" => ["class", "interface"],
  2090.                         "Transaction" => ["class", "interface"],
  2091.                         "Committer" => ["class", "interface"],
  2092.                         "Rollback" => ["class", "interface"],
  2093.                     ],
  2094.                     "IdentityMap" => [
  2095.                         "InstanceMap" => ["class", "interface"],
  2096.                         "Registry" => ["class", "interface"],
  2097.                     ],
  2098.                     "Database" => [
  2099.                         "Connection" => ["class", "interface"],
  2100.                         "Factory" => ["class", "trait"],
  2101.                         "Manager" => ["class", "interface"],
  2102.                         "Schema" => [
  2103.                             "Definition" => ["class"],
  2104.                             "Blueprint" => ["class"],
  2105.                             "Fixture" => ["class"],
  2106.                             "Seed" => ["class"],
  2107.                             "Migration" => [
  2108.                                 "Programmatic" => ["class"],
  2109.                                 "Raw" => ["class"],
  2110.                             ],
  2111.                         ],
  2112.                         "Logic" => [
  2113.                             "Procedure" => ["class"],
  2114.                             "Trigger" => ["class"],
  2115.                             "View" => ["class"],
  2116.                             "Constraint" => ["class"],
  2117.                             "Function" => ["class"],
  2118.                         ],
  2119.                         "Storage" => [
  2120.                             "Flat" => [
  2121.                                 "JSON" => [".json"],
  2122.                                 "CSV" => [".csv"],
  2123.                                 "YAML" => [".yaml", ".yml"],
  2124.                                 "Serialized" => [".ser", ".phpser"],
  2125.                                 "MessagePack" => [".msgpack"],
  2126.                             ],
  2127.                             "Document" => [
  2128.                                 "Collection" => ["class", "interface"],
  2129.                                 "Query" => ["class", "interface"],
  2130.                                 "Index" => ["class", "interface"],
  2131.                             ],
  2132.                             "KeyValue" => [
  2133.                                 "Store" => ["class", "interface"],
  2134.                                 "Bucket" => ["class", "interface"],
  2135.                             ],
  2136.                             "TimeSeries" => [
  2137.                                 "Writer" => ["class", "interface"],
  2138.                                 "Reader" => ["class", "interface"],
  2139.                             ],
  2140.                         ],
  2141.                     ],
  2142.                     "Cache" => [
  2143.                         "Store" => ["class", "interface"],
  2144.                         "Strategy" => ["class", "interface"],
  2145.                         "Invalidator" => ["class", "interface"],
  2146.                         "Tagger" => ["class", "interface"],
  2147.                         "Warmer" => ["class", "interface"],
  2148.                         "Decorator" => ["class", "interface"],
  2149.                     ],
  2150.                     "Outbox" => [
  2151.                         "Message" => ["class"],
  2152.                         "Store" => ["class", "interface"],
  2153.                         "Publisher" => ["class", "interface"],
  2154.                         "Relay" => ["class", "interface"],
  2155.                     ],
  2156.                 ],
  2157.                 "Search" => [
  2158.                     "FullText" => [
  2159.                         "Engine" => ["class", "interface"],
  2160.                         "Indexer" => ["class", "interface"],
  2161.                         "Searcher" => ["class", "interface"],
  2162.                         "Query" => ["class", "interface"],
  2163.                         "Result" => ["class"],
  2164.                         "Highlight" => ["class", "interface"],
  2165.                         "Facet" => ["class", "interface"],
  2166.                         "Suggest" => ["class", "interface"],
  2167.                     ],
  2168.                     "Vector" => [
  2169.                         "Store" => ["class", "interface"],
  2170.                         "Indexer" => ["class", "interface"],
  2171.                         "Retriever" => ["class", "interface"],
  2172.                         "Query" => ["class", "interface"],
  2173.                     ],
  2174.                     "Index" => ["class", "interface"],
  2175.                     "Pipeline" => ["class", "interface"],
  2176.                 ],
  2177.                 "Structure" => [
  2178.                     "Transfer" => [
  2179.                         "DTO" => ["class"],
  2180.                         "Payload" => ["class"],
  2181.                         "Resource" => ["class"],
  2182.                         "Form" => ["class"],
  2183.                         "Request" => ["class"],
  2184.                         "Response" => ["class"],
  2185.                         "Cursor" => ["class"],
  2186.                         "Page" => ["class"],
  2187.                     ],
  2188.                     "Enum" => [
  2189.                         "ActionType" => ["enum"],
  2190.                         "HttpMethod" => ["enum"],
  2191.                         "OperationMode" => ["enum"],
  2192.                         "PermissionLevel" => ["enum"],
  2193.                         "PolicyType" => ["enum"],
  2194.                         "UserRole" => ["enum"],
  2195.                         "EntityState" => ["enum"],
  2196.                         "OperationStatus" => ["enum"],
  2197.                         "DataType" => ["enum"],
  2198.                         "SortDirection" => ["enum"],
  2199.                         "Visibility" => ["enum"],
  2200.                         "Priority" => ["enum"],
  2201.                         "Channel" => ["enum"],
  2202.                     ],
  2203.                     "Definition" => [
  2204.                         "Attribute" => ["class"],
  2205.                         "Annotation" => ["class"],
  2206.                         "Metadata" => ["class"],
  2207.                         "Contract" => ["interface"],
  2208.                         "Specification" => ["class", "interface"],
  2209.                         "Schema" => ["class"],
  2210.                         "Type" => ["class"],
  2211.                     ],
  2212.                 ],
  2213.                 "Processing" => [
  2214.                     "Manipulation" => [
  2215.                         "Mapper" => ["class", "interface"],
  2216.                         "Transformer" => ["class", "interface"],
  2217.                         "Hydrator" => ["class", "interface"],
  2218.                         "Normalizer" => ["class", "interface"],
  2219.                         "Serializer" => ["class", "interface"],
  2220.                         "Deserializer" => ["class", "interface"],
  2221.                         "Caster" => ["class", "interface"],
  2222.                         "Reducer" => ["class", "interface"],
  2223.                     ],
  2224.                     "Validation" => [
  2225.                         "Validator" => ["class", "interface"],
  2226.                         "Rule" => ["class", "interface"],
  2227.                         "Constraint" => ["class"],
  2228.                         "Sanitizer" => ["class", "function"],
  2229.                         "Checker" => ["class", "interface"],
  2230.                         "Inspector" => ["class", "interface"],
  2231.                         "Assertion" => ["class", "interface"],
  2232.                     ],
  2233.                     "Query" => [
  2234.                         "Builder" => ["class", "interface"],
  2235.                         "Criteria" => ["class"],
  2236.                         "Filter" => ["class", "interface"],
  2237.                         "Specification" => ["class", "interface"],
  2238.                         "Selector" => ["class", "interface"],
  2239.                         "Scope" => ["class", "interface"],
  2240.                         "Paginator" => ["class", "interface"],
  2241.                         "Sorter" => ["class", "interface"],
  2242.                     ],
  2243.                 ],
  2244.             ],
  2245.             "Api" => [
  2246.                 "Rest" => [
  2247.                     "Controller" => ["class"],
  2248.                     "Action" => ["class"],
  2249.                     "Resource" => ["class"],
  2250.                     "Collection" => ["class"],
  2251.                     "Request" => ["class"],
  2252.                     "Response" => ["class"],
  2253.                     "Router" => ["class", "interface"],
  2254.                     "Middleware" => ["class", "interface"],
  2255.                     "Filter" => ["class", "interface"],
  2256.                     "Versioner" => ["class", "interface"],
  2257.                 ],
  2258.                 "GraphQL" => [
  2259.                     "Schema" => ["class"],
  2260.                     "Query" => ["class"],
  2261.                     "Mutation" => ["class"],
  2262.                     "Subscription" => ["class"],
  2263.                     "Type" => ["class"],
  2264.                     "Resolver" => ["class", "interface"],
  2265.                     "Directive" => ["class", "interface"],
  2266.                     "Middleware" => ["class", "interface"],
  2267.                     "Loader" => ["class", "interface"],
  2268.                 ],
  2269.                 "Rpc" => [
  2270.                     "Service" => ["class", "interface"],
  2271.                     "Procedure" => ["class"],
  2272.                     "Request" => ["class"],
  2273.                     "Response" => ["class"],
  2274.                     "Middleware" => ["class", "interface"],
  2275.                     "Stub" => ["class"],
  2276.                 ],
  2277.                 "Webhook" => [
  2278.                     "Receiver" => ["class", "interface"],
  2279.                     "Verifier" => ["class", "interface"],
  2280.                     "Parser" => ["class", "interface"],
  2281.                     "Handler" => ["class"],
  2282.                     "Event" => ["class"],
  2283.                     "Router" => ["class", "interface"],
  2284.                 ],
  2285.                 "Shared" => [
  2286.                     "Formatter" => ["class", "interface"],
  2287.                     "Transformer" => ["class", "interface"],
  2288.                     "ErrorHandler" => ["class", "interface"],
  2289.                     "Negotiator" => ["class", "interface"],
  2290.                     "Throttle" => ["class", "interface"],
  2291.                     "Versioner" => ["class", "interface"],
  2292.                     "Authenticator" => ["class", "interface"],
  2293.                 ],
  2294.                 "Idempotency" => [
  2295.                     "Key" => ["class"],
  2296.                     "Store" => ["class", "interface"],
  2297.                     "Middleware" => ["class"],
  2298.                     "ConflictHandler" => ["class", "interface"],
  2299.                 ],
  2300.             ],
  2301.             "Compliance" => [
  2302.                 "Audit" => [
  2303.                     "Trail" => ["class", "interface"],
  2304.                     "Recorder" => ["class", "interface"],
  2305.                     "Entry" => ["class"],
  2306.                     "Store" => ["class", "interface"],
  2307.                     "Query" => ["class", "interface"],
  2308.                     "Exporter" => ["class", "interface"],
  2309.                     "Redactor" => ["class", "interface"],
  2310.                 ],
  2311.                 "Privacy" => [
  2312.                     "ConsentManager" => ["class", "interface"],
  2313.                     "ConsentRecord" => ["class"],
  2314.                     "DataSubject" => ["class", "interface"],
  2315.                     "ErasureHandler" => ["class", "interface"],
  2316.                     "Anonymizer" => ["class", "interface"],
  2317.                     "Pseudonymizer" => ["class", "interface"],
  2318.                     "RetentionPolicy" => ["class", "interface"],
  2319.                     "DataInventory" => ["class", "interface"],
  2320.                 ],
  2321.                 "Legal" => [
  2322.                     "Document" => ["class"],
  2323.                     "Repository" => ["class", "interface"],
  2324.                     "Acceptance" => ["class"],
  2325.                     "Enforcer" => ["class", "interface"],
  2326.                 ],
  2327.                 "Secrets" => [
  2328.                     "Manager" => ["class", "interface"],
  2329.                     "Resolver" => ["class", "interface"],
  2330.                     "Rotator" => ["class", "interface"],
  2331.                     "Auditor" => ["class", "interface"],
  2332.                 ],
  2333.             ],
  2334.             "Import" => [
  2335.                 "Ingestion" => [
  2336.                     "Reader" => ["class", "interface"],
  2337.                     "Parser" => ["class", "interface"],
  2338.                     "Detector" => ["class", "interface"],
  2339.                     "Chunker" => ["class", "interface"],
  2340.                     "Validator" => ["class", "interface"],
  2341.                 ],
  2342.                 "Mapping" => [
  2343.                     "Mapper" => ["class", "interface"],
  2344.                     "Transformer" => ["class", "interface"],
  2345.                     "Resolver" => ["class", "interface"],
  2346.                     "Profiler" => ["class", "interface"],
  2347.                 ],
  2348.                 "Execution" => [
  2349.                     "Importer" => ["class", "interface"],
  2350.                     "Runner" => ["class", "interface"],
  2351.                     "Rollback" => ["class", "interface"],
  2352.                     "Progress" => ["class", "interface"],
  2353.                     "Log" => ["class", "interface"],
  2354.                     "Report" => ["class"],
  2355.                 ],
  2356.                 "Source" => [
  2357.                     "Csv" => [".csv"],
  2358.                     "Excel" => [".xlsx", ".xls"],
  2359.                     "Json" => [".json"],
  2360.                     "Xml" => [".xml"],
  2361.                     "Fixture" => [".yaml", ".json"],
  2362.                 ],
  2363.             ],
  2364.             "Presentation" => [
  2365.                 "Frontend" => [
  2366.                     "Component" => [".vue", ".tsx", ".svelte", ".astro"],
  2367.                     "Page" => [".vue", ".tsx", ".svelte"],
  2368.                     "Layout" => [".vue", ".tsx", ".svelte"],
  2369.                     "Store" => [".ts", ".js"],
  2370.                     "Composable" => [".ts"],
  2371.                     "Router" => [".ts", ".js"],
  2372.                     "Type" => [".ts"],
  2373.                     "Config" => [".ts", ".js", ".mjs"],
  2374.                 ],
  2375.                 "Web" => [
  2376.                     "Controller" => ["class"],
  2377.                     "Action" => ["class"],
  2378.                     "Endpoint" => ["class"],
  2379.                     "Middleware" => ["class", "interface"],
  2380.                     "Filter" => ["class", "interface"],
  2381.                     "Router" => ["class", "interface"],
  2382.                     "Redirector" => ["class", "interface"],
  2383.                     "Responder" => ["class", "interface"],
  2384.                 ],
  2385.                 "View" => [
  2386.                     "Renderer" => ["class", "interface"],
  2387.                     "Engine" => ["class", "interface"],
  2388.                     "Composer" => ["class", "interface"],
  2389.                     "Component" => ["class"],
  2390.                     "Directive" => ["class", "interface"],
  2391.                     "Presenter" => ["class", "interface"],
  2392.                     "Layout" => ["class"],
  2393.                     "Template" => ["class", "interface"],
  2394.                 ],
  2395.                 "Cli" => [
  2396.                     "Renderer" => ["class", "interface"],
  2397.                     "Formatter" => ["class", "interface"],
  2398.                     "Prompt" => ["class", "interface"],
  2399.                     "Printer" => ["class", "interface"],
  2400.                     "Style" => ["class"],
  2401.                     "Progress" => ["class", "interface"],
  2402.                     "Table" => ["class"],
  2403.                 ],
  2404.                 "Assets" => [
  2405.                     "Template" => [
  2406.                         "Layout" => [".html"],
  2407.                         "View" => [".html"],
  2408.                         "Partial" => [".html"],
  2409.                         "Component" => [".html"],
  2410.                         "Email" => [".html", ".txt"],
  2411.                         "Error" => [".html"],
  2412.                     ],
  2413.                     "Static" => [
  2414.                         "Style" => [".css", ".sass", ".scss", ".less"],
  2415.                         "Script" => [".js", ".jsx", ".ts", ".tsx", ".mjs"],
  2416.                         "Image" => [".png", ".gif", ".jpg", ".jpeg", ".svg", ".webp", ".avif"],
  2417.                         "Font" => [".woff", ".woff2", ".ttf", ".otf", ".eot"],
  2418.                         "Media" => [".mp3", ".mp4", ".webm", ".ogg", ".ogv"],
  2419.                         "Data" => [".json", ".geojson", ".topojson"],
  2420.                     ],
  2421.                     "Entry" => [".php", ".htaccess", "web.config", ".nginx"],
  2422.                     "Manifest" => [".json", ".webmanifest"],
  2423.                     "Meta" => [".json", ".txt", ".xml", ".yml", ".yaml"],
  2424.                 ],
  2425.             ],
  2426.  
  2427.             "Job" => [
  2428.                 "Task" => [
  2429.                     "Job" => ["class"],
  2430.                     "Task" => ["class"],
  2431.                     "Batch" => ["class"],
  2432.                     "Chain" => ["class"],
  2433.                     "Middleware" => ["class", "interface"],
  2434.                     "Retry" => ["class", "interface"],
  2435.                 ],
  2436.                 "Idempotency" => [
  2437.                     "Guard" => ["class", "interface"],
  2438.                     "Store" => ["class", "interface"],
  2439.                 ],
  2440.                 "Queue" => [
  2441.                     "Worker" => ["class", "interface"],
  2442.                     "Dispatcher" => ["class", "interface"],
  2443.                     "Driver" => ["class", "interface"],
  2444.                     "Monitor" => ["class", "interface"],
  2445.                     "Connector" => ["class", "interface"],
  2446.                     "Serializer" => ["class", "interface"],
  2447.                 ],
  2448.                 "Pipeline" => [
  2449.                     "Pipeline" => ["class", "interface"],
  2450.                     "Stage" => ["class", "interface"],
  2451.                     "Processor" => ["class", "interface"],
  2452.                     "Extractor" => ["class", "interface"],
  2453.                     "Transformer" => ["class", "interface"],
  2454.                     "Loader" => ["class", "interface"],
  2455.                 ],
  2456.                 "Process" => [
  2457.                     "Manager" => ["class", "interface"],
  2458.                     "Runner" => ["class", "interface"],
  2459.                     "Supervisor" => ["class", "interface"],
  2460.                     "Signal" => ["class"],
  2461.                     "Lock" => ["class", "interface"],
  2462.                 ],
  2463.             ],
  2464.             "Notification" => [
  2465.                 "Core" => [
  2466.                     "Notification" => ["class"],
  2467.                     "Dispatcher" => ["class", "interface"],
  2468.                     "Channel" => ["class", "interface"],
  2469.                     "Manager" => ["class", "interface"],
  2470.                     "Queue" => ["class", "interface"],
  2471.                 ],
  2472.                 "Channel" => [
  2473.                     "Mail" => ["class", "interface"],
  2474.                     "Sms" => ["class", "interface"],
  2475.                     "Push" => ["class", "interface"],
  2476.                     "Slack" => ["class", "interface"],
  2477.                     "Webhook" => ["class", "interface"],
  2478.                     "Database" => ["class", "interface"],
  2479.                     "Broadcast" => ["class", "interface"],
  2480.                     "Telegram" => ["class", "interface"],
  2481.                 ],
  2482.                 "Message" => [
  2483.                     "MailMessage" => ["class"],
  2484.                     "SmsMessage" => ["class"],
  2485.                     "PushMessage" => ["class"],
  2486.                     "SlackMessage" => ["class"],
  2487.                     "BroadcastMessage" => ["class"],
  2488.                 ],
  2489.                 "Preference" => [
  2490.                     "Repository" => ["class", "interface"],
  2491.                     "Resolver" => ["class", "interface"],
  2492.                     "Subscriber" => ["class"],
  2493.                 ],
  2494.             ],
  2495.             "Auth" => [
  2496.                 "Authentication" => [
  2497.                     "Authenticator" => ["class", "interface"],
  2498.                     "Guard" => ["class", "interface"],
  2499.                     "Provider" => ["class", "interface"],
  2500.                     "Attempt" => ["class"],
  2501.                     "Credential" => ["class"],
  2502.                     "Verifier" => ["class", "interface"],
  2503.                     "Challenge" => ["class", "interface"],
  2504.                     "Session" => ["class", "interface"],
  2505.                     "Token" => [
  2506.                         "Token" => ["class"],
  2507.                         "Issuer" => ["class", "interface"],
  2508.                         "Parser" => ["class", "interface"],
  2509.                         "Verifier" => ["class", "interface"],
  2510.                         "Refresher" => ["class", "interface"],
  2511.                     ],
  2512.                 ],
  2513.                 "Authorization" => [
  2514.                     "Gate" => ["class", "interface"],
  2515.                     "Policy" => ["class", "interface"],
  2516.                     "Voter" => ["class", "interface"],
  2517.                     "Resolver" => ["class", "interface"],
  2518.                     "Evaluator" => ["class", "interface"],
  2519.                     "Permission" => ["class"],
  2520.                     "Role" => ["class"],
  2521.                     "Ability" => ["class"],
  2522.                 ],
  2523.                 "OAuth" => [
  2524.                     "Server" => ["class", "interface"],
  2525.                     "Client" => ["class", "interface"],
  2526.                     "Provider" => ["class", "interface"],
  2527.                     "Grant" => ["class", "interface"],
  2528.                     "Token" => ["class"],
  2529.                     "Scope" => ["class"],
  2530.                     "State" => ["class"],
  2531.                 ],
  2532.                 "Password" => [
  2533.                     "Hasher" => ["class", "interface"],
  2534.                     "Validator" => ["class", "interface"],
  2535.                     "Resetter" => ["class", "interface"],
  2536.                     "Generator" => ["class", "interface"],
  2537.                     "Broker" => ["class", "interface"],
  2538.                     "Token" => ["class"],
  2539.                 ],
  2540.                 "ApiKey" => [
  2541.                     "Repository" => ["class", "interface"],
  2542.                     "Generator" => ["class", "interface"],
  2543.                     "Verifier" => ["class", "interface"],
  2544.                     "Rotator" => ["class", "interface"],
  2545.                 ],
  2546.             ],
  2547.             "Media" => [
  2548.                 "Upload" => [
  2549.                     "Handler" => ["class", "interface"],
  2550.                     "Validator" => ["class", "interface"],
  2551.                     "Chunker" => ["class", "interface"],
  2552.                     "Receiver" => ["class", "interface"],
  2553.                 ],
  2554.                 "Image" => [
  2555.                     "Processor" => ["class", "interface"],
  2556.                     "Resizer" => ["class", "interface"],
  2557.                     "Cropper" => ["class", "interface"],
  2558.                     "Filter" => ["class", "interface"],
  2559.                     "Optimizer" => ["class", "interface"],
  2560.                     "Converter" => ["class", "interface"],
  2561.                     "Generator" => ["class", "interface"],
  2562.                 ],
  2563.                 "Av" => [
  2564.                     "Processor" => ["class", "interface"],
  2565.                     "Transcoder" => ["class", "interface"],
  2566.                     "Extractor" => ["class", "interface"],
  2567.                     "Streamer" => ["class", "interface"],
  2568.                 ],
  2569.                 "Document" => [
  2570.                     "Processor" => ["class", "interface"],
  2571.                     "Converter" => ["class", "interface"],
  2572.                     "Extractor" => ["class", "interface"],
  2573.                     "Renderer" => ["class", "interface"],
  2574.                     "Signer" => ["class", "interface"],
  2575.                 ],
  2576.                 "Delivery" => [
  2577.                     "Disk" => ["class", "interface"],
  2578.                     "Url" => ["class", "interface"],
  2579.                     "Cdn" => ["class", "interface"],
  2580.                     "Purger" => ["class", "interface"],
  2581.                     "Proxy" => ["class", "interface"],
  2582.                 ],
  2583.                 "Library" => [
  2584.                     "Repository" => ["class", "interface"],
  2585.                     "Organizer" => ["class", "interface"],
  2586.                     "Tagger" => ["class", "interface"],
  2587.                     "Search" => ["class", "interface"],
  2588.                 ],
  2589.             ],
  2590.             "Report" => [
  2591.                 "Core" => [
  2592.                     "Report" => ["class", "interface"],
  2593.                     "Builder" => ["class", "interface"],
  2594.                     "Renderer" => ["class", "interface"],
  2595.                     "Scheduler" => ["class", "interface"],
  2596.                     "Exporter" => ["class", "interface"],
  2597.                 ],
  2598.                 "Export" => [
  2599.                     "Csv" => ["class", "interface"],
  2600.                     "Excel" => ["class", "interface"],
  2601.                     "Pdf" => ["class", "interface"],
  2602.                     "Json" => ["class", "interface"],
  2603.                     "Xml" => ["class", "interface"],
  2604.                     "Zip" => ["class", "interface"],
  2605.                 ],
  2606.                 "Analytics" => [
  2607.                     "Aggregator" => ["class", "interface"],
  2608.                     "Metric" => ["class"],
  2609.                     "Dimension" => ["class"],
  2610.                     "Calculator" => ["class", "interface"],
  2611.                     "Snapshot" => ["class"],
  2612.                     "Trend" => ["class", "interface"],
  2613.                 ],
  2614.                 "Dashboard" => [
  2615.                     "Widget" => ["class", "interface"],
  2616.                     "Provider" => ["class", "interface"],
  2617.                     "Filter" => ["class", "interface"],
  2618.                     "Chart" => ["class"],
  2619.                 ],
  2620.             ],
  2621.             "Integration" => [
  2622.                 "Ai" => [
  2623.                     "Client" => ["class", "interface"],
  2624.                     "Credential" => ["class"],
  2625.                     "Response" => ["class"],
  2626.                     "Moderation" => ["class", "interface"],
  2627.                     "Embedder" => ["class", "interface"],
  2628.                 ],
  2629.                 "Payment" => [
  2630.                     "Gateway" => ["class", "interface"],
  2631.                     "Processor" => ["class", "interface"],
  2632.                     "Webhook" => ["class", "interface"],
  2633.                     "Refund" => ["class", "interface"],
  2634.                     "Subscription" => ["class", "interface"],
  2635.                     "Invoice" => ["class", "interface"],
  2636.                     "Method" => ["class"],
  2637.                 ],
  2638.                 "Tax" => [
  2639.                     "Calculator" => ["class", "interface"],
  2640.                     "Verifier" => ["class", "interface"],
  2641.                     "Webhook" => ["class", "interface"],
  2642.                 ],
  2643.                 "Mail" => [
  2644.                     "Transport" => ["class", "interface"],
  2645.                     "Driver" => ["class", "interface"],
  2646.                     "Webhook" => ["class", "interface"],
  2647.                     "Validator" => ["class", "interface"],
  2648.                 ],
  2649.                 "Sms" => [
  2650.                     "Driver" => ["class", "interface"],
  2651.                     "Webhook" => ["class", "interface"],
  2652.                 ],
  2653.                 "Push" => [
  2654.                     "Driver" => ["class", "interface"],
  2655.                     "Payload" => ["class"],
  2656.                     "Device" => ["class"],
  2657.                 ],
  2658.                 "Geo" => [
  2659.                     "Geocoder" => ["class", "interface"],
  2660.                     "Router" => ["class", "interface"],
  2661.                     "Mapper" => ["class", "interface"],
  2662.                     "Coordinate" => ["class"],
  2663.                     "Address" => ["class"],
  2664.                 ],
  2665.                 "Social" => [
  2666.                     "Provider" => ["class", "interface"],
  2667.                     "Profile" => ["class"],
  2668.                     "Token" => ["class"],
  2669.                 ],
  2670.                 "Sdk" => [
  2671.                     "Client" => ["class", "interface"],
  2672.                     "Connector" => ["class", "interface"],
  2673.                     "Adapter" => ["class", "interface"],
  2674.                     "Response" => ["class"],
  2675.                     "Exception" => ["class"],
  2676.                 ],
  2677.             ],
  2678.             "Infrastructure" => [
  2679.                 "Resilience" => [
  2680.                     "CircuitBreaker" => ["class", "interface"],
  2681.                     "RetryPolicy" => ["class", "interface"],
  2682.                     "Bulkhead" => ["class", "interface"],
  2683.                     "Timeout" => ["class", "interface"],
  2684.                     "Fallback" => ["class", "interface"],
  2685.                     "RateLimit" => ["class", "interface"],
  2686.                     "Hedging" => ["class", "interface"],
  2687.                 ],
  2688.                 "DistributedLock" => [
  2689.                     "Lock" => ["class", "interface"],
  2690.                     "Provider" => ["class", "interface"],
  2691.                     "Token" => ["class"],
  2692.                 ],
  2693.                 "Aop" => [
  2694.                     "Interceptor" => ["class", "interface"],
  2695.                     "Advice" => ["class", "interface"],
  2696.                     "Pointcut" => ["class", "interface"],
  2697.                     "Proxy" => ["class", "interface"],
  2698.                 ],
  2699.                 "Messaging" => [
  2700.                     "Bus" => ["class", "interface"],
  2701.                     "Queue" => ["class", "interface"],
  2702.                     "Topic" => ["class", "interface"],
  2703.                     "Dispatcher" => ["class", "interface"],
  2704.                     "Handler" => ["class"],
  2705.                     "Message" => ["class"],
  2706.                     "Envelope" => ["class"],
  2707.                     "Middleware" => ["class", "interface"],
  2708.                     "Consumer" => ["class", "interface"],
  2709.                     "Producer" => ["class", "interface"],
  2710.                     "Serializer" => ["class", "interface"],
  2711.                 ],
  2712.                 "Transport" => [
  2713.                     "Protocol" => ["class", "interface"],
  2714.                     "Client" => ["class", "interface"],
  2715.                     "Server" => ["class", "interface"],
  2716.                     "Stream" => ["class", "interface"],
  2717.                     "Buffer" => ["class", "interface"],
  2718.                     "Channel" => ["class", "interface"],
  2719.                     "Encoder" => ["class", "interface"],
  2720.                     "Decoder" => ["class", "interface"],
  2721.                     "Formatter" => ["class", "interface"],
  2722.                     "Interceptor" => ["class", "interface"],
  2723.                 ],
  2724.                 "Patterns" => [
  2725.                     "Adapter" => ["class", "interface"],
  2726.                     "Bridge" => ["class", "interface"],
  2727.                     "Facade" => ["class"],
  2728.                     "Proxy" => ["class", "interface"],
  2729.                     "Wrapper" => ["class", "interface"],
  2730.                     "Decorator" => ["class", "interface"],
  2731.                     "Composite" => ["class", "interface"],
  2732.                     "Flyweight" => ["class", "interface"],
  2733.                     "Driver" => ["class", "interface"],
  2734.                     "Connector" => ["class", "interface"],
  2735.                     "Visitor" => ["class", "interface"],
  2736.                 ],
  2737.                 "Security" => [
  2738.                     "Cryptography" => [
  2739.                         "Hasher" => ["class", "interface"],
  2740.                         "Cipher" => ["class", "interface"],
  2741.                         "Encoder" => ["class", "interface"],
  2742.                         "Signer" => ["class", "interface"],
  2743.                         "Verifier" => ["class", "interface"],
  2744.                         "Random" => ["class", "interface"],
  2745.                         "Key" => ["class"],
  2746.                     ],
  2747.                     "Network" => [
  2748.                         "Firewall" => ["class", "interface"],
  2749.                         "RateLimiter" => ["class", "interface"],
  2750.                         "Cors" => ["class", "interface"],
  2751.                         "Csp" => ["class", "interface"],
  2752.                         "Csrf" => ["class", "interface"],
  2753.                     ],
  2754.                 ],
  2755.                 "FileSystem" => [
  2756.                     "Storage" => ["class", "interface"],
  2757.                     "Disk" => ["class", "interface"],
  2758.                     "Manipulator" => ["class", "interface"],
  2759.                     "Watcher" => ["class", "interface"],
  2760.                     "Lock" => ["class", "interface"],
  2761.                     "Finder" => ["class", "interface"],
  2762.                     "Zipper" => ["class", "interface"],
  2763.                 ],
  2764.                 "Observability" => [
  2765.                     "Logging" => [
  2766.                         "Logger" => ["class", "interface"],
  2767.                         "Handler" => ["class", "interface"],
  2768.                         "Formatter" => ["class", "interface"],
  2769.                         "Processor" => ["class", "interface"],
  2770.                         "Channel" => ["class", "interface"],
  2771.                     ],
  2772.                     "Metrics" => [
  2773.                         "Collector" => ["class", "interface"],
  2774.                         "Gauge" => ["class", "interface"],
  2775.                         "Counter" => ["class", "interface"],
  2776.                         "Histogram" => ["class", "interface"],
  2777.                         "Exporter" => ["class", "interface"],
  2778.                     ],
  2779.                     "Tracing" => [
  2780.                         "Tracer" => ["class", "interface"],
  2781.                         "Span" => ["class", "interface"],
  2782.                         "Propagator" => ["class", "interface"],
  2783.                         "Exporter" => ["class", "interface"],
  2784.                     ],
  2785.                     "Healthcheck" => [
  2786.                         "Check" => ["class", "interface"],
  2787.                         "Registry" => ["class", "interface"],
  2788.                         "Reporter" => ["class", "interface"],
  2789.                     ],
  2790.                     "Profiler" => [
  2791.                         "Profiler" => ["class", "interface"],
  2792.                         "Timer" => ["class", "interface"],
  2793.                         "Recorder" => ["class", "interface"],
  2794.                     ],
  2795.                     "ErrorTracking" => [
  2796.                         "Client" => ["class", "interface"],
  2797.                         "Reporter" => ["class", "interface"],
  2798.                         "Filter" => ["class", "interface"],
  2799.                         "Breadcrumb" => ["class"],
  2800.                         "Context" => ["class"],
  2801.                     ],
  2802.                 ],
  2803.                 "Http" => [
  2804.                     "Client" => ["class", "interface"],
  2805.                     "Request" => ["class"],
  2806.                     "Response" => ["class"],
  2807.                     "Middleware" => ["class", "interface"],
  2808.                     "Retry" => ["class", "interface"],
  2809.                     "Pool" => ["class", "interface"],
  2810.                 ],
  2811.             ],
  2812.             "System" => [
  2813.                 "DI" => [
  2814.                     "Container" => ["class", "interface"],
  2815.                     "Locator" => ["class", "interface"],
  2816.                     "Provider" => ["class"],
  2817.                     "Registry" => ["class", "interface"],
  2818.                     "Catalog" => ["class", "interface"],
  2819.                     "Broker" => ["class", "interface"],
  2820.                     "Factory" => ["class", "interface"],
  2821.                     "Builder" => ["class", "interface"],
  2822.                     "Scope" => ["class", "interface"],
  2823.                     "Resolver" => ["class", "interface"],
  2824.                 ],
  2825.                 "State" => [
  2826.                     "Machine" => ["class", "interface"],
  2827.                     "State" => ["class"],
  2828.                     "Transition" => ["class"],
  2829.                     "Context" => ["class"],
  2830.                     "Guard" => ["class", "interface"],
  2831.                     "Action" => ["class", "interface"],
  2832.                     "Memento" => ["class"],
  2833.                     "Observer" => ["class", "interface"],
  2834.                     "Mediator" => ["class", "interface"],
  2835.                 ],
  2836.                 "Utility" => [
  2837.                     "Function" => [
  2838.                         "Helper" => ["function"],
  2839.                         "Predicate" => ["function"],
  2840.                         "Transformer" => ["function"],
  2841.                         "Formatter" => ["function"],
  2842.                         "Comparator" => ["function"],
  2843.                     ],
  2844.                     "Class" => [
  2845.                         "Parser" => ["class", "interface"],
  2846.                         "Generator" => ["class", "interface"],
  2847.                         "Iterator" => ["class", "interface"],
  2848.                         "Comparable" => ["class", "interface"],
  2849.                         "Cloneable" => ["class", "interface"],
  2850.                         "Stringable" => ["class", "interface"],
  2851.                         "Countable" => ["class", "interface"],
  2852.                         "Interpreter" => ["class", "interface"],
  2853.                     ],
  2854.                     "Type" => [
  2855.                         "Collection" => ["class"],
  2856.                         "Arr" => ["class"],
  2857.                         "Str" => ["class"],
  2858.                         "Number" => ["class"],
  2859.                         "Date" => ["class"],
  2860.                         "File" => ["class"],
  2861.                         "Path" => ["class"],
  2862.                         "Url" => ["class"],
  2863.                         "Math" => ["class", "function"],
  2864.                         "Logic" => ["class", "function"],
  2865.                         "Json" => ["class", "function"],
  2866.                         "Xml" => ["class", "function"],
  2867.                         "Regex" => ["class"],
  2868.                         "Uuid" => ["class", "function"],
  2869.                         "Crypto" => ["class", "function"],
  2870.                     ],
  2871.                 ],
  2872.                 "Extension" => [
  2873.                     "Hook" => ["function"],
  2874.                     "Plugin" => ["class", "interface"],
  2875.                     "Module" => ["class", "interface"],
  2876.                     "Shortcode" => ["class", "function"],
  2877.                     "Library" => ["class", "trait"],
  2878.                     "Macro" => ["class", "interface"],
  2879.                     "Mixin" => ["trait"],
  2880.                 ],
  2881.             ],
  2882.             "Quality" => [
  2883.                 "Test" => [
  2884.                     "Suite" => [
  2885.                         "Unit" => ["class"],
  2886.                         "Integration" => ["class"],
  2887.                         "Feature" => ["class"],
  2888.                         "E2E" => ["class"],
  2889.                         "Contract" => ["class", "interface"],
  2890.                         "Performance" => ["class"],
  2891.                         "Security" => ["class"],
  2892.                         "Mutation" => ["class"],
  2893.                         "Snapshot" => ["class"],
  2894.                         "Architecture" => ["class"],
  2895.                     ],
  2896.                     "Double" => [
  2897.                         "Mock" => ["class"],
  2898.                         "Stub" => ["class"],
  2899.                         "Spy" => ["class"],
  2900.                         "Fixture" => ["class"],
  2901.                         "Dummy" => ["class"],
  2902.                         "Fake" => ["class"],
  2903.                         "Factory" => ["class"],
  2904.                     ],
  2905.                     "Assertion" => [
  2906.                         "Matcher" => ["class", "interface"],
  2907.                         "Expectation" => ["class"],
  2908.                         "Verifier" => ["class", "interface"],
  2909.                         "Constraint" => ["class"],
  2910.                     ],
  2911.                     "Helper" => [
  2912.                         "Helper" => ["class", "trait"],
  2913.                         "Concern" => ["trait"],
  2914.                         "Setup" => ["class"],
  2915.                     ],
  2916.                 ],
  2917.                 "Analysis" => [
  2918.                     "Rule" => ["class", "interface"],
  2919.                     "Fixer" => ["class", "interface"],
  2920.                     "Config" => [".php", ".neon", ".xml"],
  2921.                     "Baseline" => [".xml", ".json"],
  2922.                 ],
  2923.                 "Benchmark" => [
  2924.                     "Bench" => ["class"],
  2925.                     "Provider" => ["class"],
  2926.                     "Fixture" => ["class"],
  2927.                 ],
  2928.                 "Docs" => [".md", ".rst", ".asciidoc"],
  2929.                 "ApiDocs" => [
  2930.                     "Spec" => [".yaml", ".json"],
  2931.                     "Collection" => [".json"],
  2932.                     "Changelog" => [".md"],
  2933.                     "Example" => [".json", ".yaml"],
  2934.                     "Generator" => ["class", "interface"],
  2935.                 ],
  2936.                 "Translation" => [
  2937.                     "Locale" => [".po", ".mo", ".json", ".yaml"],
  2938.                     "Catalog" => ["class", "interface"],
  2939.                     "Interpreter" => ["class", "interface"],
  2940.                     "Translator" => ["class", "interface"],
  2941.                     "Extractor" => ["class", "interface"],
  2942.                     "Compiler" => ["class", "interface"],
  2943.                 ],
  2944.             ],
  2945.             "Migration" => [
  2946.                 "File" => [".json"],
  2947.                 "Registry" => [".json"],
  2948.             ],
  2949.             "Build" => [
  2950.                 "Map" => [".json"],
  2951.             ],
  2952.         ],
  2953.         ["boot"],
  2954.     );
  2955.  
  2956.     # Filter args.
  2957.    $args = array_filter($args);
  2958.  
  2959.     if (empty($args)) {
  2960.         $h = [];
  2961.         $h[] = "struct like <query> to search structures.";
  2962.         $h[] = "struct list <structure> to list all files in a structure folder.";
  2963.         $h[] = "struct search <query> searches for a phrase in all structure files (php, js, css, html).";
  2964.         $h[] = "struct new <structure> <name> <?type> to create new stucture file.";
  2965.         $h[] = "struct move <structure> <filename> <target structure> to safely move (modifies all files).";
  2966.         $h[] = "struct transfer <structure> <target structure> foreach in structure do move.";
  2967.         $h[] = "struct backup <?filename> Creates backup of entire node.";
  2968.         $h[] = "struct deprecate <structure> <filename> makes a copy of target to deprecated folder.";
  2969.         $h[] = "struct delete <structure> <filename> moves target and its doc & unit-test to deleted folder.";
  2970.         $h[] = "struct restore <structure> <filename> moves latest";
  2971.         $h[] = "struct doc <structure/file' 'name> to create/read where ' ' is preserved only in headers .md.";
  2972.         $h[] = "struct sync <?projectPath> writes current dynamic structure additions to structure.json.";
  2973.         $h[] = "struct reorganize applies structure found in self to self containing files.";
  2974.         return "Structuring tool, use:\n- " . implode("\n- ", $h);
  2975.     }
  2976.  
  2977.     if ($args[0] === ":struct") {
  2978.         return $struct;
  2979.     }
  2980.  
  2981.     # -------------------------------------------------------------------------
  2982.    # Dynamic structure from structure.json — merged on top of built-in.
  2983.    # Loaded once per request via a static. The static is keyed by PROJECT_PATH
  2984.    # so it reloads cleanly if the active project changes mid-process.
  2985.    # -------------------------------------------------------------------------
  2986.    static $dynamicCache = [];
  2987.     static $buildCache = [];
  2988.     $projectPath = _node_project("path");
  2989.  
  2990.     if ($projectPath && !isset($dynamicCache[$projectPath])) {
  2991.         $dynamicCache[$projectPath] = _node_struct_load_dynamic($projectPath);
  2992.     }
  2993.     $dynamicKeys = $projectPath ? $dynamicCache[$projectPath] ?? [] : [];
  2994.  
  2995.     // ── Stage 3: build file structure ────────────────────────────────────────────
  2996.     // If node.json names a build file, load its "structure" key and merge it in.
  2997.     if ($projectPath && !isset($buildCache[$projectPath])) {
  2998.         $buildCache[$projectPath] = [];
  2999.         $nodeJson = _node_migrate_load("{$projectPath}node.json");
  3000.         if (!empty($nodeJson["build"])) {
  3001.             $buildDef = _node_build_load_merged($nodeJson["build"]);
  3002.             if (!empty($buildDef["structure"])) {
  3003.                 $buildCache[$projectPath] = _node_struct_flatten($buildDef["structure"]);
  3004.             }
  3005.         }
  3006.     }
  3007.     $buildKeys = $projectPath ? $buildCache[$projectPath] ?? [] : [];
  3008.  
  3009.     if (in_array($args[0], [":keys", ":structs", ":dump"])) {
  3010.         $keys = [];
  3011.  
  3012.         $a = function (array $node, array $key = []) use (&$keys, &$a): array {
  3013.             foreach ($node as $name => $sub) {
  3014.                 !is_array($sub) && var_dump($name, $sub);
  3015.                 $nkey = [...$key, $name];
  3016.                 if (!array_is_list($sub)) {
  3017.                     $a($sub, $nkey);
  3018.                 } else {
  3019.                     $keys[implode(D, $nkey)] = $sub;
  3020.                 }
  3021.             }
  3022.             return $key;
  3023.         };
  3024.  
  3025.         $a($struct);
  3026.  
  3027.         # Merge dynamic keys on top — dynamic entries extend or override built-in.
  3028.        # array_merge: later keys win, so dynamic wins over builtin for same path.
  3029.        $keys = [...$keys, ...$dynamicKeys, ...$buildKeys];
  3030.  
  3031.         # :keys - Check to return early.
  3032.        if ($args[0] === ":keys") {
  3033.             return $keys;
  3034.         }
  3035.  
  3036.         # :structs
  3037.        $structs = [];
  3038.  
  3039.         foreach ($keys as $namespace => $declarations) {
  3040.             $namespace = explode(D, $namespace);
  3041.             $exists = false;
  3042.             while (count($namespace) > 1 && !$exists) {
  3043.                 $nextNamespace = array_slice($namespace, 1);
  3044.                 if (array_key_exists(implode(D, $nextNamespace), $structs)) {
  3045.                     $exists = true;
  3046.                     $structs[implode(D, $namespace)] = $declarations;
  3047.                 }
  3048.                 $namespace = $nextNamespace;
  3049.             }
  3050.             if (!$exists) {
  3051.                 $structs[implode(D, $namespace)] = $declarations;
  3052.             }
  3053.         }
  3054.  
  3055.         if ($args[0] === ":keys") {
  3056.             return $structs;
  3057.         }
  3058.  
  3059.         # Equal parts.
  3060.        $paths = array_keys($keys);
  3061.         $short = array_keys($structs);
  3062.         $allowed = array_map(fn($a) => "<" . implode(", ", $a) . ">", array_values($structs));
  3063.  
  3064.         # :dump
  3065.        return array_map(fn($x) => "$paths[$x] <{$short[$x]}> {$allowed[$x]}", array_keys($short));
  3066.     }
  3067.  
  3068.     if ($args[0] === ":find") {
  3069.         if (!empty($args[1])) {
  3070.             $keys = array_keys(struct(":keys"));
  3071.             $structs = struct(":structs");
  3072.             $r = [];
  3073.             $n = 0;
  3074.             $query = strtolower((string) $args[1]);
  3075.             foreach ($structs as $definition) {
  3076.                 if (strpos(strtolower($definition), $query) !== false) {
  3077.                     $r[$keys[$n]] = $definition;
  3078.                 }
  3079.                 $n++;
  3080.             }
  3081.             return $r;
  3082.         }
  3083.         return r("Struct: Invalid <query> for :find", "Error", 1);
  3084.     }
  3085.  
  3086.     if ($args[0] === ":documentation") {
  3087.         if (isset($args[1])) {
  3088.             $path = explode(" ", $args[1])[0];
  3089.  
  3090.             # Attempt structure documentation from current and fallback to base node.
  3091.            $df = _node_project("path") . "Quality" . D . "Docs" . D . str_replace(D, "_", $path) . ".md";
  3092.             $dn = __DIR__ . D . "NodePHP/Quality/Docs/" . str_replace(D, "_", $path) . ".md";
  3093.  
  3094.             # Return docs.
  3095.            if ($doc = f($df, "read", null, false) ?: f($dn, "read", null, false)) {
  3096.                 return $doc;
  3097.             }
  3098.  
  3099.             return r("Struct: Documentation not found", "Info", "This structure is not yet documented.\nUse\nstruct doc <structure/name> to create/read .md.");
  3100.         }
  3101.         return r("Struct: No struct path to document for :documentation", "Error", 1);
  3102.     }
  3103.  
  3104.     if (str_starts_with($args[0], ":structure:path")) {
  3105.         $structure = _node_argex($args, 1);
  3106.         $all = array_map(fn($s) => array_map(fn($v) => trim($v, "> "), explode("<", $s)), struct(":structs"));
  3107.  
  3108.         if (!empty(($find = array_filter($all, fn($v) => $v[1] === $structure)))) {
  3109.             return array_pop($find)[0];
  3110.         }
  3111.         return r("Struct: Invalid structure {$structure}.", "Info", 1);
  3112.     }
  3113.  
  3114.     # -------------------------------------------------------------------------
  3115.    # struct sync — writes the current dynamic key set back to structure.json.
  3116.    # Useful after manually calling _node_struct_save_dynamic() or to inspect
  3117.    # what has been accumulated. Also reloads the static cache for this project.
  3118.    # -------------------------------------------------------------------------
  3119.    if (str_starts_with($args[0], "sync")) {
  3120.         $syncPath = _node_argex($args, 1) ?: $projectPath ?? "";
  3121.         if (!$syncPath) {
  3122.             return r("Struct: sync requires a project path or PROJECT_PATH must be defined.", "Error", 1);
  3123.         }
  3124.         $syncPath = rtrim($syncPath, D) . D;
  3125.         $current = _node_struct_load_dynamic($syncPath);
  3126.         if (_node_struct_save_dynamic($syncPath, $current)) {
  3127.             # Invalidate cache so next struct(":keys") call picks up the written file.
  3128.            unset($dynamicCache[$syncPath]);
  3129.             unset($buildCache[$syncPath]);
  3130.             return "Struct: structure.json synced at {$syncPath}structure.json (" . count($current) . " entries).\n";
  3131.         }
  3132.         return r("Struct: failed to write structure.json at {$syncPath}", "Error", 2);
  3133.     }
  3134.  
  3135.     if (str_starts_with($args[0], "reorganize")) {
  3136.         $projectPath = _node_project("path");
  3137.         $projectName = _node_project("name");
  3138.  
  3139.         r("struct reorganize: starting self-import for {$projectName}", "Migrate", 0);
  3140.  
  3141.         $result = import($projectPath, $projectName, true); // true = reorganize mode
  3142.  
  3143.         return h("struct.reorganize.result", $result);
  3144.     }
  3145.  
  3146.     $pathmake = function (string $path): string {
  3147.         $fp = str_starts_with($path, _node_project("path")) || str_starts_with($path, ROOT_PATH) ? $path : _node_project("path") . $path;
  3148.         !file_exists($fp) && mkdir($fp, 0777, true);
  3149.         return $fp . D;
  3150.     };
  3151.  
  3152.     # Same beginning of list, new, move, move_all, deprecate, delete !!!
  3153.    if (str_starts_with($args[0], "doc")) {
  3154.         if ($structure = _node_argex($args, 1)) {
  3155.             if (is_string($structPath = struct(":structure:path", $structure))) {
  3156.                 # End of same beginnings.$pathmake
  3157.                $docPath = $pathmake("Quality/Docs") . str_replace(D, "_", $structPath) . ".md";
  3158.                 if (!file_exists($docPath)) {
  3159.                     if (f($docPath, "write", "# {$structPath}\n\n")) {
  3160.                         _node_gitignore($docPath, "write");
  3161.                         return "New <structure> documentation created at: {$docPath}\n";
  3162.                     }
  3163.                     return r("Struct: Could not create documentation for <structure> {$structure}", "Error", 2);
  3164.                 }
  3165.                 return f($docPath, "read");
  3166.             }
  3167.  
  3168.             # Not a documentation for <structure> but rather for resource <name>
  3169.            $resPath = $pathmake("Quality/Docs") . str_replace(D, "_", str_replace(" ", "", $structure)) . ".md";
  3170.             if (!file_exists($resPath)) {
  3171.                 if (f($resPath, "write", "# {$structure}\n\n")) {
  3172.                     _node_gitignore($resPath, "write");
  3173.                     return "New <name> documentation created at: {$resPath}\n";
  3174.                 }
  3175.                 return r("Struct: Could not create documentation for <name> {$structure}", "Error", 2);
  3176.             }
  3177.             return f($resPath, "read");
  3178.         }
  3179.         return r("Struct: No <structure> given", "Error", 1);
  3180.     }
  3181.  
  3182.     if (str_starts_with($args[0], "like")) {
  3183.         if ($like = _node_argex($args, 1)) {
  3184.             if ($found = struct(":find", $like)) {
  3185.                 return "Searched for '{$like}', found " . count($found) . " result(s):\n" . implode("\n", $found);
  3186.             }
  3187.             return "No structure matched '{$like}'\n";
  3188.         }
  3189.         return r("Struct: Invalid <query> for like", "Error", 1);
  3190.     }
  3191.  
  3192.     if (str_starts_with($args[0], "list")) {
  3193.         if ($structure = _node_argex($args, 1)) {
  3194.             if ($path = _node_spath($structure)) {
  3195.                 $fs = _node_project("path") . $path;
  3196.  
  3197.                 if (file_exists($fs) && is_dir($fs)) {
  3198.                     $fs = glob($fs . D . "*.*");
  3199.                     $r = "Listing <{$path}> with (" . count($fs) . ") inodes:\n";
  3200.                     foreach ($fs as $fn) {
  3201.                         $r .= dump($fn);
  3202.                     }
  3203.                 } else {
  3204.                     $r = "Cant list <{$path}> not found in project <" . _node_project("name") . ">";
  3205.                 }
  3206.                 return $r;
  3207.             }
  3208.             return r("Struct: list cannot find path for {$structure}.", "Error", 2);
  3209.         }
  3210.         return r("Struct: Invalid <structure> for list", "Error", 1);
  3211.     }
  3212.  
  3213.     if (str_starts_with($args[0], "search")) {
  3214.         if ($query = _node_argex($args, 1)) {
  3215.             $files = _node_gitignore(":list:all");
  3216.             if (!empty($files)) {
  3217.                 $r = "Searching for '{$query}', found (" . count($files) . "):\n";
  3218.                 foreach ($files as $fn) {
  3219.                     $lines = file($fn, FILE_IGNORE_NEW_LINES);
  3220.                     if ($lines === false) {
  3221.                         continue;
  3222.                     }
  3223.                     $hasMatch = false;
  3224.                     foreach ($lines as $ln => $line) {
  3225.                         if (stripos($line, $query) !== false) {
  3226.                             if (!$hasMatch) {
  3227.                                 $r .= $fn . ":" . ($ln + 1) . "\n";
  3228.                                 $hasMatch = true;
  3229.                             }
  3230.                             if (strlen($line) > 114) {
  3231.                                 $pos = stripos($line, $query);
  3232.                                 $start = max(0, $pos - 50);
  3233.                                 $snippet = substr($line, $start, 100);
  3234.                                 $snippet = ".. {$snippet} ..";
  3235.                                 $r .= "{$snippet}" . "\n";
  3236.                             } else {
  3237.                                 $r .= ">  {$line}\n";
  3238.                             }
  3239.                         }
  3240.                     }
  3241.                     if ($hasMatch) {
  3242.                         $r .= "\n";
  3243.                     }
  3244.                 }
  3245.                 return $r;
  3246.             }
  3247.             return r("Project <" . _node_project("name") . "> seems to have no files yet.", "Info", 1);
  3248.         }
  3249.     }
  3250.  
  3251.     $do = function (string $structure, string $filename, ?string $additional = null, ?callable $callback = null): int {
  3252.         # Common how case starts with preparation
  3253.        # Unavoidably custom logic:
  3254.        $r = $callback();
  3255.  
  3256.         # Common how struct ends
  3257.        return $r;
  3258.     };
  3259.  
  3260.     if (str_starts_with($args[0], "new")) {
  3261.         $structure = _node_argex($args, 1, 1);
  3262.         $name = _node_argex($args, 2, 1);
  3263.         $type = _node_argex($args, 3);
  3264.         if (!empty($structure) && !empty($name)) {
  3265.             if (([$structure, $path] = _node_spex($structure) ?? []) && $path) {
  3266.                 $singleStruct = array_filter(array_map(fn($x) => explode(" ", str_replace(["<", ">"], "", $x)), struct(":structs")), fn($f) => $f[1] === $structure);
  3267.                 $singleStruct = array_pop($singleStruct);
  3268.                 $structPath = $pathmake(_node_argex($singleStruct, 0, 1));
  3269.                 $declarations = array_filter(explode(",", _node_argex($singleStruct, 2)), fn($x) => $x);
  3270.  
  3271.                 if (count($declarations) === 1) {
  3272.                     $fileName = str_starts_with($declarations[0], ".") ? "{$name}{$declarations[0]}" : $name . ucfirst($declarations[0]) . ".php";
  3273.  
  3274.                     $type = $declarations[0];
  3275.                 } else {
  3276.                     $opts = implode("\n- ", $declarations) . "\n";
  3277.                     if (empty($type)) {
  3278.                         return r("Struct: <{$structure}> allows multiple types, select one:\n - {$opts} ", "Info", 3);
  3279.                     }
  3280.                     if (!in_array($type, $declarations)) {
  3281.                         return r("Struct: Invalid type <{$type}>, select one:\n - {$opts} ", "Info", 4);
  3282.                     }
  3283.                     unset($opts);
  3284.  
  3285.                     $fileName = str_starts_with($declarations[0], ".") ? "{$name}{$declarations[0]}" : $name . ucfirst($type) . ".php";
  3286.                 }
  3287.  
  3288.                 $fileBasename = substr($fileName, 0, strrpos($fileName, "."));
  3289.                 $fileExt = substr($fileName, strrpos($fileName, "."));
  3290.  
  3291.                 # File path.
  3292.                $filePath = "{$structPath}{$fileName}";
  3293.                 $fileType = ucfirst($type);
  3294.  
  3295.                 $r = "Creating resource <{$name}>\n";
  3296.  
  3297.                 # if (strpos($path, "Test") === false) {
  3298.                # Boilerplate.
  3299.                $boilFile = $path . D . "{$fileType}Boilerplate";
  3300.                 $boilNativePath = _node_project("path") . "Boilerplate" . D . $boilFile;
  3301.                 $boilRootPath = ROOT_PATH . FW_NAME . D . "Boilerplate" . D . $boilFile;
  3302.  
  3303.                 # Decide on boilerpath
  3304.                $boilPath = f($boilNativePath, "find", null, !1) ?? f($boilRootPath, "find", null, !1);
  3305.  
  3306.                 # Create selected path if not exists.
  3307.                $pathmake(implode(D, array_slice(explode(D, $boilPath ?? $boilNativePath), 0, -1)));
  3308.  
  3309.                 $boilTemplate = $boilPath
  3310.                     ? f($boilPath, "read")
  3311.                     : "<?php declare(strict_types=1);\n\nnamespace " .
  3312.                         _node_project("name") .
  3313.                         "\\" .
  3314.                         str_replace(D, "\\", $path) .
  3315.                         ";\n\n{$type} <name> " .
  3316.                         ($type === "function" ? "() : void {\n\t# TODO: this.\n}" : "{\n\t# TODO: this.\n}") .
  3317.                         "\n";
  3318.  
  3319.                 $boilerplateIsPlainFile = str_starts_with($type, ".");
  3320.  
  3321.                 if (!$boilPath && !$boilerplateIsPlainFile) {
  3322.                     if (f($boilRootPath, "write", $boilTemplate)) {
  3323.                         $r .= "Created new boilerplate for <{$structure}> in <" . FW_NAME . ">.\n";
  3324.                         if (!_node_gitignore($boilRootPath, "write", null, FW_NAME)) {
  3325.                             $r .= "Altered <" . FW_NAME . "> .gitignore to include boilerplte\n";
  3326.                         }
  3327.                     }
  3328.                 }
  3329.  
  3330.                 # Boilerplate for given structure.
  3331.                $fcontents = !$boilerplateIsPlainFile
  3332.                     ? str_replace(
  3333.                         array_map(fn($t) => "<{$t}>", ["name", "type", "structure", "path", "fullpath", "filename", "fw_name", "fw_version", "project_name"]),
  3334.                         [$name, $type, $structure, $path, $structPath, $fileName, FW_NAME, FW_VERSION, _node_project("name")],
  3335.                         $boilTemplate,
  3336.                     )
  3337.                     : "";
  3338.                 # }
  3339.  
  3340.                 # Actual file
  3341.                if (!file_exists($filePath) && !f($filePath, "write", $fcontents)) {
  3342.                     # Gitignore handles all pahts as relative from ROOT_PATH
  3343.                    $r .= !_node_gitignore($filePath, "write") ? "Altered .gitignore to include new resource.\n" : "";
  3344.  
  3345.                     if (strpos($path, "Test") === false && strpos($path, "Docs") === false) {
  3346.                         $docMakeResult = struct("doc", $structure . D . str_replace($fileType, " {$fileType}", $fileBasename));
  3347.                         $r .= is_string($docMakeResult) ? $docMakeResult : "";
  3348.                     }
  3349.  
  3350.                     if (strpos($path, "Test") === false && in_array($type, ["class", "function"])) {
  3351.                         $unitName = str_replace(D, "_", $structure) . "_{$name}";
  3352.                         if (is_string(struct("new Unit {$unitName}"))) {
  3353.                             $r .= "Added Unit testing {$unitName} for {$name}.\n";
  3354.                         }
  3355.                     }
  3356.  
  3357.                     $r .= "\nResource created!";
  3358.                 }
  3359.                 return $r;
  3360.             }
  3361.             return r("Struct: Invalid structure <{$structure}>.", "Info", 2);
  3362.         }
  3363.         return r("Struct: Please set both arguments <structure> and <name>.", "Info", 1);
  3364.     }
  3365.  
  3366.     if (str_starts_with($args[0], "move")) {
  3367.         $structure = _node_argex($args, 1, 1);
  3368.         $filename = _node_argex($args, 2, 1);
  3369.         $target = _node_argex($args, 3);
  3370.         if (!empty($structure) && !empty($filename) && !empty($target)) {
  3371.             $structKeys = struct(":keys");
  3372.  
  3373.             # Allow for full path as strucure and target.
  3374.            $from = array_key_exists($structure, $structKeys) ? $structure : struct(":structure:path", $structure);
  3375.             $to = array_key_exists($target, $structKeys) ? $target : struct(":structure:path", $target);
  3376.  
  3377.             # Name without declaration
  3378.            $pureName = $filename;
  3379.             foreach (struct(":declarations") as $declaration) {
  3380.                 $decl = ucfirst($declaration);
  3381.                 if (str_ends_with($filename, $decl)) {
  3382.                     $pureName = substr($filename, 0, strpos($filename, $decl));
  3383.                     unset($decl);
  3384.                     unset($declaration);
  3385.                     break;
  3386.                 }
  3387.             }
  3388.  
  3389.             # Full paths on disk.
  3390.            $fromPathBase = _node_project("path") . $from . D . $filename;
  3391.  
  3392.             # Namespaces
  3393.            $fromNamespace = _node_project("name") . "\\" . str_replace(D, "\\", $from);
  3394.             $fromNs = "namespace {$fromNamespace};";
  3395.             $fromUse = "\nuse {$fromNamespace}\\{$pureName}";
  3396.  
  3397.             $toNamespace = _node_project("name") . "\\" . str_replace(D, "\\", $to);
  3398.             $toNs = "namespace {$toNamespace};";
  3399.             $toUse = "\nuse {$toNamespace}\\{$pureName}";
  3400.  
  3401.             # Take the first extension that matches the filename.
  3402.            $fFl = glob("{$fromPathBase}.*");
  3403.             if (empty($fFl)) {
  3404.                 f(":rollback");
  3405.                 return r("Cannot move <{$filename}>, no file with souch name exists in <{$structure}>.", "Warning", 1);
  3406.             }
  3407.  
  3408.             while (!empty($fFl)) {
  3409.                 # This extension.
  3410.                $ext = array_last(explode(".", array_shift($fFl)));
  3411.  
  3412.                 # Move this file
  3413.                $fromPath = "{$fromPathBase}.{$ext}";
  3414.                 $toPath = _node_project("path") . $to . D . "{$filename}.{$ext}";
  3415.  
  3416.                 if (file_exists($toPath)) {
  3417.                     f(":rollback");
  3418.                     _node_gitignore(":rollback");
  3419.                     return r("Trying to move '{$filename}.{$ext}' which already exists at '{$toPath}'.", "Warning", 2);
  3420.                 }
  3421.  
  3422.                 $pathmake(dirname($toPath));
  3423.  
  3424.                 # Moving file.
  3425.                if (f($fromPath, "move", $toPath)) {
  3426.                     _node_gitignore($fromPath, "move", $toPath);
  3427.  
  3428.                     # Replacing 'namespace statement' from old to new.
  3429.                    f($toPath, "write", str_replace($fromNs, $toNs, f($toPath, "read")));
  3430.                 }
  3431.             }
  3432.  
  3433.             # Go rough entire struct and replace use statements.
  3434.            foreach (_node_gitignore(":list:all") as $relfn) {
  3435.                 if (strpos($relfn, ".") !== false) {
  3436.                     if (array_last(explode(".", $relfn)) === "php" || str_ends_with($relfn, "Boilerplate")) {
  3437.                         # Path to file.
  3438.                        $fp = ROOT_PATH . $relfn;
  3439.  
  3440.                         # Replacing 'namespace statement' from old to new.
  3441.                        file_exists($fp) && f($fp, "write", str_replace($fromUse, $toUse, f($fp, "read")));
  3442.                     }
  3443.                 }
  3444.             }
  3445.             # All moved.
  3446.            return 0;
  3447.         }
  3448.         return r("Struct: Please set all arguments <structure>, <name> and <target>.", "Info", 1);
  3449.     }
  3450.  
  3451.     if (str_starts_with($args[0], "transfer")) {
  3452.         $structure = _node_argex($args, 1, 1);
  3453.         $target = _node_argex($args, 2);
  3454.         if (!empty($structure) && !empty($target)) {
  3455.             if ($path = _node_spath($structure)) {
  3456.                 foreach (glob(_node_project("path") . $path . D . "/*.*") as $fn) {
  3457.                     $bn = basename($fn);
  3458.                     $pp = strpos($bn, ".");
  3459.                     $bn = $pp !== false ? substr($bn, 0, $pp) : $bn;
  3460.  
  3461.                     if (struct("move {$structure} {$bn} {$target}")) {
  3462.                         return r("Cannot move: {$structure} {$bn} {$target}", "Error", 3);
  3463.                     }
  3464.                 }
  3465.                 return 0;
  3466.             }
  3467.             return r("Struct: no files found in <{$structure}>", "Info", 2);
  3468.         }
  3469.         return r("Struct: provide both arguments <structure> and <target>", "Info", 1);
  3470.     }
  3471.  
  3472.     if (str_starts_with($args[0], "backup")) {
  3473.         $backupName = _node_argex($args, 1) ?: date("Ymd");
  3474.         $backupDir = $pathmake("Backup");
  3475.  
  3476.         $tarName = "{$backupDir}{$backupName}";
  3477.         $tarIndex = 0;
  3478.  
  3479.         do {
  3480.             $tarSavePath = "{$tarName}." . substr("00", 0, 2 - strlen((string) $tarIndex)) . "{$tarIndex}.tar.gz";
  3481.             $tarIndex++;
  3482.         } while (file_exists($tarSavePath) && $tarIndex < 100);
  3483.  
  3484.         if (file_exists($tarSavePath)) {
  3485.             return r("Backup '{$backupName}.xx.tar.gz' exhausted, try again tomorrow.", "Warning", 1);
  3486.         }
  3487.  
  3488.         # Create exclude file
  3489.        $excludeFile = "{$backupDir}exclude.txt";
  3490.         $excludes = ["Backup", "Log", "Deprecated", "vendor", "node_modules"];
  3491.  
  3492.         f($excludeFile, "write", implode("\n", $excludes));
  3493.  
  3494.         # Change to root directory and create tar
  3495.        $currentDir = getcwd();
  3496.         chdir(_node_project("path"));
  3497.  
  3498.         $shTarName = escapeshellarg($tarSavePath);
  3499.         $shExFile = escapeshellarg($excludeFile);
  3500.  
  3501.         $cmd = "tar -czf {$shTarName} --exclude-from={$shExFile} --transform='s,^\.,,' . 2>&1";
  3502.         exec($cmd, $output, $returnCode);
  3503.  
  3504.         chdir($currentDir);
  3505.         unlink($excludeFile);
  3506.  
  3507.         if ($returnCode === 0) {
  3508.             $size = filesize($tarSavePath);
  3509.             exec("tar -tzf " . escapeshellarg($tarSavePath) . " 2>/dev/null | wc -l", $fileCountOutput, $fcReturnCode);
  3510.             $fileCount = $fcReturnCode === 0 && isset($fileCountOutput[0]) && is_numeric($fileCountOutput[0]) ? (int) $fileCountOutput[0] : 0;
  3511.  
  3512.             return 0;
  3513.         }
  3514.  
  3515.         return r("Failed to create backup. Try installing tar or check permissions.\nError: " . implode("\n", array_slice($output, 0, 3)), "Error", 2);
  3516.     }
  3517.  
  3518.     if (str_starts_with($args[0], "deprecate")) {
  3519.         $structure = _node_argex($args, 1, 1);
  3520.         $filename = _node_argex($args, 2);
  3521.  
  3522.         if (!empty($structure) && !empty($filename)) {
  3523.             if ($path = _node_spath($structure)) {
  3524.                 $fromPathBase = _node_project("path") . $path . D . $filename;
  3525.                 $fFl = glob("{$fromPathBase}.*");
  3526.  
  3527.                 if (empty($fFl)) {
  3528.                     f(":rollback");
  3529.                     return r("Cannot deprecate <{$filename}>, no file exists in <{$structure}>.", "Warning", 1);
  3530.                 }
  3531.  
  3532.                 while (!empty($fFl)) {
  3533.                     # This extension.
  3534.                    $ext = array_last(explode(".", array_shift($fFl)));
  3535.  
  3536.                     # Move this file
  3537.                    $fromPath = "{$fromPathBase}.{$ext}";
  3538.  
  3539.                     # Create path in deprecations if not set.
  3540.                    $mkPath = $pathmake("Deprecated" . D . $path);
  3541.                     $toPath = "{$mkPath}{$filename}_" . time() . ".{$ext}";
  3542.  
  3543.                     # Copy to deprecated folder.
  3544.                    f($fromPath, "copy", $toPath);
  3545.                 }
  3546.                 return 0;
  3547.             }
  3548.             return r("Struct: invalid structure <{$structure}>", "Error", 2);
  3549.         }
  3550.         return r("Struct: provide both arguments <structure> and <name>", "Info", 1);
  3551.     }
  3552.  
  3553.     if (str_starts_with($args[0], "delete")) {
  3554.         $structure = _node_argex($args, 1, 1);
  3555.         $filename = _node_argex($args, 2);
  3556.  
  3557.         if (!empty($structure) && !empty($filename)) {
  3558.             if ($path = _node_spath($structure)) {
  3559.                 $fromPathBase = _node_project("path") . $path . D . $filename;
  3560.                 $fFl = glob("{$fromPathBase}.*");
  3561.  
  3562.                 if (empty($fFl)) {
  3563.                     f(":rollback");
  3564.                     return r("Cannot delete <{$filename}>, no file exists in <{$structure}>.", "Warning", 1);
  3565.                 }
  3566.  
  3567.                 // Create deletion manifest entry
  3568.                 $deletionId = time() . "_" . bin2hex(random_bytes(4));
  3569.                 $timestamp = time();
  3570.                 $manifestEntry = [
  3571.                     "id" => $deletionId,
  3572.                     "timestamp" => $timestamp,
  3573.                     "structure" => $structure,
  3574.                     "original_filename" => $filename,
  3575.                     "original_path" => $path,
  3576.                     // System metadata
  3577.                     "system" => [
  3578.                         "user" => function_exists("posix_getuid") ? posix_getuid() : null,
  3579.                         "group" => function_exists("posix_getgid") ? posix_getgid() : null,
  3580.                         "process_id" => getmypid(),
  3581.                         "hostname" => gethostname(),
  3582.                         "php_version" => PHP_VERSION,
  3583.                     ],
  3584.                     "files" => [],
  3585.                     "docs" => null,
  3586.                     "unit_tests" => null,
  3587.                 ];
  3588.  
  3589.                 while (!empty($fFl)) {
  3590.                     # This extension.
  3591.                    $ext = array_last(explode(".", array_shift($fFl)));
  3592.  
  3593.                     # Move this file
  3594.                    $fromPath = "{$fromPathBase}.{$ext}";
  3595.  
  3596.                     # Create path in deprecations if not set.
  3597.                    $mkPath = $pathmake("Deleted" . D . $path);
  3598.                     $toFilename = "{$filename}_{$deletionId}.{$ext}";
  3599.                     $toPath = "{$mkPath}{$toFilename}";
  3600.  
  3601.                     # Move primary resource to deleted folder.
  3602.                    f($fromPath, "move", $toPath);
  3603.                     _node_gitignore($fromPath, "delete");
  3604.  
  3605.                     # Store in manifest
  3606.                    $manifestEntry["files"][] = [
  3607.                         "original" => $path . D . $filename . ".{$ext}",
  3608.                         "deleted" => "Deleted" . D . $path . D . $toFilename,
  3609.                         "extension" => $ext,
  3610.                     ];
  3611.                 }
  3612.  
  3613.                 # Move documentations to deleted folder
  3614.                $docFilename = str_replace(D, "_", $structure) . "_{$filename}";
  3615.                 $docPath = str_replace([D . $path . D, D . $filename], [D . "Quality" . D . "Docs" . D, D . $docFilename], $fromPathBase) . ".md";
  3616.  
  3617.                 if (file_exists($docPath)) {
  3618.                     $deletedDocFilename = "{$docFilename}_{$deletionId}.md";
  3619.                     $deletedDocPath = $pathmake("Deleted" . D . "Quailty" . D . "Docs") . $deletedDocFilename;
  3620.                     f($docPath, "move", $deletedDocPath);
  3621.                     _node_gitignore($docPath, "delete");
  3622.  
  3623.                     $manifestEntry["docs"] = [
  3624.                         "original" => str_replace(_node_project("path"), "", $docPath),
  3625.                         "deleted" => "Deleted" . D . "Quality" . D . "Docs" . D . $deletedDocFilename,
  3626.                     ];
  3627.                 }
  3628.  
  3629.                 # Move unit tests to deleted folder
  3630.                $pureName = $filename;
  3631.                 foreach (struct(":declarations") as $declaration) {
  3632.                     $decl = ucfirst($declaration);
  3633.                     if (str_ends_with($filename, $decl)) {
  3634.                         $pureName = substr($filename, 0, strpos($filename, $decl));
  3635.                         unset($decl);
  3636.                         unset($declaration);
  3637.                         break;
  3638.                     }
  3639.                 }
  3640.  
  3641.                 $unitName = str_replace(D, "_", $structure) . "_{$pureName}Class";
  3642.                 $unitPath = struct(":structure:path", "Unit") . D . $unitName;
  3643.                 $unitFile = _node_project("path") . "{$unitPath}.php";
  3644.                 if (file_exists($unitFile)) {
  3645.                     $pathmake("Deleted" . D . struct(":structure:path", "Unit"));
  3646.                     $deletedUnitFilename = "{$unitName}_{$deletionId}.php";
  3647.                     $deletedUnitPath = _node_project("path") . "Deleted" . D . struct(":structure:path", "Unit") . D . $deletedUnitFilename;
  3648.                     f(_node_project("path") . $unitFile, "move", $deletedUnitPath);
  3649.                     _node_gitignore(_node_project("path") . $unitFile, "delete");
  3650.  
  3651.                     $manifestEntry["unit_tests"] = [
  3652.                         "original" => $unitFile,
  3653.                         "deleted" => "Deleted" . D . struct(":structure:path", "Unit") . D . $deletedUnitFilename,
  3654.                     ];
  3655.                 }
  3656.  
  3657.                 # Add to shared manifest file
  3658.                $manifestFile = _node_project("path") . "Deleted" . D . "files.json";
  3659.  
  3660.                 # Load existing manifests or create empty array
  3661.                $manifests = [];
  3662.                 if (file_exists($manifestFile)) {
  3663.                     $existingData = file_get_contents($manifestFile);
  3664.                     if (!empty($existingData)) {
  3665.                         $manifests = json_decode($existingData, true);
  3666.                         if (!is_array($manifests)) {
  3667.                             $manifests = [];
  3668.                         }
  3669.                     }
  3670.                 }
  3671.  
  3672.                 # Add new manifest entry at the beginning (most recent first)
  3673.                array_unshift($manifests, $manifestEntry);
  3674.  
  3675.                 # Save back to file
  3676.                $pathmake(dirname($manifestFile));
  3677.                 file_put_contents($manifestFile, json_encode($manifests, JSON_PRETTY_PRINT));
  3678.  
  3679.                 # All deletions done.
  3680.                return 0;
  3681.             }
  3682.             return r("Struct: invalid structure <{$structure}>", "Error", 2);
  3683.         }
  3684.         return r("Struct: provide both arguments <structure> and <name>", "Info", 1);
  3685.     }
  3686.  
  3687.     if (str_starts_with($args[0], "restore")) {
  3688.         $structure = _node_argex($args, 1, 1);
  3689.         $filename = _node_argex($args, 2);
  3690.  
  3691.         if (!empty($structure) && !empty($filename)) {
  3692.             # Load manifests
  3693.            $manifestFile = _node_project("path") . "Deleted" . D . "files.json";
  3694.             $manifests = [];
  3695.  
  3696.             if (file_exists($manifestFile)) {
  3697.                 $data = file_get_contents($manifestFile);
  3698.                 if (!empty($data)) {
  3699.                     $manifests = json_decode($data, true);
  3700.                     if (!is_array($manifests)) {
  3701.                         $manifests = [];
  3702.                     }
  3703.                 }
  3704.             }
  3705.  
  3706.             if (empty($manifests)) {
  3707.                 return r("No deletions found for <{$filename}> in structure <{$structure}>", "Warning", 1);
  3708.             }
  3709.  
  3710.             # Find the most recent manifest for this structure/filename
  3711.            $manifestToRestore = null;
  3712.             $manifestIndex = null;
  3713.  
  3714.             foreach ($manifests as $index => $manifest) {
  3715.                 if ($manifest["structure"] === $structure && $manifest["original_filename"] === $filename) {
  3716.                     $manifestToRestore = $manifest;
  3717.                     $manifestIndex = $index;
  3718.                     break; // First match is most recent due to array_unshift in delete
  3719.                 }
  3720.             }
  3721.  
  3722.             if (!$manifestToRestore) {
  3723.                 return r("No deletion found for <{$filename}> in structure <{$structure}>", "Warning", 1);
  3724.             }
  3725.  
  3726.             # Restore main files
  3727.            foreach ($manifestToRestore["files"] as $fileInfo) {
  3728.                 $fromPath = _node_project("path") . $fileInfo["deleted"];
  3729.                 $toPath = _node_project("path") . $fileInfo["original"];
  3730.  
  3731.                 # Ensure target directory exists
  3732.                $pathmake(dirname($toPath));
  3733.  
  3734.                 # Move file back
  3735.                if (file_exists($fromPath)) {
  3736.                     f($fromPath, "move", $toPath);
  3737.                     _node_gitignore($toPath, "write");
  3738.                 }
  3739.             }
  3740.  
  3741.             # Restore documentation
  3742.            if ($manifestToRestore["docs"]) {
  3743.                 $fromPath = _node_project("path") . $manifestToRestore["docs"]["deleted"];
  3744.                 $toPath = _node_project("path") . $manifestToRestore["docs"]["original"];
  3745.  
  3746.                 $pathmake(dirname($toPath));
  3747.                 if (file_exists($fromPath)) {
  3748.                     f($fromPath, "move", $toPath);
  3749.                     _node_gitignore($toPath, "write");
  3750.                 }
  3751.             }
  3752.  
  3753.             # Restore unit tests
  3754.            if ($manifestToRestore["unit_tests"]) {
  3755.                 $fromPath = _node_project("path") . $manifestToRestore["unit_tests"]["deleted"];
  3756.                 $toPath = _node_project("path") . $manifestToRestore["unit_tests"]["original"];
  3757.  
  3758.                 $pathmake(dirname($toPath));
  3759.                 if (file_exists($fromPath)) {
  3760.                     f($fromPath, "move", $toPath);
  3761.                     _node_gitignore($toPath, "write");
  3762.                 }
  3763.             }
  3764.  
  3765.             # Remove manifest entry from array
  3766.            array_splice($manifests, $manifestIndex, 1);
  3767.  
  3768.             # Save updated manifests back to file (or delete file if empty)
  3769.            if (empty($manifests)) {
  3770.                 if (file_exists($manifestFile)) {
  3771.                     unlink($manifestFile);
  3772.                 }
  3773.             } else {
  3774.                 file_put_contents($manifestFile, json_encode($manifests, JSON_PRETTY_PRINT));
  3775.             }
  3776.  
  3777.             # All restorations done.
  3778.            return 0;
  3779.         }
  3780.         return r("Struct: provide both arguments <structure> and <name>", "Info", 1);
  3781.     }
  3782.  
  3783.     # Nothing happened.
  3784.    return 0;
  3785. }
  3786.  
  3787. function _node_struct_build_keys(string $projectPath): array
  3788. {
  3789.     // Trigger struct() so caches are warm, then return the build-layer keys.
  3790.     struct(":keys");
  3791.     // Re-enter cleanly by calling the same internal logic.
  3792.     $nodeJson = _node_migrate_load(rtrim($projectPath, D) . D . "node.json");
  3793.     if (empty($nodeJson["build"])) {
  3794.         return [];
  3795.     }
  3796.     $buildDef = _node_build_load_merged($nodeJson["build"]);
  3797.     return !empty($buildDef["structure"]) ? _node_struct_flatten($buildDef["structure"]) : [];
  3798. }
  3799. # struct end
  3800.  
  3801. # write begin dev
  3802. function w(...$args): mixed
  3803. {
  3804.     # Filter args.
  3805.    $args = array_filter($args);
  3806.  
  3807.     if (empty($args)) {
  3808.         $h = [];
  3809.         $h[] = "w <structure> <name> <?type> to open new structure resource for writing.";
  3810.         $h[] = "w in <?code> opens STDIN at caret position to append in between source.";
  3811.         $h[] = "w mv <line> <target> Moves line to below or above target.";
  3812.         $h[] = "w save to save current file.";
  3813.         $h[] = "w close to close current file.";
  3814.         $h[] = "w ln <n> <?str> set caret at line, to beginning of optional <str>.";
  3815.         $h[] = "w at <str/[home/end]> caret at first matched <str> from current caret position.";
  3816.         $h[] = "w up <str/[home/end]> same as at but matching backwards from caret.";
  3817.         $h[] = "w sel <n/str/[w/end/ln/body/all]> selects from <n> chars or until matched <str> or given [command].";
  3818.         $h[] = "w del <?space separated line numbers> removes lines or current selection.";
  3819.         $h[] = "w tab <ln> <ln> <ln> ... prepends tabulation to given line numbers or removes on negative number.";
  3820.         $h[] = "w c adds selection or line in buffer.";
  3821.         $h[] = "w x adds selection or line in buffer and removes it.";
  3822.         $h[] = "w v <?n> pastes buffer <n> or last buffer if <n> not set.";
  3823.         $h[] = "w buffer shows the buffer.";
  3824.         $h[] = "w z undo's last action (moves pointer one step down).";
  3825.         $h[] = "w r redo's one action (moves pointer one step up).";
  3826.         $h[] = "w backup <?n> <?[restore]> shows <n'th> step up in backup array or restores it. Or number of backups.";
  3827.         $h[] = "w focus <[phase/section/section env]> hides all code outside of focus. On mismatch drops focus.";
  3828.         $h[] = "w fold <?[all/open]> folds/unfolds current declaration or [command].";
  3829.         $h[] = "w find <str> counts occurs and selects first from caret position.";
  3830.         $h[] = "w replace <old> <new> replaces all matches within file.";
  3831.         $h[] = "w supersade <old> <new> replaces all matches by find within entire codebase.";
  3832.         $h[] = "w namespace <name> calls 'struct move <structre> <fn> <name>' and refocuses w session.";
  3833.         $h[] = "w lint <?[w/end/ln/body/all]> passes code under given [command] to lint.";
  3834.         $h[] = "w run <?[w/end/ln/body/all]> passes code under given [command] to php -r ''.";
  3835.         $h[] = "w test <?structure> finds all or <structure> tests by opened file <name> and runs them.";
  3836.         $undoOf = ["in", "mv", "replace", "namespace", "rename", "del", "tab", "c", "x", "v", "r"];
  3837.         # keep track of undo history: .
  3838.  
  3839.         return "Writing tool, use:\n- " . implode("\n- ", $h) . "\nUndo history on: " . implode(", ", $undoOf);
  3840.     }
  3841.  
  3842.     # Three lines up and 3 lines down will be shown from line at caret position.
  3843.    # If caret is at line 0 then 6 lines down will be shown, when caret is at last line
  3844.    # then 6 lines before it will be shown.
  3845.    $lineRange = 5;
  3846.  
  3847.     # Editor indentation spaces
  3848.    $indentSpc = 4;
  3849.  
  3850.     # How many cuts and copies will be stored in buffer?
  3851.    $bufferHistorySize = 2;
  3852.  
  3853.     # Supported filetypes for editin
  3854.    $supportedFiletypes = [".php", ".html", ".md", "Boilerplate"];
  3855.  
  3856.     $focusedFn = h("w.focused.filename", sys_get_temp_dir() . D . "w_focused");
  3857.     $focusedMemory = file_exists($focusedFn)
  3858.         ? (object) json_decode(f($focusedFn, "read", null, false), false)
  3859.         : (object) [
  3860.             "structure" => "",
  3861.             "name" => "",
  3862.             "type" => "",
  3863.             "path" => "",
  3864.             "caret" => (object) [
  3865.                 "line" => 0,
  3866.                 "char" => 0,
  3867.                 "selected_line" => null, // No selection made
  3868.                 "selected_char" => null,
  3869.             ],
  3870.             "contents" => [], // Temporary / unsaved contents of this file.
  3871.             "modifications" => [],
  3872.             "pointer" => 0, // Undopointer within modifications array (point to last stored index).
  3873.             "buffer" => [],
  3874.         ];
  3875.     $saveFocus = fn($msg, $mem = null) => f($focusedFn, "write", json_encode($mem ?? $focusedMemory, JSON_PRETTY_PRINT)) /* && var_dump("{$msg} => ", $focusedMemory->contents) */;
  3876.  
  3877.     # Buffer management.
  3878.    $record = function () use (&$focusedMemory, $bufferHistorySize) {
  3879.         $focusedMemory->modifications = array_slice($focusedMemory->modifications, 0, $focusedMemory->pointer + 1);
  3880.         $focusedMemory->modifications[] = $focusedMemory->contents;
  3881.  
  3882.         // Increment the pointer to the new empty state
  3883.         $focusedMemory->pointer = count($focusedMemory->modifications); // - 1;
  3884.  
  3885.         if (count($focusedMemory->modifications) > $bufferHistorySize) {
  3886.             array_shift($focusedMemory->modifications);
  3887.             $focusedMemory->pointer = max(0, $focusedMemory->pointer - 1);
  3888.         }
  3889.     };
  3890.  
  3891.     $getSelection = function () use ($focusedMemory) {
  3892.         if ($focusedMemory->caret->selected_line !== null) {
  3893.             $sL = $focusedMemory->caret->selected_line;
  3894.             $sC = $focusedMemory->caret->selected_char;
  3895.             $eL = $focusedMemory->caret->line;
  3896.             $eC = $focusedMemory->caret->char;
  3897.  
  3898.             // Normalize: Start must be physically before End
  3899.             if ($sL > $eL || ($sL === $eL && $sC > $eC)) {
  3900.                 [$sL, $eL, $sC, $eC] = [$eL, $sL, $eC, $sC];
  3901.             }
  3902.  
  3903.             if ($sL === $eL) {
  3904.                 return [substr($focusedMemory->contents[$sL], $sC, $eC - $sC)];
  3905.             }
  3906.  
  3907.             $result = [substr($focusedMemory->contents[$sL], $sC)];
  3908.             for ($i = $sL + 1; $i < $eL; $i++) {
  3909.                 $result[] = $focusedMemory->contents[$i];
  3910.             }
  3911.             $result[] = substr($focusedMemory->contents[$eL], 0, $eC);
  3912.             return $result;
  3913.         }
  3914.         return [$focusedMemory->contents[$focusedMemory->caret->line]];
  3915.     };
  3916.  
  3917.     if ($args[0] === ":buffer") {
  3918.         return $focusedMemory->buffer;
  3919.     }
  3920.  
  3921.     # Dump focused data if any
  3922.    if ($args[0] === ":focused") {
  3923.         return $focusedMemory;
  3924.     }
  3925.  
  3926.     if ($args[0] === ":opened") {
  3927.         return !empty($focusedMemory->path);
  3928.     }
  3929.  
  3930.     # Display current view on opened file.
  3931.    if ($args[0] === ":view") {
  3932.         # If there's no file opened, return en empty view.
  3933.        if (!w(":opened")) {
  3934.             return "";
  3935.         }
  3936.  
  3937.         # Lines
  3938.        $totalLines = count($focusedMemory->contents);
  3939.  
  3940.         $targetCount = $lineRange * 2;
  3941.         $startLine = max(0, $focusedMemory->caret->line - $lineRange);
  3942.         $endLine = min($totalLines - 1, $startLine + $targetCount);
  3943.         $selLine = $focusedMemory->caret->selected_line;
  3944.         $selChar = $focusedMemory->caret->selected_char;
  3945.  
  3946.         if ($endLine - $startLine < $targetCount) {
  3947.             $startLine = max(0, $endLine - $targetCount);
  3948.         }
  3949.  
  3950.         # Length of padding
  3951.        $lnLen = strlen((string) $totalLines);
  3952.         $lnCaret = "# ";
  3953.  
  3954.         # Fileinfo
  3955.        $relativePath = substr($focusedMemory->path, strlen(_node_project("path")));
  3956.         $structure = $focusedMemory->structure;
  3957.         $name = $focusedMemory->name;
  3958.         $type = $focusedMemory->type;
  3959.         $char = $focusedMemory->caret->char;
  3960.  
  3961.         $modified = empty($focusedMemory->modifications) ? "" : "*";
  3962.         $lnLen += strlen($lnCaret);
  3963.  
  3964.         $r = "\n{$relativePath}{$modified} | {$structure} {$name} {$type}\n";
  3965.         foreach ($focusedMemory->contents as $ln => $line) {
  3966.             if ($ln >= $startLine && $ln <= $endLine) {
  3967.                 $focusedLine = $ln == $focusedMemory->caret->line;
  3968.                 if ($focusedLine || ($selLine !== null && ($selLine <= $ln && $focusedMemory->caret->line >= $ln))) {
  3969.                     $selStart = "\033[44m";
  3970.                     $caretStart = "\033[7m";
  3971.                     $reset = "\033[0m";
  3972.  
  3973.                     if ($selLine !== null && $selLine <= $ln && $ln !== $focusedMemory->caret->line) {
  3974.                         $line = "{$selStart}{$line}{$reset}";
  3975.                     } elseif ($selLine !== null && $selLine == $ln) {
  3976.                         $start = $selChar;
  3977.                         $length = $char - $selChar;
  3978.  
  3979.                         $line = substr_replace($line, $selStart . substr($line, $start, $length) . $reset, $start, $length);
  3980.                     } else {
  3981.                         $p = min($char, strlen($line));
  3982.                         $charToInvert = $line[$p] ?? " ";
  3983.                         $line = substr_replace($line, "{$caretStart}{$charToInvert}{$reset}", $p, 1);
  3984.                     }
  3985.                 } else {
  3986.                     # $line = preg_replace('/(\$\w+)/', "\033[33m$1\033[0m", $line); # Variables: yellow
  3987.                    $keywords = [
  3988.                         "__halt_compiler",
  3989.                         "__CLASS__",
  3990.                         "__DIR__",
  3991.                         "__FILE__",
  3992.                         "__FUNCTION__",
  3993.                         "__LINE__",
  3994.                         "__METHOD__",
  3995.                         "__NAMESPACE__",
  3996.                         "__TRAIT__",
  3997.                         "abstract",
  3998.                         "and",
  3999.                         "array",
  4000.                         "as",
  4001.                         "bool",
  4002.                         "break",
  4003.                         "callable",
  4004.                         "case",
  4005.                         "catch",
  4006.                         "class",
  4007.                         "clone",
  4008.                         "const",
  4009.                         "continue",
  4010.                         "declare",
  4011.                         "default",
  4012.                         "die",
  4013.                         "do",
  4014.                         "echo",
  4015.                         "else",
  4016.                         "elseif",
  4017.                         "empty",
  4018.                         "enddeclare",
  4019.                         "endfor",
  4020.                         "endforeach",
  4021.                         "endif",
  4022.                         "endswitch",
  4023.                         "endwhile",
  4024.                         "enum",
  4025.                         "eval",
  4026.                         "exit",
  4027.                         "extends",
  4028.                         "false",
  4029.                         "final",
  4030.                         "finally",
  4031.                         "fn",
  4032.                         "for",
  4033.                         "foreach",
  4034.                         "function",
  4035.                         "global",
  4036.                         "goto",
  4037.                         "if",
  4038.                         "implements",
  4039.                         "include",
  4040.                         "include_once",
  4041.                         "instanceof",
  4042.                         "insteadof",
  4043.                         "interface",
  4044.                         "isset",
  4045.                         "list",
  4046.                         "match",
  4047.                         "namespace",
  4048.                         "new",
  4049.                         "null",
  4050.                         "or",
  4051.                         "print",
  4052.                         "private",
  4053.                         "protected",
  4054.                         "public",
  4055.                         "readonly",
  4056.                         "require",
  4057.                         "require_once",
  4058.                         "return",
  4059.                         "self",
  4060.                         "static",
  4061.                         "switch",
  4062.                         "this",
  4063.                         "throw",
  4064.                         "trait",
  4065.                         "true",
  4066.                         "try",
  4067.                         "unset",
  4068.                         "use",
  4069.                         "var",
  4070.                         "while",
  4071.                         "xor",
  4072.                         "yield",
  4073.                         "yield from",
  4074.                     ];
  4075.                     $patterns = [
  4076.                         "comment" => '(?:\/\/.*$|#.*$)', // Gray
  4077.                         "string" => '(?:"(?:\\\\.|[^"])*"|\'(?:\\\\.|[^\'])*\')', // Green (handles escaped quotes)
  4078.                         "variable" => '(?:\$\w+)', // Yellow
  4079.                         "keyword" => "\b(?:" . implode("|", array_map("preg_quote", $keywords)) . ")\b", // Magenta
  4080.                         "const" => "\b(?:true|false|null)\b", // Cyan
  4081.                     ];
  4082.                     $fullPattern = "/(" . implode(")|(", $patterns) . ")/i";
  4083.                     $line = preg_replace_callback(
  4084.                         $fullPattern,
  4085.                         fn($m) => match (true) {
  4086.                             !empty($m[1]) => "\033[90m{$m[1]}\033[0m", // Comment
  4087.                             !empty($m[2]) => "\033[32m{$m[2]}\033[0m", // String
  4088.                             !empty($m[3]) => "\033[33m{$m[3]}\033[0m", // Variable
  4089.                             !empty($m[4]) => "\033[35m{$m[4]}\033[0m", // Keyword
  4090.                             !empty($m[5]) => "\033[36m{$m[5]}\033[0m", // Constant
  4091.                             default => $m[0],
  4092.                         },
  4093.                         $line,
  4094.                     );
  4095.                 }
  4096.  
  4097.                 # Leading spaces of an empty line (Keep after syntax highlighting)
  4098.                if (empty(trim($line))) {
  4099.                     // strip_tags or similar to ignore ANSI
  4100.                     $line = preg_replace_callback("/^(\h*)/", fn($m) => str_repeat("\033[90m·\033[0m", strlen($m[1])), $line);
  4101.                 }
  4102.                 $ln += 1; # Display from 1;
  4103.                $r .= str_repeat(" ", $lnLen - strlen((string) $ln) - ($focusedLine ? strlen($lnCaret) : 0)) . ($focusedLine ? $lnCaret : "") . "\033[90m{$ln} |\033[0m {$line}\n";
  4104.             }
  4105.         }
  4106.  
  4107.         return $r;
  4108.     }
  4109.  
  4110.     # Starting to type code.
  4111.    if (str_starts_with($args[0], "in") && w(":opened")) {
  4112.         # Take user input.
  4113.        $input = str_replace("\t", str_repeat(" ", (int) $indentSpc), _node_argex($args, 1) ?: file_get_contents("php://stdin"));
  4114.  
  4115.         if ($focusedMemory->caret->selected_line !== null) {
  4116.             # Delete selection & reload focused file.
  4117.            w("del");
  4118.             $focusedMemory = (object) json_decode(f($focusedFn, "read", null, false), false);
  4119.         }
  4120.         $ln = $focusedMemory->caret->line;
  4121.  
  4122.         # Add to undo before insertion.
  4123.        $record();
  4124.  
  4125.         $inputLines = explode("\n", $input);
  4126.         $inputLineCount = count($inputLines);
  4127.  
  4128.         $prefix = substr($focusedMemory->contents[$ln], 0, $focusedMemory->caret->char);
  4129.         $suffix = substr($focusedMemory->contents[$ln], $focusedMemory->caret->char);
  4130.  
  4131.         if ($inputLineCount === 1) {
  4132.             $focusedMemory->contents[$ln] = "{$prefix}{$input}{$suffix}";
  4133.             $focusedMemory->caret->char += strlen($input);
  4134.         } else {
  4135.             $newLines = $inputLines;
  4136.             $newLines[0] = "{$prefix}{$newLines[0]}";
  4137.  
  4138.             $lastIdx = $inputLineCount - 1;
  4139.             $newLines[$lastIdx] .= $suffix;
  4140.  
  4141.             array_splice($focusedMemory->contents, (int) $ln, 1, $newLines);
  4142.  
  4143.             $focusedMemory->caret->line += $lastIdx;
  4144.             $focusedMemory->caret->char = strlen(array_last($newLines)) - strlen($suffix);
  4145.         }
  4146.         return $saveFocus("in", $focusedMemory);
  4147.     }
  4148.  
  4149.     if (str_starts_with($args[0], "mv") && w(":opened")) {
  4150.         $lineIdx = (int) _node_argex($args, 1, 1) - 1;
  4151.         $targetIdx = (int) _node_argex($args, 2);
  4152.  
  4153.         if (isset($focusedMemory->contents[$lineIdx])) {
  4154.             $record();
  4155.             $movingLine = array_splice($focusedMemory->contents, $lineIdx, 1)[0];
  4156.  
  4157.             if ($lineIdx < ($realTarget = abs($targetIdx) - 1)) {
  4158.                 $realTarget--;
  4159.             }
  4160.             $insertionPoint = $targetIdx < 0 ? $realTarget : $realTarget + 1;
  4161.  
  4162.             array_splice($focusedMemory->contents, $insertionPoint, 0, $movingLine);
  4163.  
  4164.             $focusedMemory->caret->line = $insertionPoint;
  4165.         }
  4166.  
  4167.         return $saveFocus("mv");
  4168.     }
  4169.  
  4170.     if ($args[0] === "save" && w(":opened")) {
  4171.         $source = implode("\n", $focusedMemory->contents);
  4172.         $errors = lint($source);
  4173.         if (empty($errors)) {
  4174.             foreach ($supportedFiletypes as $ext) {
  4175.                 if (substr($focusedMemory->path, strlen($ext) * -1) === $ext) {
  4176.                     $backupFn = str_replace($ext, ".backup.json", $focusedMemory->path);
  4177.  
  4178.                     # Initialize source backups or load existing ones.
  4179.                    if (!file_exists($backupFn)) {
  4180.                         $backupArray = [f($focusedMemory->path, "read")];
  4181.                         f($backupFn, "write", json_encode($backupArray));
  4182.                     } else {
  4183.                         $backupArray = json_decode(f($backupFn, "read"), true);
  4184.                     }
  4185.  
  4186.                     # Add current source to backups if it differs.
  4187.                    if (array_last($backupArray) !== $source) {
  4188.                         $backupArray[] = $source;
  4189.                         f($backupFn, "write", json_encode($backupArray));
  4190.                     }
  4191.  
  4192.                     # Save edited source.
  4193.                    return f($focusedMemory->path, "write", $source);
  4194.                 }
  4195.             }
  4196.         }
  4197.         return "Not saving file containing errors.\n\n" . implode("\n", $errors);
  4198.     }
  4199.  
  4200.     if ($args[0] === "close") {
  4201.         $part = explode("_", $focusedMemory->name);
  4202.         $name = array_pop($part);
  4203.         $structure = implode(D, $part);
  4204.  
  4205.         return !isset($args[1]) || $args[1] === true || empty($focusedMemory->modifications)
  4206.             ? (file_exists($focusedFn)
  4207.                 ? (int) (unlink($focusedFn) && (strpos($focusedMemory->path, "/Quality/Test/") !== false ? w($structure, $name, "Class") : true))
  4208.                 : 0)
  4209.             : /* Autodiscard = false and focused memory had modifications */ false;
  4210.     }
  4211.  
  4212.     # Internal variant for subsequent calls.
  4213.    if (str_starts_with($args[0], ":ln") && w(":opened")) {
  4214.         $ln = _node_argex($args, 1, 1) - 1;
  4215.         $str = _node_argex($args, 2);
  4216.         return [
  4217.             $ln,
  4218.             array_key_exists($ln, $focusedMemory->contents)
  4219.                 ? (in_array($str, ["end", "homde"])
  4220.                     ? ($str === "end"
  4221.                         ? strlen($focusedMemory->contents[$ln])
  4222.                         : 0)
  4223.                     : (int) strpos($focusedMemory->contents[$ln], $str))
  4224.                 : 0,
  4225.         ];
  4226.     }
  4227.  
  4228.     # Jumping to line.
  4229.    if (str_starts_with($args[0], "ln") && w(":opened")) {
  4230.         $ln = _node_argex($args, 1, 1);
  4231.         $str = _node_argex($args, 2);
  4232.  
  4233.         $pos = w(":ln {$ln} {$str}");
  4234.         $focusedMemory->caret->line = $pos[0];
  4235.         $focusedMemory->caret->char = $pos[1];
  4236.  
  4237.         return $saveFocus("ln");
  4238.     }
  4239.  
  4240.     # Jumping to char to the right.
  4241.    if ((str_starts_with($args[0], "at") || str_starts_with($args[0], "up")) && w(":opened")) {
  4242.         $str = _node_argex($args, 1);
  4243.  
  4244.         # Edge Jumps
  4245.        if (in_array($str, ["end", "home"])) {
  4246.             $focusedMemory->caret->char = $str === "home" ? 0 : strlen($focusedMemory->contents[$focusedMemory->caret->line]);
  4247.             return $saveFocus("at/up - end/home");
  4248.         }
  4249.  
  4250.         $line = $focusedMemory->contents[$focusedMemory->caret->line];
  4251.         $char = $focusedMemory->caret->char;
  4252.  
  4253.         $pos = str_starts_with($args[0], "at")
  4254.             ? (strpos($line, $str, min($char + 1, strlen($line) - 1)) ?:
  4255.             strpos($line, $str, 0))
  4256.             : (strrpos(substr($line, 0, max($char - 1, 0)), $str) ?:
  4257.             strrpos($line, $str));
  4258.  
  4259.         $focusedMemory->caret->char = $pos !== false ? $pos : $char;
  4260.  
  4261.         return $saveFocus("at/up");
  4262.     }
  4263.  
  4264.     if (str_starts_with($args[0], "sel") && w(":opened")) {
  4265.         $pointer = _node_argex($args, 1);
  4266.         $c = &$focusedMemory->caret;
  4267.         $lines = $focusedMemory->contents;
  4268.  
  4269.         if (empty($pointer)) {
  4270.             $c->selected_line = null;
  4271.             $c->selected_char = null;
  4272.             return $saveFocus("sel");
  4273.         }
  4274.  
  4275.         if (is_numeric($pointer)) {
  4276.             $c->selected_line = $c->line;
  4277.             $c->selected_char = $c->char;
  4278.             $c->char = min($c->char + (int) $pointer, strlen($lines[$c->line] ?? ""));
  4279.             return $saveFocus("sel <n>");
  4280.         }
  4281.  
  4282.         // Helper to finalize selection order (Start must be <= End)
  4283.         $setSel = function ($sL, $sC, $eL, $eC) use ($c, $saveFocus) {
  4284.             if ($sL < $eL || ($sL === $eL && $sC <= $eC)) {
  4285.                 $c->selected_line = $sL;
  4286.                 $c->selected_char = $sC;
  4287.                 $c->line = $eL;
  4288.                 $c->char = $eC;
  4289.             } else {
  4290.                 $c->selected_line = $eL;
  4291.                 $c->selected_char = $eC;
  4292.                 $c->line = $sL;
  4293.                 $c->char = $sC;
  4294.             }
  4295.             return $saveFocus("sel [command]");
  4296.         };
  4297.  
  4298.         switch ($pointer) {
  4299.             case "w":
  4300.                 $line = $lines[$c->line];
  4301.                 $left = substr($line, 0, $c->char);
  4302.                 preg_match('/[a-zA-Z0-9_]+$/', $left, $m1);
  4303.                 $start = $c->char - (isset($m1[0]) ? strlen($m1[0]) : 0);
  4304.  
  4305.                 $right = substr($line, $c->char);
  4306.                 preg_match("/^[a-zA-Z0-9_]+/", $right, $m2);
  4307.                 $end = $c->char + (isset($m2[0]) ? strlen($m2[0]) : 0);
  4308.                 return $setSel($c->line, $start, $c->line, $end);
  4309.  
  4310.             case "end":
  4311.                 $line = $lines[$c->line];
  4312.                 return $setSel($c->line, $c->char, $c->line, strlen($line));
  4313.  
  4314.             case "ln":
  4315.                 return $setSel($c->line, 0, $c->line, strlen($lines[$c->line]));
  4316.  
  4317.             case "body":
  4318.                 $openL = $c->line;
  4319.                 $openC = -1;
  4320.                 $stack = [];
  4321.                 $pairs = ["}" => "{", "]" => "[", ")" => "("];
  4322.                 $opp = ["{" => "}", "[" => "]", "(" => ")"];
  4323.  
  4324.                 for ($i = $c->line; $i >= 0; $i--) {
  4325.                     $text = $i === $c->line ? substr($lines[$i], 0, $c->char) : $lines[$i];
  4326.                     for ($j = strlen($text) - 1; $j >= 0; $j--) {
  4327.                         $char = $text[$j];
  4328.                         if (in_array($char, ["{", "[", "("])) {
  4329.                             $openL = $i;
  4330.                             $openC = $j;
  4331.                             break 2;
  4332.                         }
  4333.                     }
  4334.                 }
  4335.                 if ($openC === -1) {
  4336.                     return $saveFocus("sel [body] openC -1");
  4337.                 }
  4338.  
  4339.                 $targetOpen = $lines[$openL][$openC];
  4340.                 $targetClose = $opp[$targetOpen];
  4341.  
  4342.                 $depth = 0;
  4343.                 for ($i = $openL; $i < count($lines); $i++) {
  4344.                     $jStart = $i === $openL ? $openC + 1 : 0;
  4345.                     for ($j = $jStart; $j < strlen($lines[$i]); $j++) {
  4346.                         if ($lines[$i][$j] === $targetOpen) {
  4347.                             $depth++;
  4348.                         }
  4349.                         if ($lines[$i][$j] === $targetClose) {
  4350.                             if ($depth === 0) {
  4351.                                 return $setSel($openL, $openC, $i, $j + 1);
  4352.                             }
  4353.                             $depth--;
  4354.                         }
  4355.                     }
  4356.                 }
  4357.                 return $saveFocus("sel [body]");
  4358.  
  4359.             case "all":
  4360.                 $lastL = count($lines) - 1;
  4361.                 return $setSel(0, 0, $lastL, strlen($lines[$lastL]));
  4362.  
  4363.             default:
  4364.                 for ($i = $c->line; $i < count($lines); $i++) {
  4365.                     $text = $i === $c->line ? substr($lines[$i], $c->char) : $lines[$i];
  4366.                     $pos = strpos($text, $pointer);
  4367.                     if ($pos !== false) {
  4368.                         $actualChar = $i === $c->line ? $c->char + $pos + strlen($pointer) : $pos + strlen($pointer);
  4369.                         return $setSel($c->line, $c->char, $i, $actualChar);
  4370.                     }
  4371.                 }
  4372.         }
  4373.         // return $saveFocus();
  4374.         return 0;
  4375.     }
  4376.  
  4377.     if (str_starts_with($args[0], "del") && w(":opened")) {
  4378.         $numbers = _node_argex($args, 1);
  4379.         $record();
  4380.  
  4381.         if (count($focusedMemory->modifications) > $bufferHistorySize) {
  4382.             array_shift($focusedMemory->modifications);
  4383.             $focusedMemory->caret->pointer--;
  4384.         }
  4385.  
  4386.         if (!empty($numbers) && !empty(($numbers = array_filter(explode(" ", $numbers), "is_numeric")))) {
  4387.             $numbers = array_map("intval", $numbers);
  4388.             rsort($numbers);
  4389.  
  4390.             foreach ($numbers as $n) {
  4391.                 $n -= 1;
  4392.                 if (isset($focusedMemory->contents[$n])) {
  4393.                     array_splice($focusedMemory->contents, $n, 1);
  4394.                 }
  4395.             }
  4396.  
  4397.             $focusedMemory->contents = array_values($focusedMemory->contents);
  4398.  
  4399.             $maxLine = count($focusedMemory->contents) - 1;
  4400.             if ($focusedMemory->caret->line > $maxLine) {
  4401.                 $focusedMemory->caret->line = max(0, $maxLine);
  4402.             }
  4403.             return $saveFocus("del <n> ...");
  4404.         }
  4405.  
  4406.         $selLine = $focusedMemory->caret->selected_line ?? null;
  4407.         $selChar = $focusedMemory->caret->selected_char ?? null;
  4408.         $curLine = $focusedMemory->caret->line;
  4409.         $curChar = $focusedMemory->caret->char;
  4410.  
  4411.         if ($selLine !== null) {
  4412.             $startL = $selLine;
  4413.             $startC = $selChar;
  4414.             $endL = $curLine;
  4415.             $endC = $curChar;
  4416.  
  4417.             $prefix = substr($focusedMemory->contents[$startL], 0, $startC);
  4418.             $suffix = substr($focusedMemory->contents[$endL], $endC);
  4419.  
  4420.             $linesToRemove = $endL - $startL + 1;
  4421.             array_splice($focusedMemory->contents, $startL, $linesToRemove, ["{$prefix}{$suffix}"]);
  4422.  
  4423.             $focusedMemory->caret->line = $startL;
  4424.             $focusedMemory->caret->char = $startC;
  4425.  
  4426.             $focusedMemory->caret->selected_line = null;
  4427.             $focusedMemory->caret->selected_char = null;
  4428.         } else {
  4429.             $ln = $focusedMemory->caret->line;
  4430.             $pos = $focusedMemory->caret->char;
  4431.             $lineCount = count($focusedMemory->contents);
  4432.             $currentLineLength = strlen($focusedMemory->contents[$ln]);
  4433.  
  4434.             if ($pos >= $currentLineLength && $ln < $lineCount - 1) {
  4435.                 $nextLine = $ln + 1;
  4436.                 $focusedMemory->contents[$ln] .= $focusedMemory->contents[$nextLine];
  4437.                 array_splice($focusedMemory->contents, $nextLine, 1);
  4438.             } elseif ($pos < $currentLineLength) {
  4439.                 $focusedMemory->contents[$ln] = substr($focusedMemory->contents[$ln], 0, $pos) . substr($focusedMemory->contents[$ln], $pos + 1);
  4440.             }
  4441.         }
  4442.         return $saveFocus("del");
  4443.     }
  4444.  
  4445.     if (str_starts_with($args[0], "tab") && w(":opened")) {
  4446.         if (!empty(($numbersRaw = _node_argex($args, 1)))) {
  4447.             if (!empty(($numbers = array_filter(explode(" ", $numbersRaw), "is_numeric")))) {
  4448.                 $focusedMemory->modifications = array_slice($focusedMemory->modifications, 0, $focusedMemory->pointer + 1);
  4449.                 $record();
  4450.                 $indentStr = str_repeat(" ", (int) $indentSpc);
  4451.  
  4452.                 foreach ($numbers as $n) {
  4453.                     $idx = abs((int) $n) - 1;
  4454.  
  4455.                     if (isset($focusedMemory->contents[$idx])) {
  4456.                         $line = $focusedMemory->contents[$idx];
  4457.  
  4458.                         if ((int) $n >= 0) {
  4459.                             $focusedMemory->contents[$idx] = "{$indentStr}{$line}";
  4460.                         } else {
  4461.                             if (str_starts_with($line, $indentStr)) {
  4462.                                 $focusedMemory->contents[$idx] = substr($line, strlen($indentStr));
  4463.                             } elseif (str_starts_with($line, " ")) {
  4464.                                 $focusedMemory->contents[$idx] = ltrim($line);
  4465.                             }
  4466.                         }
  4467.                     }
  4468.                 }
  4469.             }
  4470.         }
  4471.         return $saveFocus("tab");
  4472.     }
  4473.  
  4474.     if ((in_array($args[0], ["c", "x", "v", "buffer"]) || str_starts_with($args[0], "v")) && w(":opened")) {
  4475.         $cmd = _node_argex($args, 0, 1);
  4476.         $arg = _node_argex($args, 1);
  4477.  
  4478.         switch ($cmd) {
  4479.             case "c": // Copy
  4480.             case "x": // Cut
  4481.                 $focusedMemory->buffer[] = $getSelection();
  4482.                 if ($cmd === "x") {
  4483.                     if ($focusedMemory->caret->selected_line !== null) {
  4484.                         w("del");
  4485.                         $focusedMemory = (object) json_decode(f($focusedFn, "read", null, false), false);
  4486.                     } else {
  4487.                         array_splice($focusedMemory->contents, $focusedMemory->caret->line, 1);
  4488.                     }
  4489.                     $focusedMemory->caret->selected_char = null;
  4490.                     $focusedMemory->caret->selected_line = null;
  4491.                 }
  4492.                 break;
  4493.  
  4494.             case "v":
  4495.                 $idx = $arg !== null && is_numeric($arg) ? (int) $arg : count($focusedMemory->buffer) - 1;
  4496.                 if (isset($focusedMemory->buffer[$idx])) {
  4497.                     $content = implode("\n", $focusedMemory->buffer[$idx]);
  4498.                     w("in", $content);
  4499.                     $focusedMemory = (object) json_decode(f($focusedFn, "read", null, false), false);
  4500.                 }
  4501.                 break;
  4502.  
  4503.             case "buffer":
  4504.                 $r = "";
  4505.                 for ($i = count($focusedMemory->buffer) - 1; $i >= 0; $i--) {
  4506.                     $buff = $focusedMemory->buffer[$i];
  4507.                     $r .= "\n\033[93m{$i}[\033[0m" . implode("\n", $buff) . "\033[93m] \033[0m";
  4508.                 }
  4509.                 return "{$r}";
  4510.                 break;
  4511.         }
  4512.  
  4513.         return $saveFocus("c,x,v,buffer");
  4514.     }
  4515.  
  4516.     if ($args[0] === "z" && w(":opened")) {
  4517.         if ($focusedMemory->pointer > 0) {
  4518.             $focusedMemory->pointer--;
  4519.             $focusedMemory->contents = $focusedMemory->modifications[$focusedMemory->pointer];
  4520.         }
  4521.         return $saveFocus("z");
  4522.     }
  4523.  
  4524.     if ($args[0] === "r" && w(":opened")) {
  4525.         if ($focusedMemory->pointer < count($focusedMemory->modifications) - 1) {
  4526.             $focusedMemory->pointer++;
  4527.             $focusedMemory->contents = $focusedMemory->modifications[$focusedMemory->pointer];
  4528.         }
  4529.         return $saveFocus("r");
  4530.     }
  4531.  
  4532.     if (str_starts_with($args[0], "backup") && w(":opened")) {
  4533.         foreach ($supportedFiletypes as $ext) {
  4534.             if (substr($focusedMemory->path, strlen($ext) * -1) === $ext) {
  4535.                 $backupFn = str_replace($ext, ".backup.json", $focusedMemory->path);
  4536.  
  4537.                 $n = _node_argex($args, 1, 1);
  4538.                 $apply = _node_argex($args, 2, 1) === "restore"; // Boolean to state user wants to restore given backup.
  4539.  
  4540.                 $backups = file_exists($backupFn) ? json_decode(f($backupFn, "read"), true) : [];
  4541.  
  4542.                 if (empty($n)) {
  4543.                     return "Number of backups available: " . count($backups);
  4544.                 }
  4545.  
  4546.                 if (!array_key_exists((int) $n, $backups)) {
  4547.                     return "Backup {$n} not found.";
  4548.                 }
  4549.  
  4550.                 if ($apply) {
  4551.                     # Backup current state
  4552.                    $source = implode("\n", $focusedMemory->contents);
  4553.  
  4554.                     if (!empty($backups) && array_last($backups) !== $source) {
  4555.                         $backups[] = $source;
  4556.                         f($backupFn, "write", json_encode($backups, JSON_PRETTY_PRINT));
  4557.                     }
  4558.  
  4559.                     # Close editor
  4560.                    return f($focusedMemory->path, "write", $backups[$n]) && w("close");
  4561.                 }
  4562.                 return "\n" . $backups[$n];
  4563.             }
  4564.         }
  4565.     }
  4566.  
  4567.     # focus
  4568.    # fold
  4569.  
  4570.     if (str_starts_with($args[0], "find") && w(":opened")) {
  4571.         if (empty(($phrase = _node_argex($args, 1)))) {
  4572.             return 0;
  4573.         }
  4574.         $totalLines = count($focusedMemory->contents);
  4575.         $startL = $focusedMemory->caret->line;
  4576.         $startC = $focusedMemory->caret->char;
  4577.  
  4578.         for ($i = 0; $i < $totalLines; $i++) {
  4579.             $ln = ($startL + $i) % $totalLines;
  4580.             $lineContent = $focusedMemory->contents[$ln];
  4581.             $offset = $i === 0 ? $startC : 0;
  4582.  
  4583.             $pos = strpos($lineContent, $phrase, $offset);
  4584.             if ($pos !== false) {
  4585.                 $focusedMemory->caret->selected_line = $ln;
  4586.                 $focusedMemory->caret->selected_char = $pos;
  4587.  
  4588.                 $focusedMemory->caret->line = $ln;
  4589.                 $focusedMemory->caret->char = $pos + strlen($phrase);
  4590.                 $saveFocus("find");
  4591.                 break;
  4592.             }
  4593.         }
  4594.         return substr_count(implode("\n", $focusedMemory->contents), $phrase);
  4595.     }
  4596.  
  4597.     if (str_starts_with($args[0], "replace") && w(":opened")) {
  4598.         $old = _node_argex($args, 1, 1);
  4599.         $new = _node_argex($args, 2);
  4600.  
  4601.         if (empty($old) || empty($new)) {
  4602.             return "Provide <old> <new> without quotes, space separated.";
  4603.         }
  4604.         $record();
  4605.         $matches = w("find", $old);
  4606.         for ($i = 0; $i < $matches; $i++) {
  4607.             w("in", $new); // Saves the focused memory.
  4608.             $focusedMemory = (object) json_decode(f($focusedFn, "read", null, false), false);
  4609.             if (!w("find", $old)) {
  4610.                 break;
  4611.             }
  4612.         }
  4613.         return $matches;
  4614.     }
  4615.  
  4616.     # Yes, it does not require for any file to be opened.
  4617.    if (str_starts_with($args[0], "supersade")) {
  4618.         $old = _node_argex($args, 1, 1);
  4619.         $new = _node_argex($args, 2);
  4620.  
  4621.         if (empty($old) || empty($new)) {
  4622.             return "Provide <old> <new> without quotes, space separated to supersade all of: " . _node_project("name");
  4623.         }
  4624.  
  4625.         if (!empty(($allFiles = _node_gitignore(":list:all")))) {
  4626.             # Reference currently focused memoty.
  4627.            $fm = &$focusedMemory;
  4628.  
  4629.             # Preserve currently opened.
  4630.            if ($opened = w(":opened") ? [$fm->structure, $fm->name, $fm->type] : null) {
  4631.                 w("close");
  4632.             }
  4633.             $pnLen = strlen(_node_project("name")) + 1;
  4634.             $structs = struct(":structs");
  4635.  
  4636.             $log = "";
  4637.             foreach ($allFiles as $path) {
  4638.                 $fn = basename($path);
  4639.  
  4640.                 foreach ($supportedFiletypes as $ext) {
  4641.                     if (substr($fn, strlen($ext) * -1) === $ext) {
  4642.                         $fp = dirname(substr($path, $pnLen));
  4643.  
  4644.                         if (!empty(($find = array_filter($structs, fn($x) => substr($x, 0, strlen($fp)) === $fp)))) {
  4645.                             $parts = explode("<", array_pop($find));
  4646.  
  4647.                             $structure = trim($parts[1], " >");
  4648.                             $types = array_map("ucfirst", explode(", ", trim($parts[2], " >")));
  4649.                             $name = $fn;
  4650.                             foreach ($types as $type) {
  4651.                                 foreach ([$type, "{$type}.php"] as $cType) {
  4652.                                     if (substr($fn, strlen($cType) * -1) === $cType) {
  4653.                                         $name = substr($fn, 0, strlen($fn) - strlen($cType));
  4654.                                         break 2; // Keep current $type
  4655.                                     }
  4656.                                 }
  4657.                             }
  4658.                             # $path, $fp, $fn, $structure, $types, $name, $type
  4659.                            $log .= "Checking {$structure} {$name} {$type} ";
  4660.  
  4661.                             # Open file in WriteEditor
  4662.                            w($structure, $name, $type);
  4663.                             $found = w("replace", $old, $new);
  4664.                             if ($found > 0) {
  4665.                                 $log .= " - found {$found}!";
  4666.                                 # Save and close
  4667.                                w("save") && w("close");
  4668.                             }
  4669.                             $log .= "\n";
  4670.                         }
  4671.                     }
  4672.                 }
  4673.             }
  4674.  
  4675.             w("close"); // Close if anything is still opened.
  4676.             # Open last session.
  4677.            isset($opened) && $opened && w(...$opened);
  4678.  
  4679.             # Return results.
  4680.            return "Supersaded {$old} to {$new}:\n" . trim($log);
  4681.         }
  4682.         return 0;
  4683.     }
  4684.  
  4685.     if (str_starts_with($args[0], "namespace") && w(":opened")) {
  4686.         $fn = basename($focusedMemory->path);
  4687.         $ext = array_last(explode(".", $fn));
  4688.  
  4689.         if ($ext === "php") {
  4690.             $namespace = str_replace("\\", D, _node_argex($args, 1));
  4691.             $pn = _node_project("name") . D;
  4692.             $fn = substr($fn, 0, strlen($fn) - 4); // Remove .php extension for movement.
  4693.             $namespace = substr($namespace, str_starts_with($namespace, $pn) ? strlen($pn) : 0);
  4694.  
  4695.             # Reference currently focused memoty.
  4696.            $fm = &$focusedMemory;
  4697.  
  4698.             # Preserve currently opened.
  4699.            $opened = [$fm->structure, $fm->name, $fm->type];
  4700.             w("close");
  4701.  
  4702.             $structs = struct(":structs");
  4703.             if (!empty(($find = array_filter($structs, fn($x) => substr($x, 0, strlen($namespace)) === $namespace)))) {
  4704.                 $parts = explode("<", array_pop($find));
  4705.                 $structure = trim($parts[1], " >");
  4706.  
  4707.                 # Move filename from structure to structure.
  4708.                $moveError = struct("move", $opened[0], $fn, $structure);
  4709.                 if ($moveError === 0) {
  4710.                     # Check to move backups.
  4711.                    $oldBackups = _node_project("path") . struct(":structure:path", $opened[0]) . D . $fn . ".backup.json";
  4712.                     $newBackups = _node_project("path") . struct(":structure:path", $structure) . D . $fn . ".backup.json";
  4713.                     if (file_exists($oldBackups) && !file_exists($newBackups)) {
  4714.                         rename($oldBackups, $newBackups);
  4715.                     }
  4716.                     # Relocate opened.
  4717.                    $opened[0] = $structure;
  4718.  
  4719.                     # Re open moved file in new stucture.
  4720.                    w(...$opened);
  4721.                 }
  4722.                 return $moveError;
  4723.             }
  4724.         }
  4725.         return "Namespace changed, entire project updated.";
  4726.     }
  4727.  
  4728.     if (str_starts_with($args[0], "lint") && w(":opened")) {
  4729.         $selection = _node_argex($args, 1);
  4730.         $ln = $focusedMemory->caret->line;
  4731.         $ch = $focusedMemory->caret->char;
  4732.         $selection && w("sel", $selection);
  4733.         $input = implode("\n", $getSelection());
  4734.         $error = lint($input);
  4735.         $selection && w("sel");
  4736.         $focusedMemory->caret->line = $ln;
  4737.         $focusedMemory->caret->char = $ch;
  4738.         $saveFocus("run");
  4739.         return (object) ["input" => $input, "errors" => $error ?: null];
  4740.     }
  4741.  
  4742.     if (str_starts_with($args[0], "run") && w(":opened")) {
  4743.         $selection = _node_argex($args, 1);
  4744.         $ln = $focusedMemory->caret->line;
  4745.         $ch = $focusedMemory->caret->char;
  4746.         $selection && w("sel", $selection);
  4747.         $string = implode("\n", $getSelection());
  4748.         $input = str_starts_with($string, "<?php") ? substr($string, 5) : (str_starts_with($string, "<?") ? substr($string, 2) : $string);
  4749.         $input = str_ends_with($input, "?>") ? substr($input, 0, strlen($input) - 2) : $input;
  4750.         $selection && w("sel");
  4751.         $focusedMemory->caret->line = $ln;
  4752.         $focusedMemory->caret->char = $ch;
  4753.         $saveFocus("run");
  4754.         return shell_exec("php -r '{$input}' 2>&1") ?? "Execution returned NULL";
  4755.     }
  4756.  
  4757.     if (str_starts_with($args[0], "test") && w(":opened")) {
  4758.         if (strpos($focusedMemory->path, "/Quality/Test/") === false) {
  4759.             if (!empty(($structs = array_filter(struct(":structs"), fn($x) => strpos($x, "/Test/"))))) {
  4760.                 $structure = _node_argex($args, 1, 1);
  4761.                 $action = _node_argex($args, 2);
  4762.  
  4763.                 $log = "Checking test files:\n";
  4764.                 foreach ($structs as $struct) {
  4765.                     $part = array_map(fn($t) => trim($t, " >"), explode("<", $struct));
  4766.  
  4767.                     $requested = $structure === $part[1];
  4768.                     $open = $action === "open";
  4769.  
  4770.                     if (!$structure || $requested) {
  4771.                         $path = _node_project("path") . $part[0] . D;
  4772.                         $name = str_replace(D, "_", $focusedMemory->structure) . "_{$focusedMemory->name}";
  4773.                         $type = "Class";
  4774.                         $file = "{$name}{$type}.php";
  4775.  
  4776.                         $log .= "<{$part[1]}> {$file}";
  4777.                         if (file_exists("{$path}{$file}")) {
  4778.                             # Save current file, close and open new.
  4779.                             if ($open) {
  4780.                                 return w("save") && w("close") && w($part[1], $name, $type);
  4781.                             }
  4782.  
  4783.                             # Run the acutal test file and log methods.
  4784.                             $namespace = str_replace(D, "\\", _node_project("name") . D . rtrim($part[0], D));
  4785.                             $call = "{$namespace}\\{$name}";
  4786.  
  4787.                             $reflection = new ReflectionClass($call);
  4788.                             $class = $reflection->isInstantiable() ? new $call() : null;
  4789.                             $log .= ":\n";
  4790.  
  4791.                             foreach ($reflection->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
  4792.                                 $methodName = $method->getName();
  4793.                                 if (str_starts_with($methodName, "test")) {
  4794.                                     try {
  4795.                                         if ($method->isStatic()) {
  4796.                                             $result = $name::$methodName();
  4797.                                             $log .= " :: {$methodName}: " . ($result ?? "ok") . "\n";
  4798.                                         } elseif ($class) {
  4799.                                             $result = $class->$methodName();
  4800.                                             $log .= " -> {$methodName}: " . ($result ?? "ok") . "\n";
  4801.                                         }
  4802.                                     } catch (Throwable $e) {
  4803.                                         $log .= " !! {$methodName}: " . $e->getMessage() . "\n";
  4804.                                     }
  4805.                                 }
  4806.                             }
  4807.                         } else {
  4808.                             $log .=
  4809.                                 $requested && is_string($createError = struct("new", $structure, $name, $type))
  4810.                                     ? " - created!"
  4811.                                     : " - not found" . ($requested ? ", could not create: {$createError}" : "") . ".\n";
  4812.  
  4813.                             # Save current file, close and open new.
  4814.                             if ($open && is_string($createError)) {
  4815.                                 return w("save") && w("close") && w($structure, $name, $type);
  4816.                             }
  4817.                         }
  4818.                     }
  4819.                 }
  4820.                 return trim($log);
  4821.             }
  4822.             return 1; // Cant manage tests on a test file.
  4823.         }
  4824.         return 0; // Invalid structure.
  4825.     }
  4826.  
  4827.     # The most dynamic opration stays the very last in order of execution.
  4828.     # Opening structure for edits.
  4829.     if (count($args) >= 2 || count(explode(" ", $args[0])) >= 2) {
  4830.         $structure = _node_argex($args, 0, 1);
  4831.         $name = _node_argex($args, 1, 1);
  4832.         $type = _node_argex($args, 2, 1) ?: "Class";
  4833.  
  4834.         if (!empty($structure) && !empty($name)) {
  4835.             if (([$structure, $path] = _node_spex($structure) ?? []) && $path) {
  4836.                 foreach ($supportedFiletypes as $ext) {
  4837.                     $fn = _node_project("path") . $path . D . $name . ucfirst($type) . ($type !== $ext ? $ext : "");
  4838.                     if (file_exists($fn)) {
  4839.                         // Close anything opened.
  4840.                         if (is_int(w("close", false))) {
  4841.                             $focusedMemory->structure = $structure;
  4842.                             $focusedMemory->name = $name;
  4843.                             $focusedMemory->type = $type;
  4844.                             $focusedMemory->path = $fn;
  4845.                             $focusedMemory->caret = (object) [
  4846.                                 "line" => 0,
  4847.                                 "char" => 0,
  4848.                                 "selected_line" => null, // No selection made
  4849.                                 "selected_char" => null,
  4850.                             ];
  4851.                             $focusedMemory->contents = h(
  4852.                                 "w.load.contents",
  4853.                                 array_map(fn($l) => str_replace("\t", str_repeat(" ", (int) $indentSpc), $l), file($fn, FILE_IGNORE_NEW_LINES)),
  4854.                             );
  4855.                             $focusedMemory->modifications = [];
  4856.                             $focusedMemory->pointer = 0;
  4857.                             return $saveFocus("Opened Structrure Type");
  4858.                         }
  4859.                         return r("Opened file cannot be closed, manually save or discard modifications.", "Info", 1);
  4860.                     }
  4861.                 }
  4862.                 return r("Trying to open {$fn}", "Error", 1, $args);
  4863.             }
  4864.         }
  4865.     }
  4866.  
  4867.     # Nothing happened.
  4868.     return null;
  4869. }
  4870. # write end
  4871.  
  4872. # gitignore begin: dev prod
  4873. /*
  4874.  * @param string $fn File path pattern to manage in .gitignore section
  4875.  * @param string $action Action to perform: write, find, delete, copy, move, read
  4876.  * @param string $arg Argument for move action (new path) or copy action (new pattern)
  4877.  * @param string $project optional to target external project .gitifnore file.
  4878.  * @return int 0 on success, 1 if line not found, 2 on file write error
  4879.  */
  4880. function _node_gitignore(string $fn, string $action = "find", ?string $arg = null, ?string $project = null): mixed
  4881. {
  4882.     # Set path to point custom project only if not already working on it (.git folder not moved to root).
  4883.     $gitignorePath = ROOT_PATH . ($project && file_exists($project . D . ".git") ? $project . D : "") . ".gitignore";
  4884.  
  4885.     $beginMarker = h("gitignore.marker.begin", "# Resources begin");
  4886.     $endMarker = h("gitignore.marker.end", "# Resources end");
  4887.  
  4888.     $supportedStructurePaths = array_values(
  4889.         array_unique(
  4890.             array_map(
  4891.                 fn($p) => ($project ?? _node_project("name")) . D . $p,
  4892.                 array_merge(
  4893.                     ...array_map(
  4894.                         fn($p) => array_map(fn($i) => implode(D, array_slice($parts = explode(D, $p), 0, $i)), range(0, count($parts = explode(D, $p)))),
  4895.                         array_map(fn($x) => explode(" ", $x)[0], struct(":structs")),
  4896.                     ),
  4897.                 ),
  4898.             ),
  4899.         ),
  4900.     );
  4901.  
  4902.     if ($fn === ":paths") {
  4903.         return $supportedStructurePaths;
  4904.     }
  4905.  
  4906.     if ($fn === ":paths:plaintext") {
  4907.         return implode("\n", array_map(fn($p) => "!{$p}", $supportedStructurePaths));
  4908.     }
  4909.  
  4910.     # Igitignore default files.
  4911.     $defaultFiles = h("gitignore.default.files", [
  4912.         ...[
  4913.             "!.gitignore",
  4914.             "!" . ($project ?? _node_project("name")),
  4915.             ...array_map(fn($p) => "!{$p}", $supportedStructurePaths),
  4916.             "!" . ($project ?? _node_project("name")) . D . "packages.json",
  4917.             "!README.md",
  4918.         ],
  4919.         ...($project ?? _node_project("name")) === FW_NAME ? ["!" . NAME . ".php", "!" . NAME] : [],
  4920.     ]);
  4921.  
  4922.     # Read current .gitignore content each time anything executes
  4923.     $content = file_exists($gitignorePath)
  4924.         ? f($gitignorePath, "read")
  4925.         : h("gitignore.default.fc", "# Exclude everything, include explicitly\n*\n\n" . implode("\n", $defaultFiles) . "\n");
  4926.  
  4927.     # Enable rollback per phase
  4928.     static $rollbackState = [];
  4929.     $rollbackState[p(":name")] ??= $content;
  4930.  
  4931.     if ($fn === ":rollback") {
  4932.         return f($gitignorePath, "write", $rollbackState[p(":name")]) ? 0 : r("Could not rollback gitignore on phase: " . p(":name"), "Error", 1);
  4933.     }
  4934.  
  4935.     # Find section markers
  4936.     $beginPos = strpos($content, $beginMarker);
  4937.     $endPos = strpos($content, $endMarker);
  4938.  
  4939.     # If section doesn't exist, create it at the end
  4940.     if ($beginPos === false || $endPos === false) {
  4941.         $beforeSection = $content;
  4942.         $sectionLines = [];
  4943.         $afterSection = "";
  4944.  
  4945.         # Ensure section exists
  4946.         if ($content !== "" && substr($content, -1) !== "\n") {
  4947.             $content .= "\n";
  4948.         }
  4949.         $content .= h("gitignore.default.markerarea", "{$beginMarker}\n{$endMarker}\n");
  4950.  
  4951.         # Re-calc positions.
  4952.         $beginPos = strpos($content, $beginMarker);
  4953.         $endPos = strpos($content, $endMarker);
  4954.     } else {
  4955.         # Parse existing section
  4956.         $beforeSection = substr($content, 0, $beginPos);
  4957.         $sectionEnd = $endPos + strlen($endMarker);
  4958.         $afterSection = substr($content, $sectionEnd);
  4959.  
  4960.         # Extract section content (between markers)
  4961.         $sectionContent = substr($content, $beginPos + strlen($beginMarker), $endPos - $beginPos - strlen($beginMarker));
  4962.  
  4963.         # Split into lines and clean up
  4964.         $sectionLines = array_filter(explode("\n", $sectionContent), fn($line) => trim($line) !== "" && !str_starts_with(trim($line), "#"));
  4965.  
  4966.         # Re-index array
  4967.         $sectionLines = array_values($sectionLines);
  4968.     }
  4969.  
  4970.     if ($fn === ":list:all") {
  4971.         return array_map(fn($fn) => ltrim(trim($fn), "!"), $sectionLines ?? []);
  4972.     }
  4973.  
  4974.     # Normalize paths to ensure consistent comparison
  4975.     $fn = rtrim($fn, D);
  4976.     $arg = $arg ? rtrim($arg, D) : $arg;
  4977.  
  4978.     # Convert to relative paths from ROOT_PATH
  4979.     $fn = str_starts_with($fn, ROOT_PATH) ? substr($fn, strlen(ROOT_PATH)) : $fn;
  4980.     $arg = $arg && str_starts_with($arg, ROOT_PATH) ? substr($arg, strlen(ROOT_PATH)) : $arg;
  4981.  
  4982.     # Normalize the input pattern for comparison - ensure it starts with !
  4983.     $normalizedFn = ltrim(trim($fn), "!");
  4984.     $normalizedFn = "!{$normalizedFn}";
  4985.  
  4986.     # Find if the pattern exists in section
  4987.     $foundIndex = -1;
  4988.     foreach ($sectionLines as $index => $line) {
  4989.         # Normalize stored line for comparison (ensure it starts with !)
  4990.         $storedLine = ltrim(trim($line), "!");
  4991.         $storedLine = "!{$storedLine}";
  4992.         if ($storedLine === $normalizedFn) {
  4993.             $foundIndex = $index;
  4994.             break;
  4995.         }
  4996.     }
  4997.  
  4998.     $return = null;
  4999.  
  5000.     # Perform requested action
  5001.     switch ($action) {
  5002.         case "find":
  5003.         case "read":
  5004.         case "append":
  5005.             $return = empty($fn) || $foundIndex !== -1 ? 0 : r("Gitignore: Dummy operation {$action} did not find file", "Info", 1);
  5006.             break;
  5007.         case "write":
  5008.             # Add if not already present (ensure starts with !)
  5009.             if ($foundIndex === -1) {
  5010.                 $sectionLines[] = $normalizedFn;
  5011.                 # Sort to keep gitignore organized
  5012.                 sort($sectionLines, SORT_STRING);
  5013.             }
  5014.             break;
  5015.  
  5016.         case "copy":
  5017.             if ($arg === null) {
  5018.                 return r("Gitignore: Missing argument for copy", "Error", 2);
  5019.             }
  5020.             # Normalize arg to ensure starts with !
  5021.             $normalizedArg = ltrim(trim($arg), "!");
  5022.             $normalizedArg = "!{$normalizedArg}";
  5023.  
  5024.             # Check if the copy target already exists
  5025.             $copyFoundIndex = -1;
  5026.             foreach ($sectionLines as $index => $line) {
  5027.                 $storedLine = ltrim(trim($line), "!");
  5028.                 $storedLine = "!{$storedLine}";
  5029.                 if ($storedLine === $normalizedArg) {
  5030.                     $copyFoundIndex = $index;
  5031.                     break;
  5032.                 }
  5033.             }
  5034.  
  5035.             # Add copy target if not already present
  5036.             if ($copyFoundIndex === -1) {
  5037.                 $sectionLines[] = $normalizedArg;
  5038.                 # Sort to keep gitignore organized
  5039.                 sort($sectionLines, SORT_STRING);
  5040.             }
  5041.             break;
  5042.  
  5043.         case "delete":
  5044.             if ($foundIndex === -1) {
  5045.                 return r("Gitignore delete found no file within .gitignore", "Error", 1); # Line not found
  5046.             }
  5047.             # Remove the line
  5048.             array_splice($sectionLines, $foundIndex, 1);
  5049.             break;
  5050.  
  5051.         case "move":
  5052.             if ($foundIndex === -1) {
  5053.                 return r("Gitignore: Move found no line to move", "Error", 1); # Line not found
  5054.             }
  5055.             if ($arg === null) {
  5056.                 return r("Gitignore: Move got no target argument", "Error", 2); # Missing argument
  5057.             }
  5058.             # Normalize arg to ensure starts with !
  5059.             $normalizedArg = ltrim(trim($arg), "!");
  5060.             $normalizedArg = "!{$normalizedArg}";
  5061.  
  5062.             # Replace with new path
  5063.             $sectionLines[$foundIndex] = $normalizedArg;
  5064.             # Re-sort after change
  5065.             sort($sectionLines, SORT_STRING);
  5066.             break;
  5067.  
  5068.         default:
  5069.             # Unknown action
  5070.             return r("Gitignore: Unknown action '{$action}'", "Error", 2);
  5071.     }
  5072.  
  5073.     # Reconstruct the gitignore content
  5074.     $newSectionContent = "{$beginMarker}\n";
  5075.     foreach ($sectionLines as $line) {
  5076.         # Ensure each stored line starts with !
  5077.         $storedLine = ltrim(trim($line), "!");
  5078.         $storedLine = "!{$storedLine}";
  5079.         $newSectionContent .= "{$storedLine}\n";
  5080.     }
  5081.     $newSectionContent .= $endMarker;
  5082.  
  5083.     $newContent = "{$beforeSection}{$newSectionContent}{$afterSection}";
  5084.  
  5085.     # Write using your f() function
  5086.     $result = f($gitignorePath, "write", $newContent, false);
  5087.  
  5088.     # Check if write was successful
  5089.     if ($result === false || $result === null) {
  5090.         return r("Gitignore: File write error", "Error", 2); # File write error
  5091.     }
  5092.  
  5093.     return $return ?? $result; # Success
  5094. }
  5095. # gitignore end;
  5096.  
  5097. # gitrepo begin: dev prod
  5098. function _node_gitrepo(): ?string
  5099. {
  5100.     $configFile = ROOT_PATH . ".git" . D . "config";
  5101.  
  5102.     if (!file_exists($configFile)) {
  5103.         return null;
  5104.     }
  5105.  
  5106.     $url = parse_ini_file($configFile, true)["remote origin"]["url"] ?? null;
  5107.  
  5108.     return $url ? basename($url, ".git") : null;
  5109. }
  5110. # gitrepo end;
  5111.  
  5112. # git begin: dev prod
  5113. function git(mixed ...$args): mixed
  5114. {
  5115.     # Git server host.
  5116.     $host = "git.kolostov.ee";
  5117.  
  5118.     # Filter args.
  5119.     $args = array_filter($args);
  5120.  
  5121.     if (empty($args)) {
  5122.         return implode("\n", [
  5123.             "git login <?user> <?pass> Sets local authentication for pushing into https://{$host}",
  5124.             "git spawn <user>/<repo> Creates and inits new repository if not exists or else pulls repository.",
  5125.             "git target <?repo> Targets to repository if exists or lists all available repositories.",
  5126.             "git send <?message> Performs 'git add .', 'git commit -m <message>', 'git pull', 'git push' in sequence.",
  5127.             "git update Goes trough all projects and does 'git pull' on each of them.",
  5128.             "git logout <user> Removes user from local authentication file for https://{$host}",
  5129.         ]);
  5130.     }
  5131.  
  5132.     if ($args[0] === ":list") {
  5133.         return array_map("basename", array_filter(glob(ROOT_PATH . "*"), fn($fn) => is_dir($fn) && file_exists($fn . D . ".git")));
  5134.     }
  5135.  
  5136.     if (in_array($args[0], [":target", "target"]) || str_starts_with($args[0], "target")) {
  5137.         $currentTarget = _node_gitrepo();
  5138.         if ($args[0] === "target") {
  5139.             return "Current target: {$currentTarget}, available:\n" . implode("\n", git(":list") ?: ["- none"]);
  5140.         }
  5141.  
  5142.         $givenTarget = _node_argex($args, 1, 1);
  5143.         if ($args[0] === ":target" || empty($givenTarget)) {
  5144.             return $currentTarget;
  5145.         }
  5146.  
  5147.         if ($givenTarget === $currentTarget) {
  5148.             return "Git already targeting: {$givenTarget}";
  5149.         }
  5150.  
  5151.         # Supposed new git target
  5152.        $newTarget = ROOT_PATH . $givenTarget;
  5153.         $currentTarget = ROOT_PATH . $currentTarget . D;
  5154.         if (file_exists($newTarget) && is_dir($newTarget) && file_exists($newTarget . D . ".git")) {
  5155.             $newTarget .= D;
  5156.             $listOfManagedMoves = [".git", "README.md", ".gitignore"];
  5157.             $skip_current_target = []; // Allow non-existent initial target.
  5158.             $flag = true;
  5159.  
  5160.             foreach ($listOfManagedMoves as $fn) {
  5161.                 if (!file_exists(ROOT_PATH . $fn)) {
  5162.                     // $flag = false;
  5163.                     // return r("Error finding currently targeted {$fn} in" . ROOT_PATH, "Error", 3, $args);
  5164.                     $skip_current_target[] = $fn;
  5165.                 }
  5166.                 if (!file_exists("{$newTarget}{$fn}") || file_exists("{$currentTarget}{$fn}")) {
  5167.                     if ($fn === ".gitignore" && !file_exists("{$newTarget}{$fn}")) {
  5168.                         // Create new gitignore for project.
  5169.                         if (_node_gitignore("", "find", project: $givenTarget)) {
  5170.                             return r("Could no create initial gitignore for project {$givenTarget}", "Error", 2, $args);
  5171.                         }
  5172.                     } else {
  5173.                         $flag = false;
  5174.                         return r("Error moving {$fn} from {$newTarget} or {$currentTarget} full", "Error", 2, $args);
  5175.                     }
  5176.                 }
  5177.             }
  5178.             if ($flag) {
  5179.                 foreach ($listOfManagedMoves as $fn) {
  5180.                     if ((in_array($fn, $skip_current_target) === false && !f(ROOT_PATH . $fn, "move", "{$currentTarget}{$fn}")) || !f("{$newTarget}{$fn}", "move", ROOT_PATH . $fn)) {
  5181.                         $info = [ROOT_PATH, $currentTarget, $newTarget, $fn];
  5182.  
  5183.                         # Error moving files, roll back.
  5184.                        return f(":rollback")
  5185.                             ? r("Error moving files, check permissions and dirs.", "Error", 4, $info)
  5186.                             : r("Complete collaps of filesystem, cant rollback failed move.", "Error", 5, $info);
  5187.                     }
  5188.                 }
  5189.  
  5190.                 # Targeting completed
  5191.                return "Now targeting {$newTarget} \n";
  5192.             }
  5193.         } else {
  5194.             return "Could not find Repository {$givenTarget} in {$newTarget}, avaiable: \n" . implode("\n", git(":list") ?: ["- none"]);
  5195.         }
  5196.         return r("Cannot target {$givenTarget}, folder not found: {$newTarget}", "Internal", 1, $args);
  5197.     }
  5198.  
  5199.     if (str_starts_with($args[0], "spawn")) {
  5200.         $targ = _node_argex($args, 1, 1);
  5201.         if (!$targ || empty($targ) || strpos($targ, "/") === false) {
  5202.             return "Expecting <username>/<reponame> to call https://{$host}/<username>/<reponame>.git";
  5203.         }
  5204.         $parts = explode("/", $targ);
  5205.         $user = trim($parts[0]);
  5206.         $repo = trim($parts[1]);
  5207.         if (!empty($user) && !empty($repo)) {
  5208.             $newRepo = ROOT_PATH . $repo;
  5209.             if (file_exists($newRepo) && is_dir($newRepo)) {
  5210.                 return "Trying to spawn already existing repository: {$repo}";
  5211.             }
  5212.  
  5213.             try {
  5214.                 $clone = @shell_exec("git clone https://{$host}/{$user}/{$repo}.git 2>&1");
  5215.                 if (strpos($clone, "cloned an empty")) {
  5216.                     $makeUrl = "https://{$host}/{$user}/{$repo}.git?make";
  5217.                     $make = @file_get_contents($makeUrl);
  5218.                     if ($make === false || strpos($make, $repo) === false) {
  5219.                         r("Could not create repo at {$makeUrl}", "Warning", 3);
  5220.                     }
  5221.                 }
  5222.  
  5223.                 if (!file_exists($newRepo) && !is_dir($newRepo)) {
  5224.                     // Make new folder for repo
  5225.                     mkdir($newRepo, 0777, true);
  5226.  
  5227.                     // Do local git init
  5228.                     $initCommands = ["cd " . escapeshellarg($newRepo), "git init", "git remote add origin https://{$host}/{$user}/{$repo}.git"];
  5229.  
  5230.                     $initResult = shell_exec(implode(" && ", $initCommands) . " 2>&1");
  5231.  
  5232.                     r("Initialized new git repository for {$repo}", "Info", 0, [
  5233.                         "init" => $initResult,
  5234.                     ]);
  5235.                 }
  5236.  
  5237.                 if (file_exists($newRepo) && is_dir($newRepo)) {
  5238.                     $newRepoSubfolder = $newRepo . D . $repo;
  5239.                     if (file_exists($newRepoSubfolder) && is_dir($newRepoSubfolder)) {
  5240.                         if (!f($newRepoSubfolder, "move", $newRepo)) {
  5241.                             return f(":rollback")
  5242.                                 ? r("Could not move repo subfoder on spawn", "Error", 4)
  5243.                                 : r("Could not rollback on failure of moving repos subfolder on spawn", "Error", 5);
  5244.                         }
  5245.                     }
  5246.                     $newRedme = $newRepo . D . "README.md";
  5247.                     if (!_node_gitignore("", "find", project: $repo) && !file_exists($newRedme)) {
  5248.                         f($newRedme, "write", "Init git\n");
  5249.                     }
  5250.  
  5251.                     if (file_exists($newRepo . D . "packages.json")) {
  5252.                         $path = escapeshellarg($newRepo);
  5253.                         $command = "composer install --working-dir=$path --no-interaction --optimize-autoloader 2>&1";
  5254.                         shell_exec($command);
  5255.                     }
  5256.  
  5257.                     // Auto-init blockchain and node.json for fresh spawns
  5258.                     $spawnedProjectPath = ROOT_PATH . $repo . D;
  5259.                     $spawnedNodeJson = "{$spawnedProjectPath}node.json";
  5260.                     if (!file_exists($spawnedNodeJson)) {
  5261.                         $scaffold = node(":scaffold");
  5262.                         file_put_contents($spawnedNodeJson, json_encode($scaffold, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
  5263.  
  5264.                         _node_gitignore($spawnedNodeJson, "write");
  5265.                     }
  5266.                     // Initialise blockchain for the new deployment
  5267.                     $prevProject = _node_project("name");
  5268.                     _node_project("name", $repo);
  5269.                     _node_migrate_ensure_blockchain();
  5270.                     _node_project("name", $prevProject);
  5271.  
  5272.                     return "Spawned {$user}/{$repo} for " . FW_NAME . " which was presumably an empty project";
  5273.                 }
  5274.             } catch (Exception $e) {
  5275.                 return r("Error operating with git & file_get_contents on spawning new repository.", "Error", 6, $e);
  5276.             }
  5277.             return r("Could not clone {$user}/{$repo} into " . ROOT_PATH, "Error", 2);
  5278.         }
  5279.         return r("Invalid git source [{$user}/{$repo}] check and try again.", "Warning", 1);
  5280.     }
  5281.  
  5282.     if (str_starts_with($args[0], "logout")) {
  5283.         $user = _node_argex($args, 1, 1);
  5284.         if (!empty($user)) {
  5285.             $creds = "protocol=https\nhost={$host}\nusername={$user}\n\n";
  5286.             $erase = "printf " . escapeshellarg($creds) . " | git credential-store erase 2>&1";
  5287.             return shell_exec($erase);
  5288.         }
  5289.         return "Empty user.";
  5290.     }
  5291.  
  5292.     if (str_starts_with($args[0], "login")) {
  5293.         $user = _node_argex($args, 1, 1);
  5294.         $pass = _node_argex($args, 2);
  5295.  
  5296.         if (empty($user) || empty($pass)) {
  5297.             $credentials = trim(shell_exec("cat ~/.git-credentials 2>&1"));
  5298.             if (empty($credentials) || strpos($credentials, $host) === false) {
  5299.                 $cuser = null;
  5300.                 $cpass = null;
  5301.             } else {
  5302.                 $line = trim(array_filter(explode("\n", $credentials), fn($ln) => strpos($ln, $host) !== false)[0]);
  5303.                 $line = explode(":", $line);
  5304.                 if (count($line) === 3) {
  5305.                     $cuser = substr($line[1], 2);
  5306.                     $cpass = substr($line[2], 0, strpos($line[2], "@{$host}") ?: 0);
  5307.                 }
  5308.             }
  5309.  
  5310.             return $user === ":user" ? $cuser : ($user === ":pass" ? $cpass : "Current authentication set for https://{$host} is:\n" . implode("\n", [$cuser, $cpass]));
  5311.         }
  5312.  
  5313.         $creds = "protocol=https\nhost={$host}\nusername={$user}\npassword={$pass}\n\n";
  5314.         $cmd = "printf " . escapeshellarg($creds) . " | git credential-store --file ~/.git-credentials store 2>&1";
  5315.  
  5316.         return shell_exec($cmd);
  5317.     }
  5318.  
  5319.     if (str_starts_with($args[0], "send")) {
  5320.         $message = _node_argex($args, 1) ?: "Quick fixes";
  5321.  
  5322.         $msgEsc = escapeshellarg($message);
  5323.         $output = shell_exec("git add . && git commit -m {$msgEsc} && git pull --no-rebase && git push 2>&1");
  5324.  
  5325.         return $output;
  5326.     }
  5327.  
  5328.     if (str_starts_with($args[0], "update")) {
  5329.         $currentTarget = _node_gitrepo() ?: null;
  5330.         if (!empty(($repos = git(":list")))) {
  5331.             $log = "";
  5332.             foreach ($repos as $repo) {
  5333.                 git("target", $repo);
  5334.                 $log .= "Pulling {$repo} \n" . shell_exec("git pull 2>&1") . "\n";
  5335.             }
  5336.             git("target", $currentTarget); // Back to current target.
  5337.             return trim($log);
  5338.         }
  5339.     }
  5340.  
  5341.     return shell_exec("git " . implode(" ", $args) . " 2>&1");
  5342. }
  5343. # git end;
  5344.  
  5345. # import begin: dev
  5346. /**
  5347.  * Imports an external project into the NodePHP ecosystem.
  5348.  * Maps files to structures, rewrites namespaces, and manages git tracking.
  5349.  * Unrecognised namespaces are inferred, placed, and written to structure.json
  5350.  * so that struct() picks them up on the next run (emergent structure growth).
  5351.  *
  5352.  * @param string|bool ...$args Variadic: first arg is source dir, second is project name.
  5353.  *                        Pass ":help" for usage. Pass ":map" to see the default asset map.
  5354.  * @return string Status message or help text.
  5355.  */
  5356. function import(string|bool ...$args): string
  5357. {
  5358.     # Filter args (matches pattern of struct, git, w, dump).
  5359.    $reorganize = (bool) h("import.reorganize", array_pop(array_filter($args, fn($a) => is_bool($a))) ?? false);
  5360.     $args = array_filter($args, fn($a) => !is_bool($a));
  5361.  
  5362.     if (empty($args) || $args[0] === ":help") {
  5363.         return implode("\n", [
  5364.             "import <source> <projectName> Imports an external project into the NodePHP ecosystem.",
  5365.             "import :map Lists the default asset extension-to-structure mappings.",
  5366.             "import :status Shows status of any in-progress import sessions.",
  5367.             "import :clean Cleans import memory.",
  5368.         ]);
  5369.     }
  5370.  
  5371.     if ($args[0] === ":map") {
  5372.         $map = h("import.asset.map", _node_import_default_asset_map());
  5373.         $output = ["Asset Extension to Structure Mapping:", ""];
  5374.         foreach ($map as $ext => $path) {
  5375.             $output[] = sprintf("  %-10s => %s", $ext, $path);
  5376.         }
  5377.         return implode("\n", $output);
  5378.     }
  5379.  
  5380.     if ($args[0] === ":status") {
  5381.         return _node_import_status();
  5382.     }
  5383.  
  5384.     if ($args[0] === ":clean") {
  5385.         $sessions = glob(sys_get_temp_dir() . D . "import_session_*") ?: [];
  5386.         $maxAge = h("import.session.max_age", 86400);
  5387.         $count = array_sum(array_map(fn($s) => filemtime($s) < time() - $maxAge && unlink($s) ? 1 : 0, $sessions));
  5388.         return r("Cleaned {$count} stale import session(s).", "Info", "Cleaned {$count} stale session(s).\n");
  5389.     }
  5390.  
  5391.     $source = _node_argex($args, 0, 1);
  5392.     $projectName = _node_argex($args, 1);
  5393.  
  5394.     if (!$source || !$projectName) {
  5395.         return r("import requires <source> and <projectName>.", "Error", "Usage: " . import(":help"));
  5396.     }
  5397.  
  5398.     # 1. Validate source directory.
  5399.    $source = rtrim(_node_import_resolve_path($source), D) . D;
  5400.     if (!is_dir($source)) {
  5401.         return r("Source directory does not exist: {$source}", "Error", "Source not found.");
  5402.     }
  5403.  
  5404.     # Track duration with a plain local variable — import() is not a phase handler,
  5405.    # so $this (Context) is not available here.
  5406.    $startTime = microtime(true);
  5407.     $targetRoot = h("import.target.root", ROOT_PATH . $projectName . D);
  5408.     $isSelfImport = h("import.is_self", rtrim($source, D) === rtrim($targetRoot, D));
  5409.  
  5410.     # 2. Prepare target project — spawn via git() if absent.
  5411.    # Skip for self-import (reorganize) — project already exists.
  5412.    if (!$isSelfImport && !is_dir($targetRoot)) {
  5413.         r("Project {$projectName} not found, spawning...", "Info", 0);
  5414.         $spawnResult = git("spawn", git("login", ":user") . "/$projectName");
  5415.         if (is_string($spawnResult) && (str_contains($spawnResult, "Error") || str_contains($spawnResult, "Could not"))) {
  5416.             return r("Failed to spawn project: {$spawnResult}", "Error", "Spawn failed.");
  5417.         }
  5418.     }
  5419.  
  5420.     $isSelfImport || git("target", $projectName);
  5421.  
  5422.     r("Starting import from {$source} to {$projectName}", "Info", 0);
  5423.  
  5424.     # 3. Asset extension → structure mapping (fully hookable).
  5425.    $assetMap = h("import.asset.map", _node_import_default_asset_map());
  5426.  
  5427.     # 4. Resolve struct keys — builtin merged with dynamic from structure.json.
  5428.    #    struct(":keys") already returns the merged set because struct() reads
  5429.    #    structure.json via _node_struct_load_dynamic() at initialisation time.
  5430.    #    We keep a LOCAL $allKeys that we can extend during this run so that
  5431.    #    newly inferred structures are immediately available to the second PHP pass,
  5432.    #    without needing to reset the static inside struct().
  5433.    static $builtinKeys = null;
  5434.     $builtinKeys ??= struct(":keys");
  5435.  
  5436.     # Load the dynamic set explicitly so we can track what we ADD to it this run.
  5437.    $existingDynamic = _node_struct_load_dynamic($targetRoot);
  5438.     $newDynamic = []; # Entries discovered during this import run.
  5439.    $allKeys = array_merge($builtinKeys, $existingDynamic);
  5440.  
  5441.     # 5. Scan all source files.
  5442.    try {
  5443.         $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS));
  5444.     } catch (Exception $e) {
  5445.         return r("Failed to scan directory: " . $e->getMessage(), "Error", "Scan failed.");
  5446.     }
  5447.  
  5448.     $files = [];
  5449.     foreach ($iterator as $file) {
  5450.         if ($file->isFile()) {
  5451.             $rel = substr($file->getPathname(), strlen($source));
  5452.             $ext = strtolower("." . $file->getExtension());
  5453.             # Skip bare-extension results and common untracked directories.
  5454.            $excludeDirs = h("import.exclude.dirs", [".git", ".svn", "node_modules", "vendor", "Deleted", "Backup", "Deprecated", "Log", "Boilerplate"]);
  5455.             if ($ext === "." || in_array(strtok($rel, D), $excludeDirs)) {
  5456.                 continue;
  5457.             }
  5458.             $files[$rel] = [
  5459.                 "path" => $file->getPathname(),
  5460.                 "ext" => $ext,
  5461.                 "size" => $file->getSize(),
  5462.                 "mtime" => $file->getMTime(),
  5463.             ];
  5464.         }
  5465.     }
  5466.  
  5467.     $files = h("import.files", $files);
  5468.  
  5469.     if (empty($files)) {
  5470.         return r("No files found in source directory.", "Warning", "Import aborted.");
  5471.     }
  5472.  
  5473.     # Session file lives in sys_get_temp_dir() — read/write via file_get_contents
  5474.    # directly since f() is reserved for project-tree paths tracked by rollback.
  5475.    $sessionFile = h("import.session.file", sys_get_temp_dir() . D . "import_session_" . md5($projectName));
  5476.  
  5477.     $pathTransformations = [];
  5478.     $namespaceMap = [];
  5479.     $processed = ["assets" => 0, "php" => 0, "skipped" => 0, "dynamic" => 0];
  5480.  
  5481.     # Write initial session state.
  5482.    file_put_contents(
  5483.         $sessionFile,
  5484.         json_encode(
  5485.             [
  5486.                 "started" => time(),
  5487.                 "source" => $source,
  5488.                 "project" => $projectName,
  5489.                 "files" => array_keys($files),
  5490.                 "processed" => [],
  5491.             ],
  5492.             JSON_PRETTY_PRINT,
  5493.         ),
  5494.     );
  5495.  
  5496.     # Declare $nsPattern before both PHP loops so it is guaranteed in scope
  5497.    # even if $phpFiles is empty and the first-pass loop never executes.
  5498.    $nsPattern = h("import.php.namespace.pattern", "/namespace\s+([^;{]+)[;{]/");
  5499.  
  5500.     /**
  5501.      * Soft-delete a source file during reorganize — uses f() move into Deleted/
  5502.      * so it is rollbackable and gitignore-tracked, identical to struct delete behaviour.
  5503.      */
  5504.     $softDelete = function (string $absPath) use ($targetRoot, $projectName): void {
  5505.         if (!file_exists($absPath)) {
  5506.             return;
  5507.         }
  5508.  
  5509.         $relFromRoot = substr($absPath, strlen($targetRoot));
  5510.         $deletedDir = $targetRoot . "Deleted" . D . dirname($relFromRoot) . D;
  5511.  
  5512.         if (!is_dir($deletedDir)) {
  5513.             mkdir($deletedDir, 0777, true);
  5514.         }
  5515.  
  5516.         $deletedPath = $deletedDir . basename($absPath);
  5517.  
  5518.         f($absPath, "move", $deletedPath);
  5519.         _node_gitignore($absPath, "delete");
  5520.         r("struct reorganize: soft-deleted {$relFromRoot}", "Migrate", 0);
  5521.  
  5522.         // Also move .backup.json sidecar if present
  5523.         $backupSrc = preg_replace('/\.[^.]+$/', ".backup.json", $absPath);
  5524.         if (file_exists($backupSrc)) {
  5525.             $backupDst = preg_replace('/\.[^.]+$/', ".backup.json", $deletedPath);
  5526.             f($backupSrc, "move", $backupDst);
  5527.             _node_gitignore($backupSrc, "delete");
  5528.         }
  5529.     };
  5530.  
  5531.     try {
  5532.         # 6. Process non-PHP assets.
  5533.        foreach ($files as $relativePath => $file) {
  5534.             if ($file["ext"] === ".php") {
  5535.                 continue;
  5536.             }
  5537.  
  5538.             $ext = $file["ext"];
  5539.             $relativePath = h("import.relative.path", $relativePath, [$file]);
  5540.  
  5541.             if (!isset($assetMap[$ext])) {
  5542.                 r("No asset mapping for extension {$ext}, skipping.", "Info", 0, ["file" => $relativePath]);
  5543.                 $processed["skipped"]++;
  5544.                 continue;
  5545.             }
  5546.  
  5547.             # Asset map values are full struct key paths (e.g. "Presentation/Assets/Static/Image").
  5548.            # Validate directly against $allKeys (builtin + dynamic).
  5549.            $structPath = h("import.asset.structure", $assetMap[$ext], [$ext]);
  5550.  
  5551.             if (!array_key_exists($structPath, $allKeys)) {
  5552.                 r("Asset structure not found: {$structPath}", "Warning", 0, ["file" => $relativePath]);
  5553.                 $processed["skipped"]++;
  5554.                 continue;
  5555.             }
  5556.  
  5557.             $filename = h("import.asset.filename", basename($relativePath), [$relativePath]);
  5558.             $targetPath = h("import.asset.targetpath", "$targetRoot$structPath" . D . $filename, [$relativePath]);
  5559.  
  5560.             # Build directory tree if absent — import creates structure, not assumes it.
  5561.            if (!is_dir(dirname($targetPath))) {
  5562.                 mkdir(dirname($targetPath), 0777, true);
  5563.             }
  5564.  
  5565.             $content = _node_import_read_external($file["path"]);
  5566.             if ($content === null) {
  5567.                 r("Failed to read asset: {$file["path"]}", "Warning", 0);
  5568.                 $processed["skipped"]++;
  5569.                 continue;
  5570.             }
  5571.  
  5572.             $content = h("import.asset.content", $content, [$relativePath, $ext]);
  5573.  
  5574.             if (f($targetPath, "write", $content) === false) {
  5575.                 throw new RuntimeException("Failed to write asset: {$targetPath}");
  5576.             }
  5577.  
  5578.             _node_gitignore($targetPath, "write", project: $projectName);
  5579.  
  5580.             $pathTransformations[$relativePath] = $structPath . D . $filename;
  5581.             $processed["assets"]++;
  5582.  
  5583.             // Soft-delete source if reorganizing and file actually moved
  5584.             if ($reorganize && $isSelfImport) {
  5585.                 $srcAbs = $file["path"];
  5586.                 $dstAbs = $targetPath;
  5587.                 if (rtrim($srcAbs, D) !== rtrim($dstAbs, D)) {
  5588.                     $softDelete($srcAbs);
  5589.                 }
  5590.             }
  5591.             _node_import_update_session($sessionFile, "asset", $relativePath, $targetPath);
  5592.             r("Migrated asset: {$relativePath} -> {$structPath}", "Info", 0);
  5593.         }
  5594.  
  5595.         # 7. First PHP pass — build namespace → structure map.
  5596.        #    Unknown namespaces are inferred and registered into $allKeys immediately
  5597.        #    so the second pass can place those files without skipping them.
  5598.        $phpFiles = array_filter($files, fn($f) => $f["ext"] === ".php");
  5599.  
  5600.         foreach ($phpFiles as $relativePath => $file) {
  5601.             $content = _node_import_read_external($file["path"]);
  5602.             if (!$content) {
  5603.                 continue;
  5604.             }
  5605.  
  5606.             if (preg_match($nsPattern, $content, $m)) {
  5607.                 $oldNamespace = trim($m[1]);
  5608.                 $namespaceParts = explode("\\", $oldNamespace);
  5609.  
  5610.                 # Strip leading vendor/project segment, use remainder as path hint.
  5611.                $pathHint = implode(D, array_slice($namespaceParts, 1));
  5612.                 $matched = _node_import_find_structure($pathHint ?: dirname($relativePath), $allKeys);
  5613.  
  5614.                 if ($matched) {
  5615.                     $namespaceMap[$oldNamespace] = $matched;
  5616.                 } else {
  5617.                     # No match in builtin + existing dynamic — infer a new structure path.
  5618.                    $inferred = _node_import_infer_structure($oldNamespace, $projectName);
  5619.                     if ($inferred) {
  5620.                         $detectedType = _node_import_detect_type($content);
  5621.                         $typeEntry = [$detectedType === "Class" ? "class" : strtolower($detectedType)];
  5622.  
  5623.                         # Register immediately into $allKeys so second pass finds it.
  5624.                        $allKeys[$inferred] = $typeEntry;
  5625.                         $newDynamic[$inferred] = $typeEntry;
  5626.                         $namespaceMap[$oldNamespace] = $inferred;
  5627.  
  5628.                         r("Inferred new structure: {$oldNamespace} -> {$inferred}", "Info", 0, [
  5629.                             "hint" => $pathHint ?: dirname($relativePath),
  5630.                         ]);
  5631.                         $processed["dynamic"]++;
  5632.                     } else {
  5633.                         r("No structure matched namespace: {$oldNamespace}", "Info", 0, [
  5634.                             "hint" => $pathHint ?: dirname($relativePath),
  5635.                         ]);
  5636.                     }
  5637.                 }
  5638.             }
  5639.         }
  5640.  
  5641.         $namespaceMap = h("import.namespace.map", $namespaceMap);
  5642.  
  5643.         # Persist newly discovered structures to structure.json immediately,
  5644.        # before the second pass writes any files — safe even if second pass throws.
  5645.        if (!empty($newDynamic)) {
  5646.             if (_node_struct_save_dynamic($targetRoot, $newDynamic)) {
  5647.                 r("Wrote " . count($newDynamic) . " new structure(s) to structure.json.", "Info", 0, $newDynamic);
  5648.             } else {
  5649.                 r("Could not write structure.json — dynamic entries will not persist.", "Warning", 0);
  5650.             }
  5651.         }
  5652.  
  5653.         # 8. Second PHP pass — rewrite content and place files.
  5654.        foreach ($phpFiles as $relativePath => $file) {
  5655.             $content = _node_import_read_external($file["path"]);
  5656.             if ($content === null) {
  5657.                 r("Could not read PHP file, skipping: {$relativePath}", "Warning", 0);
  5658.                 $processed["skipped"]++;
  5659.                 continue;
  5660.             }
  5661.  
  5662.             $targetType = h("import.php.type", _node_import_detect_type($content));
  5663.  
  5664.             $namePattern = h("import.php.name.pattern", "/(?:class|interface|trait|enum)\s+(\w+)/", [$targetType]);
  5665.             preg_match($namePattern, $content, $nameMatch);
  5666.             $className = h("import.php.classname", $nameMatch[1] ?? pathinfo($relativePath, PATHINFO_FILENAME), [$relativePath]);
  5667.  
  5668.             # Resolve target structure from namespace map, then directory hint.
  5669.            # $allKeys includes builtin + existing dynamic + newly inferred entries.
  5670.            $targetStructure = null;
  5671.             if (preg_match($nsPattern, $content, $nsMatch)) {
  5672.                 $oldNs = trim($nsMatch[1]);
  5673.                 $targetStructure = $namespaceMap[$oldNs] ?? null;
  5674.             }
  5675.             if (!$targetStructure) {
  5676.                 $dirHint = str_replace(["\\", "/"], D, dirname($relativePath));
  5677.                 $targetStructure = _node_import_find_structure($dirHint, $allKeys);
  5678.             }
  5679.  
  5680.             $targetStructure = h("import.php.structure", $targetStructure ?? h("import.php.fallback.structure", "System/Utility/Function/Helper"), [$relativePath]);
  5681.  
  5682.             # Validate the resolved structure path exists in the combined key set.
  5683.            if (!array_key_exists($targetStructure, $allKeys)) {
  5684.                 r("Target structure not in struct definition: {$targetStructure}", "Warning", 0, [
  5685.                     "file" => $relativePath,
  5686.                 ]);
  5687.                 $processed["skipped"]++;
  5688.                 continue;
  5689.             }
  5690.  
  5691.             # Rewrite namespace.
  5692.            $projectNamespace = h("import.php.project.namespace", str_replace(D, "\\", $projectName), [$projectName]);
  5693.             $newNamespace = h("import.php.new.namespace", "$projectNamespace\\" . str_replace(D, "\\", $targetStructure), [$targetStructure]);
  5694.  
  5695.             $content = preg_replace($nsPattern, "namespace {$newNamespace};", $content, 1);
  5696.  
  5697.             # Rewrite use statements — handle both sub-namespace and direct imports.
  5698.            foreach ($namespaceMap as $oldNs => $newStruct) {
  5699.                 $newNs = "$projectNamespace\\" . str_replace(D, "\\", $newStruct);
  5700.                 $content = str_replace(["use {$oldNs}\\", "use {$oldNs};"], ["use {$newNs}\\", "use {$newNs};"], $content);
  5701.             }
  5702.  
  5703.             # Rewrite embedded asset path references (handles single and double quotes).
  5704.            foreach ($pathTransformations as $oldPath => $newPath) {
  5705.                 $content = preg_replace_callback(
  5706.                     h("import.path.pattern", "/(['\"])(.*?)" . preg_quote($oldPath, "/") . "(.*?)\\1/"),
  5707.                     fn($m) => $m[1] . $m[2] . $newPath . $m[3] . $m[1],
  5708.                     $content,
  5709.                 );
  5710.             }
  5711.  
  5712.             $content = h("import.php.content", $content, [$relativePath, $targetStructure]);
  5713.  
  5714.             # Write directly to $targetRoot — struct("new") targets PROJECT_PATH (the active
  5715.            # project), not $targetRoot, so we write + register with gitignore manually.
  5716.            # $targetStructure IS the relative directory path — mkdir creates it if absent.
  5717.            $typeSuffix = ucfirst($targetType);
  5718.             $phpFilename = h("import.php.filename", "{$className}{$typeSuffix}.php", [$className, $targetType]);
  5719.             $finalPath = h("import.php.finalpath", $targetRoot . $targetStructure . D . $phpFilename, [$className, $targetStructure]);
  5720.  
  5721.             if (!is_dir(dirname($finalPath))) {
  5722.                 mkdir(dirname($finalPath), 0777, true);
  5723.             }
  5724.  
  5725.             if (f($finalPath, "write", $content) === false) {
  5726.                 throw new RuntimeException("Failed to write PHP file: {$finalPath}");
  5727.             }
  5728.  
  5729.             _node_gitignore($finalPath, "write", project: $projectName);
  5730.  
  5731.             // Soft-delete source PHP file if reorganizing and file actually moved
  5732.             if ($reorganize && $isSelfImport) {
  5733.                 $srcAbs = $file["path"];
  5734.                 if (rtrim($srcAbs, D) !== rtrim($finalPath, D)) {
  5735.                     $softDelete($srcAbs);
  5736.                 }
  5737.             }
  5738.  
  5739.             $processed["php"]++;
  5740.             _node_import_update_session($sessionFile, "php", $relativePath, $finalPath, [
  5741.                 "type" => $targetType,
  5742.                 "structure" => $targetStructure,
  5743.             ]);
  5744.             r("Migrated PHP: {$className} ({$targetType}) -> {$targetStructure}", "Info", 0);
  5745.         }
  5746.  
  5747.         # 9. Write import manifest and register it.
  5748.        # Ensure the target root itself exists before writing the manifest.
  5749.        if (!is_dir($targetRoot)) {
  5750.             mkdir($targetRoot, 0777, true);
  5751.         }
  5752.  
  5753.         $duration = round(microtime(true) - $startTime, 2);
  5754.         $manifestPath = h("import.manifest.path", "{$targetRoot}import_manifest.json");
  5755.         $manifest = h("import.manifest", [
  5756.             "source" => $source,
  5757.             "target" => $projectName,
  5758.             "timestamp" => time(),
  5759.             "duration" => $duration,
  5760.             "mappings" => $namespaceMap,
  5761.             "assets" => $pathTransformations,
  5762.             "dynamic" => $newDynamic,
  5763.             "counts" => [
  5764.                 "total" => count($files),
  5765.                 "php" => $processed["php"],
  5766.                 "assets" => $processed["assets"],
  5767.                 "skipped" => $processed["skipped"],
  5768.                 "dynamic" => $processed["dynamic"],
  5769.             ],
  5770.             "git" => git(":target") ?: null,
  5771.         ]);
  5772.  
  5773.         if (f($manifestPath, "write", json_encode($manifest, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES))) {
  5774.             _node_gitignore($manifestPath, "write", project: $projectName);
  5775.         }
  5776.  
  5777.         # Register structure.json with gitignore so it's tracked in the target repo.
  5778.        $structureJsonPath = rtrim($targetRoot, D) . D . "structure.json";
  5779.         if (file_exists($structureJsonPath)) {
  5780.             _node_gitignore($structureJsonPath, "write", project: $projectName);
  5781.         }
  5782.  
  5783.         # Clean up session file.
  5784.        file_exists($sessionFile) && unlink($sessionFile);
  5785.  
  5786.         $summary = sprintf(
  5787.             "Import completed: %s (%d total, %d PHP, %d assets, %d skipped, %d new structures) in %.2fs",
  5788.             $projectName,
  5789.             count($files),
  5790.             $processed["php"],
  5791.             $processed["assets"],
  5792.             $processed["skipped"],
  5793.             $processed["dynamic"],
  5794.             $duration,
  5795.         );
  5796.  
  5797.         return r("Import completed: {$projectName}", "Info", $summary, $manifest["counts"]);
  5798.     } catch (Throwable $e) {
  5799.         # f(":rollback") here is still within the active phase (finalize), so the ops stack
  5800.        # key matches and all f() writes from this import run are correctly undone.
  5801.        f(":rollback");
  5802.         _node_gitignore(":rollback");
  5803.  
  5804.         file_exists($sessionFile) && unlink($sessionFile);
  5805.  
  5806.         return r("Import failed: " . $e->getMessage(), "Error", "Import failed.", [
  5807.             "exception" => get_class($e),
  5808.             "message" => $e->getMessage(),
  5809.             "file" => $e->getFile(),
  5810.             "line" => $e->getLine(),
  5811.             "error" => (array) $e,
  5812.             "processed" => $processed,
  5813.         ]);
  5814.     }
  5815. }
  5816.  
  5817. /**
  5818.  * Returns the default extension → structure path map used by import().
  5819.  * Extracted so h("import.asset.map") can replace or extend it cleanly.
  5820.  * Values must be valid struct(":keys") full path keys e.g. "Domain/Logic/Service".
  5821.  * Multi-dot extensions like ".blade.php" cannot be matched via getExtension()
  5822.  * and are intentionally omitted — handle them via h("import.asset.map") hook.
  5823.  */
  5824. function _node_import_default_asset_map(): array
  5825. {
  5826.     return [
  5827.         # Styles
  5828.        ".css" => "Presentation/Assets/Static/Style",
  5829.         ".scss" => "Presentation/Assets/Static/Style",
  5830.         ".sass" => "Presentation/Assets/Static/Style",
  5831.         ".less" => "Presentation/Assets/Static/Style",
  5832.         # Scripts
  5833.        ".js" => "Presentation/Assets/Static/Script",
  5834.         ".jsx" => "Presentation/Assets/Static/Script",
  5835.         ".ts" => "Presentation/Assets/Static/Script",
  5836.         ".tsx" => "Presentation/Assets/Static/Script",
  5837.         ".mjs" => "Presentation/Assets/Static/Script",
  5838.         # Images
  5839.        ".png" => "Presentation/Assets/Static/Image",
  5840.         ".jpg" => "Presentation/Assets/Static/Image",
  5841.         ".jpeg" => "Presentation/Assets/Static/Image",
  5842.         ".gif" => "Presentation/Assets/Static/Image",
  5843.         ".svg" => "Presentation/Assets/Static/Image",
  5844.         ".webp" => "Presentation/Assets/Static/Image",
  5845.         ".ico" => "Presentation/Assets/Static/Image",
  5846.         ".bmp" => "Presentation/Assets/Static/Image",
  5847.         # Fonts
  5848.        ".woff" => "Presentation/Assets/Static/Font",
  5849.         ".woff2" => "Presentation/Assets/Static/Font",
  5850.         ".ttf" => "Presentation/Assets/Static/Font",
  5851.         ".otf" => "Presentation/Assets/Static/Font",
  5852.         ".eot" => "Presentation/Assets/Static/Font",
  5853.         # Media (not in original asset map — added for completeness)
  5854.        ".mp3" => "Presentation/Assets/Static/Media",
  5855.         ".mp4" => "Presentation/Assets/Static/Media",
  5856.         ".webm" => "Presentation/Assets/Static/Media",
  5857.         # Templates
  5858.        ".html" => "Presentation/Assets/Template/Component",
  5859.         ".htm" => "Presentation/Assets/Template/Component",
  5860.         ".twig" => "Presentation/Assets/Template/Component",
  5861.         # Documentation
  5862.        ".md" => "Quality/Docs",
  5863.         ".rst" => "Quality/Docs",
  5864.         ".txt" => "Quality/Docs",
  5865.         # Data / Meta
  5866.        ".json" => "Presentation/Assets/Meta",
  5867.         ".xml" => "Presentation/Assets/Meta",
  5868.         ".yml" => "Presentation/Assets/Meta",
  5869.         ".yaml" => "Presentation/Assets/Meta",
  5870.         ".csv" => "Data/Persistence/Database/Storage/Flat/Index",
  5871.         ".sql" => "Data/Persistence/Database/Schema/Migration/Raw",
  5872.         # Config / Entry
  5873.        ".htaccess" => "Presentation/Assets/Entry",
  5874.         ".env" => "Presentation/Assets/Entry",
  5875.         ".ini" => "Presentation/Assets/Entry",
  5876.     ];
  5877. }
  5878.  
  5879. /**
  5880.  * Resolves a path that may be relative or absolute.
  5881.  * Returns realpath when resolvable, falls back to ROOT_PATH-relative, then original.
  5882.  */
  5883. function _node_import_resolve_path(string $path): string
  5884. {
  5885.     if ($real = realpath($path)) {
  5886.         return $real;
  5887.     }
  5888.     if (str_starts_with($path, "./") || str_starts_with($path, "../")) {
  5889.         if ($real = realpath(ROOT_PATH . $path)) {
  5890.             return $real;
  5891.         }
  5892.     }
  5893.     return $path;
  5894. }
  5895.  
  5896. /**
  5897.  * Reads a file that may live outside ROOT_PATH.
  5898.  * Uses f() (with hook + audit trail) when the path is inside ROOT_PATH,
  5899.  * falls back to a direct read for external source directories.
  5900.  */
  5901. function _node_import_read_external(string $path): ?string
  5902. {
  5903.     if (str_starts_with($path, ROOT_PATH)) {
  5904.         return f($path, "read", null, false);
  5905.     }
  5906.     $content = @file_get_contents($path);
  5907.     return $content !== false ? $content : null;
  5908. }
  5909.  
  5910. /**
  5911.  * Resolves a filesystem path hint to the best-matching struct(":keys") key.
  5912.  * The returned value is a full struct path e.g. "Domain/Logic/Service" which
  5913.  * doubles as the relative directory path under PROJECT_PATH.
  5914.  * Three-pass strategy: exact segment match → containment → fuzzy similarity.
  5915.  *
  5916.  * @param string $hint    Filesystem-style hint (e.g. "Services/Auth").
  5917.  * @param array  $allKeys Merged keys array (builtin + dynamic).
  5918.  * @return string|null    Matched key, or null if no confident match.
  5919.  */
  5920. function _node_import_find_structure(string $hint, array $allKeys): ?string
  5921. {
  5922.     if (empty($hint) || $hint === "." || $hint === D) {
  5923.         return null;
  5924.     }
  5925.  
  5926.     $hint = trim(str_replace(["\\", "/"], D, $hint), D);
  5927.     $hintLower = strtolower($hint);
  5928.  
  5929.     # Pass 1: exact suffix / prefix match.
  5930.    $exactMatches = [];
  5931.     foreach (array_keys($allKeys) as $structPath) {
  5932.         $norm = strtolower(str_replace(["\\", "/"], D, $structPath));
  5933.         if ($norm === $hintLower) {
  5934.             return $structPath; # Perfect match.
  5935.        }
  5936.         if (str_ends_with($norm, $hintLower) || str_starts_with($norm, $hintLower)) {
  5937.             $exactMatches[] = $structPath;
  5938.         }
  5939.     }
  5940.     if (!empty($exactMatches)) {
  5941.         usort($exactMatches, fn($a, $b) => strlen($a) - strlen($b));
  5942.         return $exactMatches[0];
  5943.     }
  5944.  
  5945.     # Pass 2: containment — hint appears anywhere in the structure path.
  5946.    $containsMatches = [];
  5947.     foreach (array_keys($allKeys) as $structPath) {
  5948.         $norm = strtolower(str_replace(["\\", "/"], D, $structPath));
  5949.         if (str_contains($norm, $hintLower)) {
  5950.             $containsMatches[] = $structPath;
  5951.         }
  5952.     }
  5953.     if (!empty($containsMatches)) {
  5954.         # Prefer the match where the hint appears deepest (latest strpos = most specific).
  5955.        usort($containsMatches, function ($a, $b) use ($hintLower) {
  5956.             $aPos = strpos(strtolower(str_replace(["\\", "/"], D, $a)), $hintLower);
  5957.             $bPos = strpos(strtolower(str_replace(["\\", "/"], D, $b)), $hintLower);
  5958.             return $bPos - $aPos;
  5959.         });
  5960.         return $containsMatches[0];
  5961.     }
  5962.  
  5963.     # Pass 3: fuzzy similarity fallback.
  5964.    $threshold = h("import.structure.match.threshold", 50);
  5965.     $bestMatch = null;
  5966.     $bestScore = 0;
  5967.     foreach (array_keys($allKeys) as $structPath) {
  5968.         similar_text($hint, str_replace(["\\", "/"], D, $structPath), $percent);
  5969.         if ($percent > $bestScore) {
  5970.             $bestScore = $percent;
  5971.             $bestMatch = $structPath;
  5972.         }
  5973.     }
  5974.  
  5975.     return $bestScore >= $threshold ? $bestMatch : null;
  5976. }
  5977.  
  5978. /**
  5979.  * Infers a structure.json path from a fully-qualified namespace that could not
  5980.  * be matched against any known structure.
  5981.  *
  5982.  * Strategy:
  5983.  *   Given "Shuffle\Views\Pages" with projectName "Shuffle":
  5984.  *   1. Strip the project prefix segment if present.
  5985.  *   2. Convert remaining namespace segments to a D-separated path.
  5986.  *   3. Return the inferred path e.g. "Views/Pages".
  5987.  *
  5988.  * The result becomes a new leaf in structure.json. The human can later
  5989.  * rename or reorganise entries in that file — import just needs a stable
  5990.  * placeholder so files are placed somewhere sensible rather than skipped.
  5991.  *
  5992.  * Returns null only when the namespace is empty or identical to the project name.
  5993.  *
  5994.  * @param string $fullyQualifiedNamespace  e.g. "Shuffle\Views\Pages"
  5995.  * @param string $projectName              e.g. "Shuffle"
  5996.  * @return string|null
  5997.  */
  5998. function _node_import_infer_structure(string $fullyQualifiedNamespace, string $projectName): ?string
  5999. {
  6000.     $parts = explode("\\", trim($fullyQualifiedNamespace, "\\"));
  6001.  
  6002.     # Strip leading segment if it matches the project name (case-insensitive).
  6003.    if (!empty($parts) && strtolower($parts[0]) === strtolower($projectName)) {
  6004.         array_shift($parts);
  6005.     }
  6006.  
  6007.     $parts = array_filter($parts); # Remove empty segments.
  6008.    if (empty($parts)) {
  6009.         return null;
  6010.     }
  6011.  
  6012.     return implode(D, $parts);
  6013. }
  6014.  
  6015. /**
  6016.  * Detects the PHP declaration type (Class, Interface, Trait, Enum) from source content.
  6017.  */
  6018. function _node_import_detect_type(string $content): string
  6019. {
  6020.     $patterns = h("import.php.type.patterns", [
  6021.         "Enum" => "/\benum\s+\w+/",
  6022.         "Interface" => "/\binterface\s+\w+/",
  6023.         "Trait" => "/\btrait\s+\w+/",
  6024.         "Class" => "/\bclass\s+\w+/",
  6025.     ]);
  6026.  
  6027.     foreach ($patterns as $type => $pattern) {
  6028.         if (preg_match($pattern, $content)) {
  6029.             return $type;
  6030.         }
  6031.     }
  6032.  
  6033.     return "Class";
  6034. }
  6035.  
  6036. /**
  6037.  * Shows status of any in-progress import sessions left in the temp directory.
  6038.  */
  6039. function _node_import_status(): string
  6040. {
  6041.     $sessions = glob(sys_get_temp_dir() . D . "import_session_*") ?: [];
  6042.  
  6043.     if (empty($sessions)) {
  6044.         return "No active import sessions.\n";
  6045.     }
  6046.  
  6047.     $output = ["Active import sessions:", ""];
  6048.     foreach ($sessions as $session) {
  6049.         $raw = @file_get_contents($session);
  6050.         $data = $raw ? json_decode($raw, true) : null;
  6051.         if ($data) {
  6052.             $age = time() - ($data["started"] ?? time());
  6053.             $output[] = sprintf(
  6054.                 "  %s: %s (%d files, %d processed) %dm ago",
  6055.                 basename($session),
  6056.                 $data["project"] ?? "?",
  6057.                 count($data["files"] ?? []),
  6058.                 count($data["processed"] ?? []),
  6059.                 (int) floor($age / 60),
  6060.             );
  6061.         }
  6062.     }
  6063.  
  6064.     return implode("\n", $output) . "\n";
  6065. }
  6066.  
  6067. /**
  6068.  * Appends a processed-file entry to the import session tracking file.
  6069.  * Uses file_get_contents/file_put_contents directly — session files live in
  6070.  * sys_get_temp_dir() outside ROOT_PATH and are not part of the f() rollback stack.
  6071.  */
  6072. function _node_import_update_session(string $sessionFile, string $type, string $source, string $target, array $meta = []): void
  6073. {
  6074.     if (!file_exists($sessionFile)) {
  6075.         return;
  6076.     }
  6077.  
  6078.     $raw = @file_get_contents($sessionFile);
  6079.     $data = $raw ? json_decode($raw, true) : null;
  6080.  
  6081.     if (is_array($data)) {
  6082.         $data["processed"][] = [
  6083.             "type" => $type,
  6084.             "source" => $source,
  6085.             "target" => $target,
  6086.             "meta" => $meta,
  6087.             "time" => time(),
  6088.         ];
  6089.         file_put_contents($sessionFile, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
  6090.     }
  6091. }
  6092. # import end;
  6093.  
  6094. function _node_project(string $key = "name", ?string $set = null): string
  6095. {
  6096.     static $state = ["name" => null, "path" => null];
  6097.  
  6098.     if ($set !== null) {
  6099.         $state["name"] = h("project.name", $set);
  6100.         $state["path"] = h("project.path", ROOT_PATH . $state["name"] . D);
  6101.     }
  6102.  
  6103.     if ($state["name"] === null) {
  6104.         // Bootstrap default — same logic as before
  6105.         $state["name"] = h("project.name", _node_gitrepo() ?? FW_NAME);
  6106.         $state["path"] = h("project.path", ROOT_PATH . $state["name"] . D);
  6107.     }
  6108.  
  6109.     return $state[$key] ?? "";
  6110. }
  6111.  
  6112. // Backward-compat shims so existing code keeps working untouched
  6113. define("PROJECT_NAME", _node_project("name"));
  6114. define("PROJECT_PATH", _node_project("path"));
  6115.  
  6116. # migrate begin dev
  6117. /**
  6118.  * Functions auto-recorded by default when autorecord is on.
  6119.  * Extend via node.json "autorecord_functions" array.
  6120.  */
  6121. define("MIGRATE_AUTORECORD_FUNCTIONS", h("migrate.autorecord.default_fns", ["struct", "node", "git", "import"]));
  6122.  
  6123. function _node_migrate_path(): string
  6124. {
  6125.     if (is_numeric($path = struct(":structure:path", "Migration/File"))) {
  6126.         die("Structure does not support migration file.");
  6127.     }
  6128.     return _node_project("path") . $path . D;
  6129. }
  6130.  
  6131. function _node_migrate_blockchain_file(?string $blockchain = null): string
  6132. {
  6133.     if ($blockchain === null) {
  6134.         $nodeJson = _node_migrate_load(_node_project("path") . "node.json");
  6135.         $deployId = $nodeJson["deployment_id"] ?? "default";
  6136.         $blockchain = "migration.blockchain.{$deployId}";
  6137.     }
  6138.     return h("migrate.blockchain.file", _node_project("path") . "{$blockchain}.json");
  6139. }
  6140.  
  6141. function _node_migrate_registry_file(?string $migration = null): string
  6142. {
  6143.     if (is_numeric($path = struct(":structure:path", "Migration/Registry"))) {
  6144.         die("Structure does not support migration registry file.");
  6145.     }
  6146.     if ($migration === null) {
  6147.         $nodeJson = _node_migrate_load(_node_project("path") . "node.json");
  6148.         $deployId = $nodeJson["deployment_id"] ?? "default";
  6149.         $migration = "migration.{$deployId}";
  6150.     }
  6151.     return h("migrate.registry.file", _node_project("path") . "{$path}{$migration}.json");
  6152. }
  6153.  
  6154. /**
  6155.  * Load JSON file — returns [] on missing or malformed.
  6156.  */
  6157. function _node_migrate_load(string $path): array
  6158. {
  6159.     if (!file_exists($path)) {
  6160.         return [];
  6161.     }
  6162.     $raw = @file_get_contents($path);
  6163.     if (!$raw || trim($raw) === "") {
  6164.         return [];
  6165.     }
  6166.     $decoded = json_decode($raw, true);
  6167.     return is_array($decoded) ? $decoded : [];
  6168. }
  6169.  
  6170. function _node_migrate_save(string $path, array $data): bool
  6171. {
  6172.     $dir = dirname($path);
  6173.     if (!is_dir($dir)) {
  6174.         mkdir($dir, 0777, true);
  6175.     }
  6176.     return (bool) file_put_contents($path, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
  6177. }
  6178.  
  6179. /**
  6180.  * Compute the hash for a block.
  6181.  * hash = md5(prev_hash . cmd . datetime)
  6182.  */
  6183. function _node_migrate_hash(string $prevHash, string $cmd, string $datetime): string
  6184. {
  6185.     return md5("$prevHash$cmd$datetime");
  6186. }
  6187.  
  6188. /**
  6189.  * Validate entire chain integrity. Returns true if all hashes reproduce correctly.
  6190.  */
  6191. function _node_migrate_validate_chain(array $chain): bool
  6192. {
  6193.     $prev = "";
  6194.     foreach ($chain as $block) {
  6195.         $expected = _node_migrate_hash($prev, $block["cmd"], $block["datetime"]);
  6196.         if ($expected !== $block["hash"]) {
  6197.             return false;
  6198.         }
  6199.         $prev = $block["hash"];
  6200.     }
  6201.     return true;
  6202. }
  6203.  
  6204. /**
  6205.  * Append one block to a chain array (does NOT write to disk).
  6206.  */
  6207. function _node_migrate_append_block(array &$chain, string $cmd): array
  6208. {
  6209.     $prev = empty($chain) ? "" : end($chain)["hash"];
  6210.     $dt = date("Y-m-d H:i:s");
  6211.     $hash = _node_migrate_hash($prev, $cmd, $dt);
  6212.  
  6213.     $block = h("migrate.block", [
  6214.         "hash" => $hash,
  6215.         "cmd" => $cmd,
  6216.         "datetime" => $dt,
  6217.     ]);
  6218.  
  6219.     $chain[] = $block;
  6220.     return $block;
  6221. }
  6222.  
  6223. /**
  6224.  * Ensure blockchain.json exists and has a deployment_id.
  6225.  * Creates the file if absent. Returns the deployment_id.
  6226.  */
  6227. function _node_migrate_ensure_blockchain(): string
  6228. {
  6229.     $file = _node_migrate_blockchain_file();
  6230.     $data = _node_migrate_load($file);
  6231.  
  6232.     if (empty($data["deployment_id"])) {
  6233.         $data["deployment_id"] = md5(uniqid("node_deploy_", true));
  6234.         $data["created_at"] = date("Y-m-d H:i:s");
  6235.         $data["chain"] = [];
  6236.         _node_migrate_save($file, $data);
  6237.         _node_gitignore($file, "write");
  6238.         r("Blockchain initialised for deployment " . $data["deployment_id"], "Migrate", 0);
  6239.     }
  6240.  
  6241.     return $data["deployment_id"];
  6242. }
  6243.  
  6244. function migrate(mixed ...$args): mixed
  6245. {
  6246.     $args = array_filter($args, fn($a) => $a !== null && $a !== "");
  6247.  
  6248.     if (empty($args)) {
  6249.         return implode(
  6250.             "\n",
  6251.             h("migrate.help", [
  6252.                 "migrate <file> Run a migration file (without .json extension).",
  6253.                 "migrate all Run all pending migration files in order.",
  6254.                 "migrate store <cmd ...> Append a command to local blockchain.json.",
  6255.                 "migrate list List all migration files.",
  6256.                 "migrate autorecord <?[on|off]> Show or set autorecord flag in node.json.",
  6257.                 "migrate record <function> <?[on|off]> Show or toggle per-function autorecord in node.json.",
  6258.                 "migrate rollback <hash> Flush and replay chain up to given hash (requires inception_autorecord).",
  6259.                 "migrate lookup <query> Search blockchain blocks by cmd prefix or date pattern.",
  6260.             ]),
  6261.         );
  6262.     }
  6263.  
  6264.     # Resources of operation
  6265.    $migrationDir = _node_migrate_path(); // Foreign blockchians
  6266.     $blockchainFile = _node_migrate_blockchain_file(); // Local blockchain
  6267.     $registryFile = _node_migrate_registry_file(); // Registry of operated foreign blockchains
  6268.  
  6269.     $nodeJsonFile = _node_project("path") . "node.json";
  6270.  
  6271.     $loadNodeJson = fn(): array => _node_migrate_load($nodeJsonFile);
  6272.     $saveNodeJson = fn(array $data): bool => _node_migrate_save($nodeJsonFile, $data);
  6273.  
  6274.     if (str_starts_with($args[0], "store")) {
  6275.         if (empty(($cmd = _node_argex($args, 1)))) {
  6276.             return r("migrate store: provide a command string.", "Info", 1);
  6277.         }
  6278.         _node_migrate_ensure_blockchain();
  6279.  
  6280.         $bData = _node_migrate_load($blockchainFile);
  6281.         $chain = &$bData["chain"];
  6282.  
  6283.         $block = _node_migrate_append_block($chain, $cmd);
  6284.  
  6285.         if (!_node_migrate_save($blockchainFile, $bData)) {
  6286.             return r("migrate store: could not write blockchain.json", "Error", 2);
  6287.         }
  6288.         return h("migrate.store.result", "Stored [{$block["hash"]}] {$cmd}\n");
  6289.     }
  6290.  
  6291.     if (str_starts_with($args[0], "autorecord")) {
  6292.         $flag = _node_argex($args, 1, 1) ?: null;
  6293.  
  6294.         if (empty(($data = $loadNodeJson()))) {
  6295.             return r("node.json not found. Run: node init", "Info", 1);
  6296.         }
  6297.  
  6298.         if ($flag === null) {
  6299.             $current = $data["autorecord"] ?? false;
  6300.             return "autorecord is " . ($current ? "on" : "off") . "\n";
  6301.         }
  6302.  
  6303.         if (!in_array($flag, ["on", "off"])) {
  6304.             return r("migrate autorecord: use 'on' or 'off'", "Info", 1);
  6305.         }
  6306.  
  6307.         $data["autorecord"] = $flag === "on";
  6308.         return $saveNodeJson($data) ? "autorecord set to {$flag}\n" : r("Could not save node.json", "Error", 2);
  6309.     }
  6310.  
  6311.     if (str_starts_with($args[0], "record")) {
  6312.         if (!($fn = _node_argex($args, 1, 1))) {
  6313.             return r("migrate record: provide a function name.", "Info", 1);
  6314.         }
  6315.         $flag = _node_argex($args, 2, 1) ?: null;
  6316.  
  6317.         if (empty(($data = $loadNodeJson()))) {
  6318.             return r("node.json not found. Run: node init", "Info", 1);
  6319.         }
  6320.  
  6321.         $extra = $data["autorecord_functions"] ?? [];
  6322.  
  6323.         if ($flag === null) {
  6324.             $inDefault = in_array($fn, MIGRATE_AUTORECORD_FUNCTIONS);
  6325.             $inExtra = in_array($fn, $extra);
  6326.             $status = $inDefault || $inExtra ? "on" : "off";
  6327.             $source = $inDefault ? " (built-in)" : ($inExtra ? " (custom)" : "");
  6328.             return "record {$fn}: {$status}{$source}\n";
  6329.         }
  6330.         if (!in_array($flag, ["on", "off"])) {
  6331.             return r("migrate record: use 'on' or 'off'", "Info", 1);
  6332.         }
  6333.         if ($flag === "on") {
  6334.             if (!in_array($fn, $extra) && !in_array($fn, MIGRATE_AUTORECORD_FUNCTIONS)) {
  6335.                 $extra[] = $fn;
  6336.                 $data["autorecord_functions"] = array_values($extra);
  6337.                 return $saveNodeJson($data) ? "record {$fn}: on\n" : r("Could not save node.json", "Error", 2);
  6338.             }
  6339.             return "record {$fn}: already on\n";
  6340.         }
  6341.         if (in_array($fn, MIGRATE_AUTORECORD_FUNCTIONS)) {
  6342.             return r("migrate record: '{$fn}' is a built-in recorded function and cannot be turned off.", "Info", 1);
  6343.         }
  6344.         if (!in_array($fn, $extra)) {
  6345.             return "record {$fn}: already off\n";
  6346.         }
  6347.         $data["autorecord_functions"] = array_values(array_filter($extra, fn($f) => $f !== $fn));
  6348.         return $saveNodeJson($data) ? "record {$fn}: off\n" : r("Could not save node.json", "Error", 2);
  6349.     }
  6350.  
  6351.     if (str_starts_with($args[0], "list")) {
  6352.         $files = glob("$migrationDir*.json") ?: [];
  6353.         if (empty($files)) {
  6354.             return "No migration files found in {$migrationDir}\n";
  6355.         }
  6356.         $registry = _node_migrate_load($registryFile);
  6357.         $out = "";
  6358.         foreach ($files as $f) {
  6359.             $name = basename($f, ".json");
  6360.             $data = _node_migrate_load($f);
  6361.             $id = $data["deployment_id"] ?? "?";
  6362.             $steps = count($data["chain"] ?? []);
  6363.             $done = $registry[$id]["step"] ?? 0;
  6364.             $out .= "  {$name} [{$id}] {$done}/{$steps} steps done\n";
  6365.         }
  6366.         return $out;
  6367.     }
  6368.  
  6369.     if (str_starts_with($args[0], "lookup")) {
  6370.         if (empty(($query = _node_argex($args, 1)))) {
  6371.             return r("migrate lookup: provide a query.", "Info", 1);
  6372.         }
  6373.  
  6374.         $bData = _node_migrate_load($blockchainFile);
  6375.         $chain = $bData["chain"] ?? [];
  6376.  
  6377.         // Date pattern detection: YYYY, YYYY-MM, YYYY-MM-DD
  6378.         $isDate = preg_match('/^\d{4}(-\d{2}(-\d{2})?)?$/', $query);
  6379.  
  6380.         $results = [];
  6381.         if ($isDate) {
  6382.             foreach ($chain as $block) {
  6383.                 if (str_starts_with($block["datetime"], $query)) {
  6384.                     $results[] = $block;
  6385.                 }
  6386.             }
  6387.             // Sort ascending by datetime (already in insertion order, but make explicit)
  6388.             usort($results, fn($a, $b) => strcmp($a["datetime"], $b["datetime"]));
  6389.         } else {
  6390.             foreach ($chain as $block) {
  6391.                 if (str_starts_with($block["cmd"], $query)) {
  6392.                     $results[] = $block;
  6393.                 }
  6394.             }
  6395.         }
  6396.  
  6397.         if (empty($results)) {
  6398.             return "No blocks matched '{$query}'\n";
  6399.         }
  6400.  
  6401.         $out = "Found " . count($results) . " block(s) matching '{$query}':\n";
  6402.         foreach ($results as $block) {
  6403.             $out .= "  [{$block["hash"]}] {$block["datetime"]}  {$block["cmd"]}\n";
  6404.         }
  6405.         return $out;
  6406.     }
  6407.  
  6408.     if (str_starts_with($args[0], "rollback")) {
  6409.         if (!($targetHash = _node_argex($args, 1))) {
  6410.             return r("migrate rollback: provide a migration hash.", "Info", 1);
  6411.         }
  6412.         $nodeJson = $loadNodeJson();
  6413.         if (empty($nodeJson["inception_autorecord"])) {
  6414.             return r("migrate rollback: inception_autorecord is not enabled in node.json.", "Info", 1);
  6415.         }
  6416.  
  6417.         $bData = _node_migrate_load($blockchainFile);
  6418.         $chain = $bData["chain"] ?? [];
  6419.  
  6420.         if (!_node_migrate_validate_chain($chain)) {
  6421.             return r("migrate rollback: blockchain integrity check FAILED. Aborting.", "Error", 3);
  6422.         }
  6423.  
  6424.         $targetIndex = null;
  6425.         foreach ($chain as $i => $block) {
  6426.             if ($block["hash"] === $targetHash) {
  6427.                 $targetIndex = $i;
  6428.                 break;
  6429.             }
  6430.         }
  6431.  
  6432.         if ($targetIndex === null) {
  6433.             return r("migrate rollback: hash '{$targetHash}' not found in blockchain.", "Error", 2);
  6434.         }
  6435.  
  6436.         // Slice chain to replay
  6437.         $replayChain = array_slice($chain, 0, $targetIndex + 1);
  6438.  
  6439.         r("migrate rollback: replaying " . count($replayChain) . " steps to hash {$targetHash}", "Migrate", 0);
  6440.  
  6441.         // Flush project files tracked by gitignore (all project files)
  6442.         $projectFiles = _node_gitignore(":list:all");
  6443.         foreach ($projectFiles as $relPath) {
  6444.             $abs = ROOT_PATH . ltrim($relPath, "!");
  6445.             if (file_exists($abs) && !is_dir($abs)) {
  6446.                 unlink($abs);
  6447.             }
  6448.         }
  6449.  
  6450.         // TODO: when db() function becomes available Flush database.
  6451.  
  6452.         // Replay each command
  6453.         foreach ($replayChain as $block) {
  6454.             $parts = array_map("trim", explode(" ", $block["cmd"]));
  6455.             $fn = array_shift($parts);
  6456.             if (function_exists($fn)) {
  6457.                 try {
  6458.                     call_user_func_array($fn, $parts);
  6459.                 } catch (Throwable $e) {
  6460.                     r("migrate rollback: command failed [{$block["cmd"]}]: " . $e->getMessage(), "Error", 0);
  6461.                 }
  6462.             } else {
  6463.                 r("migrate rollback: unknown function '{$fn}' in block [{$block["hash"]}], skipping.", "Migrate", 0);
  6464.             }
  6465.         }
  6466.  
  6467.         // Truncate blockchain to replayed state
  6468.         $bData["chain"] = $replayChain;
  6469.         _node_migrate_save($blockchainFile, $bData);
  6470.  
  6471.         return "Rollback complete. State restored to [{$targetHash}].\n";
  6472.     }
  6473.  
  6474.     $executeFile = function (string $filePath) use ($registryFile, $blockchainFile): string {
  6475.         $data = _node_migrate_load($filePath);
  6476.  
  6477.         if (empty($data["deployment_id"]) || empty($data["chain"])) {
  6478.             return r("migrate: invalid or empty migration file: {$filePath}", "Error", "Invalid file.\n");
  6479.         }
  6480.  
  6481.         $foreignId = $data["deployment_id"];
  6482.         $chain = $data["chain"];
  6483.  
  6484.         // Integrity check
  6485.         if (!_node_migrate_validate_chain($chain)) {
  6486.             return r("migrate: chain integrity FAILED for {$foreignId}. File was tampered. Aborting.", "Error", "Integrity failure.\n");
  6487.         }
  6488.  
  6489.         // Find resume point
  6490.         $registry = _node_migrate_load($registryFile);
  6491.         $doneStep = $registry[$foreignId]["step"] ?? 0;
  6492.         $toExecute = array_slice($chain, $doneStep);
  6493.  
  6494.         if (empty($toExecute)) {
  6495.             return "  " . basename($filePath, ".json") . ": already up to date ({$doneStep} steps).\n";
  6496.         }
  6497.  
  6498.         // Execute pending steps
  6499.         $executed = 0;
  6500.         $lastHash = "";
  6501.  
  6502.         // Ensure our own blockchain is initialised for recording
  6503.         _node_migrate_ensure_blockchain();
  6504.         $bData = _node_migrate_load($blockchainFile);
  6505.         $localChain = &$bData["chain"];
  6506.  
  6507.         foreach ($toExecute as $block) {
  6508.             $parts = array_map("trim", explode(" ", $block["cmd"]));
  6509.             $fn = array_shift($parts);
  6510.  
  6511.             try {
  6512.                 if (function_exists($fn)) {
  6513.                     call_user_func_array($fn, $parts);
  6514.                 } else {
  6515.                     r("migrate: unknown function '{$fn}' in block [{$block["hash"]}], skipping.", "Migrate", 0);
  6516.                 }
  6517.             } catch (Throwable $e) {
  6518.                 r("migrate: command failed [{$block["cmd"]}]: " . $e->getMessage(), "Error", 0);
  6519.             }
  6520.  
  6521.             // Record this executed step in our own blockchain
  6522.             _node_migrate_append_block($localChain, "migrated_from:{$foreignId} " . $block["cmd"]);
  6523.  
  6524.             $lastHash = $block["hash"];
  6525.             $executed++;
  6526.         }
  6527.  
  6528.         // Persist local blockchain
  6529.         _node_migrate_save($blockchainFile, $bData);
  6530.  
  6531.         // Update registry
  6532.         $registry[$foreignId] = [
  6533.             "file" => basename($filePath),
  6534.             "step" => $doneStep + $executed,
  6535.             "last_hash" => $lastHash,
  6536.             "last_migrated_at" => date("Y-m-d H:i:s"),
  6537.         ];
  6538.  
  6539.         _node_migrate_save($registryFile, $registry);
  6540.         _node_gitignore($registryFile, "write");
  6541.  
  6542.         return h("migrate.file.result", "  " . basename($filePath, ".json") . ": {$executed} step(s) executed (total: " . ($doneStep + $executed) . ").\n");
  6543.     };
  6544.  
  6545.     if (str_starts_with($args[0], "all")) {
  6546.         if (!is_dir($migrationDir)) {
  6547.             return "No migration directory found at {$migrationDir}\n";
  6548.         }
  6549.         $files = glob("{$migrationDir}*.json") ?: [];
  6550.         if (empty($files)) {
  6551.             return "No migration files found.\n";
  6552.         }
  6553.         sort($files); // alphabetical = chronological if files are named well
  6554.         $out = "Running all migrations:\n";
  6555.         foreach ($files as $f) {
  6556.             $out .= $executeFile($f);
  6557.         }
  6558.         return $out;
  6559.     }
  6560.  
  6561.     // Single file: migrate <name>
  6562.     $name = $args[0];
  6563.     $filePath = "$migrationDir$name.json";
  6564.     if (!file_exists($filePath)) {
  6565.         return r("migrate: file not found: {$filePath}", "Error", "File not found.\n");
  6566.     }
  6567.     return $executeFile($filePath);
  6568. }
  6569. # migrate end
  6570.  
  6571. # node begin dev
  6572. /**
  6573.  * CRUD manager for node.json — project manifest, entry point, and dependency registry.
  6574.  *
  6575.  * node Show help
  6576.  * node spawn <user>/<project> Creates new or fetches existing NodePHP project with given project name
  6577.  * node target <?project> Targets NodePHP to given project or shows targeted project
  6578.  * node entry <path> Set entry point (relative to PROJECT_PATH)
  6579.  * node dep add <name>  Add a dependency project name
  6580.  * node dep remove <name>  Remove a dependency project name
  6581.  * node dep list List current dependencies
  6582.  * node meta <key> <value> Set a meta key
  6583.  * node init Create node.json with empty scaffold if absent
  6584.  * node show Pretty-print current node.json
  6585.  */
  6586. function node(mixed ...$args): mixed
  6587. {
  6588.     $args = array_filter($args, fn($a) => $a !== null && $a !== "");
  6589.  
  6590.     $file = h("node.json.path", _node_project("path") . "node.json");
  6591.  
  6592.     $load = function () use ($file): array {
  6593.         if (!file_exists($file)) {
  6594.             return [];
  6595.         }
  6596.         $raw = f($file, "read", null, false);
  6597.         if (!$raw) {
  6598.             return [];
  6599.         }
  6600.         $decoded = json_decode($raw, true);
  6601.         return is_array($decoded) ? $decoded : [];
  6602.     };
  6603.  
  6604.     $save = function (array $data) use ($file): bool {
  6605.         $encoded = json_encode(h("node.json.data", $data), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
  6606.         $result = f($file, "write", $encoded);
  6607.         if ($result !== false) {
  6608.             _node_gitignore($file, "write");
  6609.         }
  6610.         return $result !== false;
  6611.     };
  6612.  
  6613.     if (empty($args)) {
  6614.         return implode(
  6615.             "\n",
  6616.             h("node.help", [
  6617.                 "node spawn <user>/<project> Spawns existing or new NodePHP poject",
  6618.                 "node target <?project> Targets NodePHP on project ot shows current target",
  6619.                 "node entry <path> Set entry point relative to project root",
  6620.                 "node dep add <name> Add dependency project",
  6621.                 "node dep remove <name> Remove dependency project",
  6622.                 "node dep list List dependencies",
  6623.                 "node meta <key> <value> Set metadata key",
  6624.                 "node init Scaffold node.json if absent",
  6625.                 "node show Pretty-print node.json",
  6626.             ]),
  6627.         );
  6628.     }
  6629.  
  6630.     if ($args[0] === ":json") {
  6631.         return $load();
  6632.     }
  6633.  
  6634.     if ($args[0] === ":entry") {
  6635.         return h("node.entry", $load()["entry"] ?? null);
  6636.     }
  6637.  
  6638.     if ($args[0] === ":deps") {
  6639.         return h("node.deps", $load()["dependencies"] ?? []);
  6640.     }
  6641.  
  6642.     if ($args[0] === ":check") {
  6643.         $missing = [];
  6644.         foreach (node(":deps") as $dep) {
  6645.             $depPath = h("node.dep.path", ROOT_PATH . $dep);
  6646.             if (!is_dir($depPath)) {
  6647.                 $missing[] = $dep;
  6648.             }
  6649.         }
  6650.         return h("node.check.missing", $missing);
  6651.     }
  6652.  
  6653.     if ($args[0] === ":scaffold") {
  6654.         return h("node.init.scaffold", [
  6655.             "entry" => "",
  6656.             "dependencies" => [],
  6657.             "autorecord" => false,
  6658.             "inception_autorecord" => false,
  6659.             "autorecord_functions" => [],
  6660.             "build" => null,
  6661.             "build_dist" => null,
  6662.             "meta" => [
  6663.                 "version" => "0.1.0",
  6664.                 "description" => "",
  6665.             ],
  6666.         ]);
  6667.     }
  6668.  
  6669.     if ($args[0] === "init") {
  6670.         if (file_exists($file)) {
  6671.             return r("node.json already exists at: {$file}", "Info", "Already initialised.\n");
  6672.         }
  6673.         $scaffold = node(":scaffold");
  6674.         return $save($scaffold) ? "node.json created at: {$file}\n" : r("Could not create node.json", "Error", 2);
  6675.     }
  6676.  
  6677.     if ($args[0] === "show") {
  6678.         $data = $load();
  6679.         if (empty($data)) {
  6680.             return "No node.json found. Run: node init\n";
  6681.         }
  6682.         return json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . "\n";
  6683.     }
  6684.  
  6685.     if (str_starts_with($args[0], "spawn")) {
  6686.         return git(...$args);
  6687.     }
  6688.  
  6689.     if (str_starts_with($args[0], "target")) {
  6690.         return git(...$args);
  6691.     }
  6692.  
  6693.     if (str_starts_with($args[0], "entry")) {
  6694.         $path = _node_argex($args, 1);
  6695.         if (empty($path)) {
  6696.             return r("node entry: provide a relative path", "Info", 1);
  6697.         }
  6698.         $data = $load();
  6699.         if (empty($data)) {
  6700.             return r("node.json not found. Run: node init", "Info", 1);
  6701.         }
  6702.         $data["entry"] = h("node.entry.set", $path);
  6703.         return $save($data) ? "Entry point set to: {$path}\n" : r("Could not save node.json", "Error", 2);
  6704.     }
  6705.  
  6706.     if (str_starts_with($args[0], "dep")) {
  6707.         $sub = _node_argex($args, 1, 1);
  6708.  
  6709.         if ($sub === "list") {
  6710.             $deps = node(":deps");
  6711.             if (empty($deps)) {
  6712.                 return "No dependencies defined.\n";
  6713.             }
  6714.             $lines = array_map(function ($dep) {
  6715.                 $exists = is_dir(ROOT_PATH . $dep);
  6716.                 $status = $exists ? "\033[32m✓\033[0m" : "\033[31m✗ missing\033[0m";
  6717.                 return "  {$status} {$dep}";
  6718.             }, $deps);
  6719.             return implode("\n", $lines) . "\n";
  6720.         }
  6721.  
  6722.         if ($sub === "add") {
  6723.             $name = _node_argex($args, 2);
  6724.             if (empty($name)) {
  6725.                 return r("node dep add: provide a project name", "Info", 1);
  6726.             }
  6727.             $data = $load();
  6728.             if (empty($data)) {
  6729.                 return r("node.json not found. Run: node init", "Info", 1);
  6730.             }
  6731.             $deps = $data["dependencies"] ?? [];
  6732.             if (in_array($name, $deps)) {
  6733.                 return "Dependency already listed: {$name}\n";
  6734.             }
  6735.             $deps[] = h("node.dep.add", $name);
  6736.             $data["dependencies"] = array_values($deps);
  6737.             return $save($data) ? "Added dependency: {$name}\n" : r("Could not save node.json", "Error", 2);
  6738.         }
  6739.  
  6740.         if ($sub === "remove") {
  6741.             $name = _node_argex($args, 2);
  6742.             if (empty($name)) {
  6743.                 return r("node dep remove: provide a project name", "Info", 1);
  6744.             }
  6745.             $data = $load();
  6746.             if (empty($data)) {
  6747.                 return r("node.json not found. Run: node init", "Info", 1);
  6748.             }
  6749.             $before = count($data["dependencies"] ?? []);
  6750.             $data["dependencies"] = array_values(array_filter($data["dependencies"] ?? [], fn($d) => $d !== $name));
  6751.             if (count($data["dependencies"]) === $before) {
  6752.                 return "Dependency not found: {$name}\n";
  6753.             }
  6754.             return $save($data) ? "Removed dependency: {$name}\n" : r("Could not save node.json", "Error", 2);
  6755.         }
  6756.  
  6757.         return r("node dep: unknown sub-command '{$sub}'. Use add, remove, list.", "Info", 1);
  6758.     }
  6759.  
  6760.     if (str_starts_with($args[0], "meta")) {
  6761.         $key = _node_argex($args, 1, 1);
  6762.         $value = _node_argex($args, 2);
  6763.         if (empty($key)) {
  6764.             return r("node meta: provide <key> <value>", "Info", 1);
  6765.         }
  6766.         $data = $load();
  6767.         if (empty($data)) {
  6768.             return r("node.json not found. Run: node init", "Info", 1);
  6769.         }
  6770.         $data["meta"][$key] = h("node.meta.value", $value);
  6771.         return $save($data) ? "Meta '{$key}' set to: {$value}\n" : r("Could not save node.json", "Error", 2);
  6772.     }
  6773.  
  6774.     return r("node: unknown command '{$args[0]}'", "Info", node());
  6775. }
  6776. # node end
  6777.  
  6778. # note begin dev
  6779. /**
  6780.  * note() — structured note-taking system stored in PROJECT_PATH/note.json
  6781.  *
  6782.  * note list <?type> List all notes, optionally filtered by type
  6783.  * note types List all available types
  6784.  * note new <?string> Create a new untyped note (STDIN if no string)
  6785.  * note <id> Show note details with children
  6786.  * note <id> <type> <?...args> Promote note to type
  6787.  * note <id> of <parent> Set parent relationship
  6788.  * note <id> free <parent> Break parent relationship
  6789.  * note <id> set <key> <value> Set arbitrary key on note
  6790.  * note <id> delete Delete note and clean up references
  6791.  * note <id> done Mark todo as done (timestamp)
  6792.  * note <id> send Send mail note to contact parents
  6793.  * note <id> <action> Call type-specific action
  6794.  */
  6795. function note(mixed ...$args): mixed
  6796. {
  6797.     $args = array_values(array_filter($args, fn($a) => $a !== null && $a !== ""));
  6798.  
  6799.     $file = h("note.file", _node_project("path") . "note.json");
  6800.     $loadAll = function () use ($file): array {
  6801.         if (!file_exists($file)) {
  6802.             return [];
  6803.         }
  6804.         $raw = @file_get_contents($file);
  6805.         if (!$raw || trim($raw) === "") {
  6806.             return [];
  6807.         }
  6808.         $d = json_decode($raw, true);
  6809.         return is_array($d) ? $d : [];
  6810.     };
  6811.     $saveAll = function (array $data) use ($file): bool {
  6812.         $dir = dirname($file);
  6813.         if (!is_dir($dir)) {
  6814.             mkdir($dir, 0777, true);
  6815.         }
  6816.         return (bool) file_put_contents($file, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
  6817.     };
  6818.  
  6819.     // ── Constants ─────────────────────────────────────────────────────────────
  6820.     $TYPES = h("note.types", ["todo", "location", "event", "contact", "mail", "collection", "prompt", "comment"]);
  6821.  
  6822.     // ── Helpers ───────────────────────────────────────────────────────────────
  6823.  
  6824.     $genId = function () use ($loadAll): string {
  6825.         $notes = $loadAll();
  6826.         $chars = "abcdefghijklmnopqrstuvwxyz0123456789"; // ABCDEFGHIJKLMNOPQRSTUVWXYZ
  6827.         $digits = "0123456789";
  6828.         do {
  6829.             $id = "";
  6830.             for ($i = 0; $i < 4; $i++) {
  6831.                 $id .= $chars[random_int(0, strlen($chars) - 1)];
  6832.             }
  6833.             // Must contain at least one digit
  6834.             if (!preg_match("/[0-9]/", $id)) {
  6835.                 $id[random_int(0, 3)] = $digits[random_int(0, 9)];
  6836.             }
  6837.         } while (isset($notes[$id]));
  6838.         return $id;
  6839.     };
  6840.  
  6841.     $castValue = function (string $v): mixed {
  6842.         if (strtolower($v) === "true") {
  6843.             return true;
  6844.         }
  6845.         if (strtolower($v) === "false") {
  6846.             return false;
  6847.         }
  6848.         if (strtolower($v) === "null") {
  6849.             return null;
  6850.         }
  6851.         if ($v === (string) (int) $v) {
  6852.             return (int) $v;
  6853.         }
  6854.         if (is_numeric($v)) {
  6855.             return (float) $v;
  6856.         }
  6857.         return $v;
  6858.     };
  6859.  
  6860.     $logTypeSwitch = function (array &$note, string $newType): void {
  6861.         $note["type_history"][] = [
  6862.             "from" => $note["type"] ?? null,
  6863.             "to" => $newType,
  6864.             "timestamp" => time(),
  6865.         ];
  6866.     };
  6867.  
  6868.     $printNote = function (string $id, array $note, array $all, int $depth = 0) use (&$printNote): string {
  6869.         $pad = str_repeat("  ", $depth);
  6870.         $type = $note["type"] ?? "note";
  6871.         $body = $note["body"] ?? "";
  6872.         $out = "{$pad}#{$id} <{$type}> {$body}\n";
  6873.  
  6874.         // Key-value details
  6875.         $skip = ["body", "type", "type_history", "parents", "children"];
  6876.         foreach ($note as $k => $v) {
  6877.             if (in_array($k, $skip)) {
  6878.                 continue;
  6879.             }
  6880.             if ($k === "created_at") {
  6881.                 $out .= "{$pad}@ " . date("Y-m-d H:i:s", $v) . "\n";
  6882.             } elseif (is_array($v)) {
  6883.                 $out .= "{$pad}> {$k}: " . json_encode($v) . "\n";
  6884.             } elseif (is_string($v) && isset($all[$v])) {
  6885.                 // Value is a known note id — print inline summary
  6886.                 $foreign = $all[$v];
  6887.                 $foreignType = $foreign["type"] ?? "note";
  6888.                 $foreignBody = $foreign["body"] ?? "";
  6889.                 $out .= "{$pad}> {$k}: id ({$v}) <{$foreignType}> {$foreignBody}\n";
  6890.             } else {
  6891.                 $out .= "{$pad}> {$k}: " . (is_bool($v) ? ($v ? "true" : "false") : (string) $v) . "\n";
  6892.             }
  6893.         }
  6894.  
  6895.         // Parents
  6896.         if (!empty($note["parents"])) {
  6897.             $out .= "{$pad}> parents: " . implode(", ", array_map(fn($p) => "#{$p}", $note["parents"])) . "\n";
  6898.         }
  6899.  
  6900.         // Children (recursive, one level shown inline)
  6901.         if (!empty($note["children"])) {
  6902.             $out .= "{$pad}> children:\n";
  6903.             foreach ($note["children"] as $cid) {
  6904.                 if (isset($all[$cid])) {
  6905.                     $out .= $printNote($cid, $all[$cid], $all, $depth + 2);
  6906.                 }
  6907.             }
  6908.         }
  6909.  
  6910.         return trim($out);
  6911.     };
  6912.  
  6913.     // ── note (no args) ────────────────────────────────────────────────────────
  6914.     if (empty($args)) {
  6915.         return implode(
  6916.             "\n",
  6917.             h("note.help", [
  6918.                 "note list <?type> List notes, optionally filtered by type.",
  6919.                 "note types List all available note types.",
  6920.                 "note new <?string> Create untyped note (STDIN if no string).",
  6921.                 "note <id> Show note with all details and children.",
  6922.                 "note <id> <type> <?args> Promote note to a type.",
  6923.                 "note <id> of <parent> Set parent relationship.",
  6924.                 "note <id> free <parent> Break parent relationship.",
  6925.                 "note <id> set <key> <value> Set arbitrary key on note.",
  6926.                 "note <id> delete Delete note and clean up references.",
  6927.                 "note <id> done Mark todo note as done (timestamp).",
  6928.                 "note <id> send Send mail note to contact parents.",
  6929.             ]),
  6930.         );
  6931.     }
  6932.  
  6933.     // ── note types ────────────────────────────────────────────────────────────
  6934.     if ($args[0] === "types") {
  6935.         $desc = [
  6936.             "todo" => "Trackable task. Action: done",
  6937.             "location" => "Geographic point. Requires: <lat> <lon>",
  6938.             "event" => "Occurred event. Requires: <location id> <?timestamp>",
  6939.             "contact" => "Person record. Requires: <name> <email>",
  6940.             "mail" => "Email body. Requires: <subject>. Action: send (to parents of type 'contact')",
  6941.             "collection" => "Groups other notes. Use 'of' to add members.",
  6942.             "prompt" => "Saved prompt. Requires: <subject>",
  6943.             "comment" => "Code comment. Requires: <structure> <name> (<?type> defaults to Class)",
  6944.         ];
  6945.         $out = "Available note types:\n";
  6946.         foreach ($TYPES as $t) {
  6947.             $out .= "$t - " . ($desc[$t] ?? "") . "\n";
  6948.         }
  6949.         return $out;
  6950.     }
  6951.  
  6952.     // ── note list <?type> ────────────────────────────────────────────────────
  6953.     if (str_starts_with($args[0], "list")) {
  6954.         $filter = _node_argex($args, 1);
  6955.         $notes = $loadAll();
  6956.  
  6957.         if (empty($notes)) {
  6958.             return "No notes found in " . _node_project("name") . ".\n";
  6959.         }
  6960.  
  6961.         if ($filter && !in_array($filter, $TYPES) && $filter !== "note") {
  6962.             return r("note list: unknown type '{$filter}'. Run: note types", "Info", 1);
  6963.         }
  6964.  
  6965.         $out = "";
  6966.         foreach ($notes as $id => $n) {
  6967.             $type = $n["type"] ?? "note";
  6968.             if ($filter && $type !== $filter) {
  6969.                 continue;
  6970.             }
  6971.             $body = $n["body"] ?? "";
  6972.             $out .= "#{$id} <{$type}> {$body}\n";
  6973.         }
  6974.  
  6975.         return $out ?: "No notes of type '{$filter}'.\n";
  6976.     }
  6977.  
  6978.     // ── note new <?string> ───────────────────────────────────────────────────
  6979.     if (str_starts_with($args[0], "new")) {
  6980.         $body = _node_argex($args, 1) ?? null;
  6981.  
  6982.         if ($body === null || trim($body) === "") {
  6983.             echo "Enter note body (Ctrl+D to finish):\n";
  6984.             $body = "";
  6985.             while (($line = fgets(STDIN)) !== false) {
  6986.                 $body .= $line;
  6987.             }
  6988.             $body = trim($body);
  6989.         }
  6990.  
  6991.         $notes = $loadAll();
  6992.         $id = $genId();
  6993.  
  6994.         $notes[$id] = h("note.new", [
  6995.             "body" => $body,
  6996.             "type" => null,
  6997.             "created_at" => time(),
  6998.             "parents" => [],
  6999.             "children" => [],
  7000.             "type_history" => [],
  7001.         ]);
  7002.  
  7003.         if (!$saveAll($notes)) {
  7004.             return r("note new: could not write note.json", "Error", 2);
  7005.         }
  7006.  
  7007.         _node_gitignore($file, "write");
  7008.  
  7009.         return "#{$id}\n";
  7010.     }
  7011.  
  7012.     // ── All remaining commands require <id> as first arg ─────────────────────
  7013.     $id = _node_argex($args, 0, 1);
  7014.     $notes = $loadAll();
  7015.  
  7016.     if (!isset($notes[$id])) {
  7017.         return r("note: id '{$id}' not found.", "Info", 1);
  7018.     }
  7019.  
  7020.     $note = &$notes[$id];
  7021.  
  7022.     // ── note <id> (show) ─────────────────────────────────────────────────────
  7023.     if (count($args) === 1 && strpos(trim($args[0]), " ") === false) {
  7024.         return $printNote($id, $note, $notes);
  7025.     }
  7026.  
  7027.     $action = _node_argex($args, 1, 1);
  7028.  
  7029.     // ── note <id> delete ─────────────────────────────────────────────────────
  7030.     if ($action === "delete") {
  7031.         // Remove from parents' children lists
  7032.         foreach ($note["parents"] ?? [] as $pid) {
  7033.             if (isset($notes[$pid]["children"])) {
  7034.                 $notes[$pid]["children"] = array_values(array_filter($notes[$pid]["children"], fn($c) => $c !== $id));
  7035.             }
  7036.         }
  7037.         // Remove from children's parents lists
  7038.         foreach ($note["children"] ?? [] as $cid) {
  7039.             if (isset($notes[$cid]["parents"])) {
  7040.                 $notes[$cid]["parents"] = array_values(array_filter($notes[$cid]["parents"], fn($p) => $p !== $id));
  7041.             }
  7042.         }
  7043.         unset($notes[$id]);
  7044.         return $saveAll($notes) ? "#{$id} deleted.\n" : r("note delete: write failed.", "Error", 2);
  7045.     }
  7046.  
  7047.     // ── note <id> of <parent> ────────────────────────────────────────────────
  7048.     if ($action === "of") {
  7049.         $parentId = _node_argex($args, 2, 1) ?? null;
  7050.         if (!$parentId) {
  7051.             return r("note of: provide a parent id.", "Info", 1);
  7052.         }
  7053.         if (!isset($notes[$parentId])) {
  7054.             return r("note of: parent id '{$parentId}' not found.", "Info", 1);
  7055.         }
  7056.         if (in_array($parentId, $note["parents"] ?? [])) {
  7057.             return "#{$id} already has #{$parentId} as parent.\n";
  7058.         }
  7059.  
  7060.         $note["parents"][] = $parentId;
  7061.         $notes[$parentId]["children"][] = $id;
  7062.  
  7063.         return $saveAll($notes) ? "#{$id} is now a child of #{$parentId}.\n" : r("note of: write failed.", "Error", 2);
  7064.     }
  7065.  
  7066.     // ── note <id> free <parent> ──────────────────────────────────────────────────
  7067.     if ($action === "free") {
  7068.         $parentId = _node_argex($args, 2, 1) ?? null;
  7069.         if (!$parentId) {
  7070.             return r("note free: provide a parent id.", "Info", 1);
  7071.         }
  7072.         if (!isset($notes[$parentId])) {
  7073.             return r("note free: parent id '{$parentId}' not found.", "Info", 1);
  7074.         }
  7075.         if (!in_array($parentId, $note["parents"] ?? [])) {
  7076.             return "#{$id} has no relation to #{$parentId}.\n";
  7077.         }
  7078.  
  7079.         $note["parents"] = array_values(array_filter($note["parents"], fn($p) => $p !== $parentId));
  7080.         $notes[$parentId]["children"] = array_values(array_filter($notes[$parentId]["children"] ?? [], fn($c) => $c !== $id));
  7081.  
  7082.         return $saveAll($notes) ? "#{$id} and #{$parentId} are no longer related.\n" : r("note free: write failed.", "Error", 2);
  7083.     }
  7084.  
  7085.     // ── note <id> set <key> <value> ──────────────────────────────────────────
  7086.     if ($action === "set") {
  7087.         $key = _node_argex($args, 2, 1) ?? null;
  7088.         $val = _node_argex($args, 3) ?? null;
  7089.         if (!$key || $val === null) {
  7090.             return r("note set: provide <key> <value>.", "Info", 1);
  7091.         }
  7092.         // Refuse to overwrite structural array keys silently
  7093.         if (in_array($key, ["parents", "children", "type_history"]) && isset($note[$key]) && is_array($note[$key])) {
  7094.             return r("note set: '{$key}' is a structural array — use dedicated commands.", "Info", 1);
  7095.         }
  7096.         $note[$key] = $castValue($val);
  7097.         return $saveAll($notes) ? "#{$id}.{$key} = " . json_encode($note[$key]) . "\n" : r("note set: write failed.", "Error", 2);
  7098.     }
  7099.  
  7100.     // ── note <id> done ───────────────────────────────────────────────────────
  7101.     if ($action === "done") {
  7102.         if (($note["type"] ?? null) !== "todo") {
  7103.             return r("note done: #{$id} is not a todo.", "Info", 1);
  7104.         }
  7105.         $note["done"] = time();
  7106.         return $saveAll($notes) ? "#{$id} marked done at " . date("Y-m-d H:i:s", $note["done"]) . "\n" : r("note done: write failed.", "Error", 2);
  7107.     }
  7108.  
  7109.     // ── note <id> send ───────────────────────────────────────────────────────
  7110.     if ($action === "send") {
  7111.         if (($note["type"] ?? null) !== "mail") {
  7112.             return r("note send: #{$id} is not a mail note.", "Info", 1);
  7113.         }
  7114.  
  7115.         $subject = $note["subject"] ?? "(no subject)";
  7116.         $body = $note["body"] ?? "";
  7117.  
  7118.         // Load mail config from node.json
  7119.         $nodeJson = _node_migrate_load(_node_project("path") . "node.json");
  7120.         $mailCfg = $nodeJson["mail"] ?? [];
  7121.  
  7122.         foreach (["host", "port", "username", "password", "from"] as $required) {
  7123.             if (empty($mailCfg[$required])) {
  7124.                 return r("note send: missing node.json mail.{$required} config.", "Info", 1);
  7125.             }
  7126.         }
  7127.  
  7128.         // Find all parent notes of type contact
  7129.         $contacts = [];
  7130.         foreach ($note["parents"] ?? [] as $pid) {
  7131.             if (isset($notes[$pid]) && ($notes[$pid]["type"] ?? null) === "contact") {
  7132.                 $contacts[$pid] = $notes[$pid];
  7133.             }
  7134.         }
  7135.  
  7136.         if (empty($contacts)) {
  7137.             return "note send: no parent contact notes found for #{$id}.\n";
  7138.         }
  7139.  
  7140.         $alreadySent = $note["sent_to"] ?? [];
  7141.         $sent = [];
  7142.         $skipped = [];
  7143.  
  7144.         foreach ($contacts as $cid => $contact) {
  7145.             if (in_array($cid, $alreadySent)) {
  7146.                 $skipped[] = $cid;
  7147.                 continue;
  7148.             }
  7149.  
  7150.             $toEmail = $contact["email"] ?? null;
  7151.             $toName = $contact["name"] ?? $cid;
  7152.  
  7153.             if (!$toEmail) {
  7154.                 $skipped[] = $cid;
  7155.                 continue;
  7156.             }
  7157.  
  7158.             $result = _node_note_smtp_send($mailCfg, $toEmail, $toName, $subject, $body);
  7159.  
  7160.             if ($result === true) {
  7161.                 $sent[] = $cid;
  7162.                 $alreadySent[] = $cid;
  7163.             } else {
  7164.                 return r("note send: SMTP error for #{$cid}: {$result}", "Error", 2);
  7165.             }
  7166.         }
  7167.  
  7168.         $note["sent_to"] = $alreadySent;
  7169.  
  7170.         if (!$saveAll($notes)) {
  7171.             return r("note send: could not write note.json after sending.", "Error", 2);
  7172.         }
  7173.  
  7174.         $out = "Mail '#{$id}' send results:\n";
  7175.         foreach ($sent as $cid) {
  7176.             $out .= "  [sent]    #{$cid} {$contacts[$cid]["email"]}\n";
  7177.         }
  7178.         foreach ($skipped as $cid) {
  7179.             $out .= "  [skipped] #{$cid} (already sent or no email)\n";
  7180.         }
  7181.         return $out;
  7182.     }
  7183.  
  7184.     // ── note <id> <type> <?args> — type promotion ────────────────────────────
  7185.     if (in_array($action, $TYPES)) {
  7186.         $type = $action;
  7187.         $typeArgs = [_node_argex($args, 2)]; // edible as $args[0] for sub _argex
  7188.  
  7189.         $logTypeSwitch($note, $type);
  7190.         $note["type"] = $type;
  7191.  
  7192.         switch ($type) {
  7193.             case "todo":
  7194.                 // No extra args required — just the promotion
  7195.                 break;
  7196.  
  7197.             case "location":
  7198.                 $lat = _node_argex($typeArgs, 0, 1) ?? null;
  7199.                 $lon = _node_argex($typeArgs, 1, 1) ?? null;
  7200.                 if ($lat === null || $lon === null) {
  7201.                     return r("note location: provide <lat> <lon>.", "Info", 1);
  7202.                 }
  7203.                 $note["lat"] = (float) $lat;
  7204.                 $note["lon"] = (float) $lon;
  7205.                 break;
  7206.  
  7207.             case "event":
  7208.                 $locId = _node_argex($typeArgs, 0, 1) ?? null;
  7209.                 $timestamp = _node_argex($typeArgs, 1, 1) ?? null;
  7210.                 $timestamp = $timestamp ? strtotime($timestamp) : time();
  7211.  
  7212.                 if (!$locId) {
  7213.                     return r("note event: provide <location_id>.", "Info", 1);
  7214.                 }
  7215.                 if (!isset($notes[$locId]) || ($notes[$locId]["type"] ?? null) !== "location") {
  7216.                     return r("note event: '{$locId}' is not a location note.", "Info", 1);
  7217.                 }
  7218.                 $note["location_id"] = $locId;
  7219.                 $note["occurred_at"] = (int) $timestamp;
  7220.                 break;
  7221.  
  7222.             case "contact":
  7223.                 $name = _node_argex($typeArgs, 0, 1) ?? null;
  7224.                 $email = _node_argex($typeArgs, 1, 1) ?? null;
  7225.                 if (!$name || !$email) {
  7226.                     return r("note contact: provide <name> <email>.", "Info", 1);
  7227.                 }
  7228.                 $note["name"] = $name;
  7229.                 $note["email"] = $email;
  7230.                 break;
  7231.  
  7232.             case "mail":
  7233.                 $subject = _node_argex($typeArgs, 0) ?? null;
  7234.                 if (!$subject) {
  7235.                     return r("note mail: provide <subject>.", "Info", 1);
  7236.                 }
  7237.                 $note["subject"] = $subject;
  7238.                 $note["sent_to"] ??= [];
  7239.                 break;
  7240.  
  7241.             case "collection":
  7242.                 // No extra args — members added via 'of'
  7243.                 break;
  7244.  
  7245.             case "prompt":
  7246.                 $subject = _node_argex($typeArgs, 0) ?? null;
  7247.                 if (!$subject) {
  7248.                     return r("note prompt: provide <subject>.", "Info", 1);
  7249.                 }
  7250.                 $note["subject"] = $subject;
  7251.                 break;
  7252.  
  7253.             case "comment":
  7254.                 $structure = _node_argex($typeArgs, 0, 1) ?? null;
  7255.                 $name = _node_argex($typeArgs, 1, 1) ?? null;
  7256.                 $struct_type = _node_argex($typeArgs, 2, 1) ?? "Class";
  7257.                 if (!$structure || !$name) {
  7258.                     return r("note comment: provide <structure> <name> <?type>.", "Info", 1);
  7259.                 }
  7260.                 $note["structure"] = $structure;
  7261.                 $note["name"] = $name;
  7262.                 $note["struct_type"] = $struct_type;
  7263.                 break;
  7264.         }
  7265.  
  7266.         return $saveAll($notes) ? "#{$id} promoted to <{$type}>.\n" : r("note: write failed.", "Error", 2);
  7267.     }
  7268.  
  7269.     // ── Fallthrough — unknown action ──────────────────────────────────────────
  7270.     return r("note: unknown action '{$action}' for #{$id}. Run: note", "Info", 1);
  7271. }
  7272.  
  7273. /**
  7274.  * Send a single email via SMTP using PHP's native socket functions.
  7275.  * Config keys expected in $cfg: host, port, username, password, from, from_name (optional).
  7276.  * Returns true on success or an error string on failure.
  7277.  */
  7278. function _node_note_smtp_send(array $cfg, string $toEmail, string $toName, string $subject, string $body): true|string
  7279. {
  7280.     $host = $cfg["host"];
  7281.     $port = (int) ($cfg["port"] ?? 587);
  7282.     $user = $cfg["username"];
  7283.     $pass = $cfg["password"];
  7284.     $from = $cfg["from"];
  7285.     $fromName = $cfg["from_name"] ?? $from;
  7286.     $timeout = (int) ($cfg["timeout"] ?? 15);
  7287.  
  7288.     $send = function ($socket, string $cmd) use ($timeout): string {
  7289.         fwrite($socket, "$cmd\r\n");
  7290.         $response = "";
  7291.         stream_set_timeout($socket, $timeout);
  7292.         while ($line = fgets($socket, 512)) {
  7293.             $response .= $line;
  7294.             // SMTP multi-line: lines continue while 4th char is '-'
  7295.             if (isset($line[3]) && $line[3] !== "-") {
  7296.                 break;
  7297.             }
  7298.         }
  7299.         return $response;
  7300.     };
  7301.  
  7302.     $expect = fn(string $response, string $code): bool => str_starts_with(trim($response), $code);
  7303.  
  7304.     // Open socket
  7305.     $errno = 0;
  7306.     $errstr = "";
  7307.     $prefix = $port === 465 ? "ssl://" : "";
  7308.     $socket = @fsockopen("{$prefix}{$host}", $port, $errno, $errstr, $timeout);
  7309.  
  7310.     if (!$socket) {
  7311.         return "Could not connect to {$host}:{$port} — {$errstr} ({$errno})";
  7312.     }
  7313.  
  7314.     // Read greeting
  7315.     $resp = fread($socket, 512);
  7316.     if (!$expect($resp, "220")) {
  7317.         fclose($socket);
  7318.         return "SMTP greeting failed: {$resp}";
  7319.     }
  7320.  
  7321.     // EHLO
  7322.     $resp = $send($socket, "EHLO " . gethostname());
  7323.  
  7324.     // STARTTLS for port 587
  7325.     if ($port === 587) {
  7326.         $resp = $send($socket, "STARTTLS");
  7327.         if (!$expect($resp, "220")) {
  7328.             fclose($socket);
  7329.             return "STARTTLS failed: {$resp}";
  7330.         }
  7331.         stream_socket_enable_crypto($socket, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
  7332.         $resp = $send($socket, "EHLO " . gethostname());
  7333.     }
  7334.  
  7335.     // AUTH LOGIN
  7336.     $resp = $send($socket, "AUTH LOGIN");
  7337.     if (!$expect($resp, "334")) {
  7338.         fclose($socket);
  7339.         return "AUTH LOGIN failed: {$resp}";
  7340.     }
  7341.     $resp = $send($socket, base64_encode($user));
  7342.     if (!$expect($resp, "334")) {
  7343.         fclose($socket);
  7344.         return "AUTH username failed: {$resp}";
  7345.     }
  7346.     $resp = $send($socket, base64_encode($pass));
  7347.     if (!$expect($resp, "235")) {
  7348.         fclose($socket);
  7349.         return "AUTH password failed: {$resp}";
  7350.     }
  7351.  
  7352.     // Envelope
  7353.     $resp = $send($socket, "MAIL FROM:<{$from}>");
  7354.     if (!$expect($resp, "250")) {
  7355.         fclose($socket);
  7356.         return "MAIL FROM failed: {$resp}";
  7357.     }
  7358.     $resp = $send($socket, "RCPT TO:<{$toEmail}>");
  7359.     if (!$expect($resp, "250")) {
  7360.         fclose($socket);
  7361.         return "RCPT TO failed: {$resp}";
  7362.     }
  7363.  
  7364.     // Data
  7365.     $resp = $send($socket, "DATA");
  7366.     if (!$expect($resp, "354")) {
  7367.         fclose($socket);
  7368.         return "DATA command failed: {$resp}";
  7369.     }
  7370.  
  7371.     $date = date("r");
  7372.     $encoded = base64_encode($body);
  7373.     $headers = implode("\r\n", [
  7374.         "Date: {$date}",
  7375.         "From: {$fromName} <{$from}>",
  7376.         "To: {$toName} <{$toEmail}>",
  7377.         "Subject: {$subject}",
  7378.         "MIME-Version: 1.0",
  7379.         "Content-Type: text/plain; charset=UTF-8",
  7380.         "Content-Transfer-Encoding: base64",
  7381.     ]);
  7382.  
  7383.     $resp = $send($socket, "$headers\r\n\r\n$encoded\r\n.");
  7384.     if (!$expect($resp, "250")) {
  7385.         fclose($socket);
  7386.         return "Message send failed: {$resp}";
  7387.     }
  7388.  
  7389.     $send($socket, "QUIT");
  7390.     fclose($socket);
  7391.  
  7392.     return true;
  7393. }
  7394. # note end
  7395.  
  7396. # ctx begin dev
  7397. function ctx(mixed ...$args): string
  7398. {
  7399.     $args = array_filter($args);
  7400.  
  7401.     if (empty($args)) {
  7402.         return implode(
  7403.             "\n",
  7404.             h("ctx.help", [
  7405.                 "ctx <class|function> Show target source with all dependencies resolved.",
  7406.                 "ctx <class|function> :deps Show only the dependency tree, no source.",
  7407.                 "ctx <class|function> :file Show only the file path where target lives.",
  7408.             ]),
  7409.         );
  7410.     }
  7411.  
  7412.     $target = $args[0];
  7413.     $modifier = $args[1] ?? null;
  7414.  
  7415.     // ── Search surface ────────────────────────────────────────────────────────
  7416.     // Use gitignore tracked file list — same surface as struct("search"),
  7417.     // dump(), and w() — respects project boundaries and excludes Deleted/,
  7418.     // Backup/, Deprecated/ etc automatically.
  7419.     $trackedFiles = h(
  7420.         "ctx.files",
  7421.         array_filter(array_map(fn($rel) => ROOT_PATH . $rel, _node_gitignore(":list:all")), fn($f) => file_exists($f) && !is_dir($f) && str_ends_with($f, ".php")),
  7422.     );
  7423.  
  7424.     if (empty($trackedFiles)) {
  7425.         return r("ctx: no tracked PHP files found in project <" . _node_project("name") . ">", "Info", "No files tracked yet.\n");
  7426.     }
  7427.  
  7428.     // ── Locate target ─────────────────────────────────────────────────────────
  7429.     $targetData = _node_ctx_find_target($target, $trackedFiles);
  7430.  
  7431.     if (!$targetData) {
  7432.         // Before giving up, check dependency projects
  7433.         $nodeJson = _node_migrate_load(_node_project("path") . "node.json");
  7434.         foreach (h("ctx.dep.search", $nodeJson["dependencies"] ?? []) as $dep) {
  7435.             $depPath = ROOT_PATH . $dep . D;
  7436.             $depTracked = array_filter(
  7437.                 array_map(fn($rel) => ROOT_PATH . $rel, _node_migrate_load("$depPath.gitignore") ? _node_gitignore(":list:all") : []),
  7438.                 fn($f) => file_exists($f) && str_ends_with($f, ".php"),
  7439.             );
  7440.             if ($found = _node_ctx_find_target($target, $depTracked)) {
  7441.                 $targetData = $found;
  7442.                 break;
  7443.             }
  7444.         }
  7445.     }
  7446.  
  7447.     if (!$targetData) {
  7448.         return r("ctx: '{$target}' not found in tracked files.", "Info", "Not found.\n");
  7449.     }
  7450.  
  7451.     // ── :file shortcut ────────────────────────────────────────────────────────
  7452.     if ($modifier === ":file") {
  7453.         return str_replace(ROOT_PATH, "", $targetData["file"]) . "\n";
  7454.     }
  7455.  
  7456.     // ── Determine struct path label for the file ──────────────────────────────
  7457.     $relFile = str_replace(ROOT_PATH, "", $targetData["file"]);
  7458.     $structKey = _node_ctx_resolve_struct_key($targetData["file"]);
  7459.  
  7460.     // ── Build dependency tree ─────────────────────────────────────────────────
  7461.     $deps = _node_ctx_extract_deps($targetData["content"]);
  7462.     $relatedCode = [];
  7463.  
  7464.     foreach ($deps as $depName => $depType) {
  7465.         $depData = match ($depType) {
  7466.             "class" => _node_ctx_find_target($depName, $trackedFiles),
  7467.             "function" => _node_ctx_find_target($depName, $trackedFiles),
  7468.             default => null,
  7469.         };
  7470.  
  7471.         if ($depData && $depData["file"] !== $targetData["file"]) {
  7472.             $relatedCode[$depName] = [
  7473.                 "file" => str_replace(ROOT_PATH, "", $depData["file"]),
  7474.                 "struct" => _node_ctx_resolve_struct_key($depData["file"]),
  7475.                 "content" => $depData["content"],
  7476.                 "type" => $depType,
  7477.             ];
  7478.         }
  7479.     }
  7480.  
  7481.     // ── :deps shortcut ────────────────────────────────────────────────────────
  7482.     if ($modifier === ":deps") {
  7483.         if (empty($relatedCode)) {
  7484.             return "ctx: '{$target}' has no external dependencies in tracked files.\n";
  7485.         }
  7486.         $out = "Dependencies of {$target}:\n";
  7487.         foreach ($relatedCode as $name => $data) {
  7488.             $out .= sprintf("  %-30s %-10s %s\n", $name, "({$data["type"]})", $data["file"]);
  7489.         }
  7490.         return $out;
  7491.     }
  7492.  
  7493.     // ── Full output ───────────────────────────────────────────────────────────
  7494.     $out = "";
  7495.  
  7496.     // Header — file + struct location
  7497.     if ($structKey) {
  7498.         $out .= "Structure location: {$structKey}\n\n";
  7499.     }
  7500.     $out .= "## {$relFile}\n";
  7501.  
  7502.     // Target source
  7503.     $out .= "```\n" . h("ctx.target.content", $targetData["content"]) . "\n```\n\n";
  7504.  
  7505.     // Related code
  7506.     if (!empty($relatedCode)) {
  7507.         $out .= "# related code for context:\n\n";
  7508.         foreach ($relatedCode as $name => $data) {
  7509.             $label = "";
  7510.             if ($data["struct"]) {
  7511.                 $label .= "Structure: {$data["struct"]}\n\n";
  7512.             }
  7513.             $label = "## {$data["file"]}";
  7514.             $out .= "$label\n```\n" . $data["content"] . "\n```\n\n";
  7515.         }
  7516.     }
  7517.  
  7518.     // Documentation — pull from struct doc if it exists
  7519.     $doc = struct(":documentation", $structKey ?? $target);
  7520.     if (is_string($doc) && !str_contains($doc, "not yet documented") && !str_contains($doc, "not found")) {
  7521.         $out .= "# Documentation:\n\n#$doc\n\n";
  7522.     }
  7523.  
  7524.     // Migration history — any blockchain blocks mentioning this target
  7525.     $lookup = migrate("lookup", $target);
  7526.     if (is_string($lookup) && !str_contains($lookup, "No blocks")) {
  7527.         $out .= "# Migration history:\n\n$lookup\n";
  7528.     }
  7529.  
  7530.     return h("ctx.output", trim($out), [$target, $targetData, $relatedCode]);
  7531. }
  7532.  
  7533. // ── Helpers ───────────────────────────────────────────────────────────────────
  7534.  
  7535. /**
  7536.  * Find a class or function by name within a list of absolute file paths.
  7537.  * Returns the extracted source block and file location, or null.
  7538.  */
  7539. function _node_ctx_find_target(string $target, array $files): ?array
  7540. {
  7541.     $isClassTarget = !str_contains($target, "::") && preg_match("/^[A-Z]/", $target);
  7542.     $className = str_contains($target, "::") ? explode("::", $target)[0] : $target;
  7543.  
  7544.     foreach (h("ctx.search.files", $files) as $file) {
  7545.         $content = @file_get_contents($file);
  7546.         if (!$content) {
  7547.             continue;
  7548.         }
  7549.  
  7550.         // Function search
  7551.         if (!$isClassTarget) {
  7552.             $block = _node_ctx_extract_function($content, $target);
  7553.             if ($block) {
  7554.                 return ["type" => "function", "file" => $file, "content" => $block];
  7555.             }
  7556.         }
  7557.  
  7558.         // Class search
  7559.         if (preg_match("/\bclass\s+" . preg_quote($className, "/") . "\b/", $content)) {
  7560.             $block = _node_ctx_extract_class($content, $className);
  7561.             if ($block) {
  7562.                 return ["type" => "class", "file" => $file, "content" => $block];
  7563.             }
  7564.         }
  7565.     }
  7566.  
  7567.     return null;
  7568. }
  7569.  
  7570. /**
  7571.  * Extract a function body including its docblock.
  7572.  * Uses the existing helper if present, otherwise falls back to regex.
  7573.  */
  7574. function _node_ctx_extract_function(string $content, string $name): ?string
  7575. {
  7576.     if (function_exists("_node_get_function_body_with_docblock")) {
  7577.         return _node_get_function_body_with_docblock($content, $name) ?: null;
  7578.     }
  7579.  
  7580.     // Fallback regex — captures docblock + signature + balanced braces
  7581.     $pattern = "/(\/\*\*.*?\*\/\s*)?function\s+" . preg_quote($name, "/") . "\s*\([^)]*\)[^{]*\{/s";
  7582.     if (!preg_match($pattern, $content, $m, PREG_OFFSET_CAPTURE)) {
  7583.         return null;
  7584.     }
  7585.  
  7586.     $start = $m[0][1];
  7587.     $depth = 0;
  7588.     $len = strlen($content);
  7589.     $opened = false;
  7590.  
  7591.     for ($i = $start; $i < $len; $i++) {
  7592.         if ($content[$i] === "{") {
  7593.             $depth++;
  7594.             $opened = true;
  7595.         }
  7596.         if ($content[$i] === "}") {
  7597.             $depth--;
  7598.         }
  7599.         if ($opened && $depth === 0) {
  7600.             return substr($content, $start, $i - $start + 1);
  7601.         }
  7602.     }
  7603.  
  7604.     return null;
  7605. }
  7606.  
  7607. /**
  7608.  * Extract a class body including its docblock using balanced-brace walking.
  7609.  */
  7610. function _node_ctx_extract_class(string $content, string $className): ?string
  7611. {
  7612.     $pattern = "/(\/\*\*.*?\*\/\s*)?(?:abstract\s+|final\s+)?class\s+" . preg_quote($className, "/") . "\b[^{]*/s";
  7613.     if (!preg_match($pattern, $content, $m, PREG_OFFSET_CAPTURE)) {
  7614.         return null;
  7615.     }
  7616.  
  7617.     $start = $m[0][1];
  7618.     $depth = 0;
  7619.     $len = strlen($content);
  7620.     $opened = false;
  7621.  
  7622.     for ($i = $start; $i < $len; $i++) {
  7623.         if ($content[$i] === "{") {
  7624.             $depth++;
  7625.             $opened = true;
  7626.         }
  7627.         if ($content[$i] === "}") {
  7628.             $depth--;
  7629.         }
  7630.         if ($opened && $depth === 0) {
  7631.             return substr($content, $start, $i - $start + 1);
  7632.         }
  7633.     }
  7634.  
  7635.     return null;
  7636. }
  7637.  
  7638. /**
  7639.  * Tokenize source content and extract all external class and function
  7640.  * references — returns ["Name" => "class"|"function"].
  7641.  * Skips PHP built-ins and NodePHP internals.
  7642.  */
  7643. function _node_ctx_extract_deps(string $content): array
  7644. {
  7645.     static $skip;
  7646.     $skip ??= h("ctx.skip.tokens", [
  7647.         ...[
  7648.             "echo",
  7649.             "print",
  7650.             "if",
  7651.             "else",
  7652.             "elseif",
  7653.             "for",
  7654.             "foreach",
  7655.             "while",
  7656.             "do",
  7657.             "switch",
  7658.             "case",
  7659.             "default",
  7660.             "break",
  7661.             "continue",
  7662.             "return",
  7663.             "function",
  7664.             "class",
  7665.             "interface",
  7666.             "trait",
  7667.             "enum",
  7668.             "namespace",
  7669.             "use",
  7670.             "extends",
  7671.             "implements",
  7672.             "new",
  7673.             "instanceof",
  7674.             "clone",
  7675.             "true",
  7676.             "false",
  7677.             "null",
  7678.             "self",
  7679.             "parent",
  7680.             "static",
  7681.             "array",
  7682.             "string",
  7683.             "int",
  7684.             "float",
  7685.             "bool",
  7686.             "void",
  7687.             "mixed",
  7688.             "iterable",
  7689.             "callable",
  7690.             "object",
  7691.             "public",
  7692.             "private",
  7693.             "protected",
  7694.             "abstract",
  7695.             "final",
  7696.             "const",
  7697.             "isset",
  7698.             "empty",
  7699.             "eval",
  7700.             "exit",
  7701.             "die",
  7702.             "list",
  7703.             "unset",
  7704.             "include",
  7705.             "include_once",
  7706.             "require",
  7707.             "require_once",
  7708.             "match",
  7709.             "throw",
  7710.             "try",
  7711.             "catch",
  7712.             "finally",
  7713.             "yield",
  7714.             "fn",
  7715.             "never",
  7716.             "readonly",
  7717.         ],
  7718.         // NodePHP framework internals — don't recurse into these
  7719.         ...["h", "r", "p", "f", "w", "dump", "struct", "git", "node", "migrate", "ctx", "import", "feed", "wrap", "lint", "_node_project", "_node_argex", "_node_spath", "_node_spex"],
  7720.     ]);
  7721.  
  7722.     $deps = [];
  7723.     $tokens = token_get_all("<?php\n{$content}");
  7724.     $count = count($tokens);
  7725.  
  7726.     for ($i = 0; $i < $count; $i++) {
  7727.         $tok = $tokens[$i];
  7728.         if (!is_array($tok)) {
  7729.             continue;
  7730.         }
  7731.  
  7732.         // extends ClassName
  7733.         if ($tok[0] === T_EXTENDS) {
  7734.             for ($j = $i + 1; $j < $count; $j++) {
  7735.                 if (!is_array($tokens[$j])) {
  7736.                     break;
  7737.                 }
  7738.                 if ($tokens[$j][0] === T_WHITESPACE) {
  7739.                     continue;
  7740.                 }
  7741.                 if ($tokens[$j][0] === T_STRING) {
  7742.                     $deps[$tokens[$j][1]] = "class";
  7743.                     break;
  7744.                 }
  7745.             }
  7746.         }
  7747.  
  7748.         // new ClassName
  7749.         if ($tok[0] === T_NEW) {
  7750.             for ($j = $i + 1; $j < $count; $j++) {
  7751.                 if (!is_array($tokens[$j])) {
  7752.                     break;
  7753.                 }
  7754.                 if ($tokens[$j][0] === T_WHITESPACE) {
  7755.                     continue;
  7756.                 }
  7757.                 if ($tokens[$j][0] === T_STRING) {
  7758.                     $name = $tokens[$j][1];
  7759.                     if (!in_array(strtolower($name), $skip)) {
  7760.                         $deps[$name] = "class";
  7761.                     }
  7762.                     break;
  7763.                 }
  7764.             }
  7765.         }
  7766.  
  7767.         // SomeString followed by ( = function call
  7768.         if ($tok[0] === T_STRING) {
  7769.             $name = $tok[1];
  7770.             if (in_array(strtolower($name), $skip)) {
  7771.                 continue;
  7772.             }
  7773.             for ($j = $i + 1; $j < $count; $j++) {
  7774.                 if (!is_array($tokens[$j])) {
  7775.                     if ($tokens[$j] === "(") {
  7776.                         if (preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $name)) {
  7777.                             $deps[$name] ??= "function";
  7778.                         }
  7779.                     }
  7780.                     break;
  7781.                 }
  7782.                 if ($tokens[$j][0] === T_WHITESPACE) {
  7783.                     continue;
  7784.                 }
  7785.                 break;
  7786.             }
  7787.         }
  7788.     }
  7789.  
  7790.     return h("ctx.deps", $deps, [$content]);
  7791. }
  7792.  
  7793. /**
  7794.  * Given an absolute file path, return the struct key it lives under
  7795.  * (e.g. "Domain/Logic/Service") or null if not resolvable.
  7796.  */
  7797. function _node_ctx_resolve_struct_key(string $absFile): ?string
  7798. {
  7799.     $projectPath = _node_project("path");
  7800.     if (!str_starts_with($absFile, $projectPath)) {
  7801.         return null;
  7802.     }
  7803.  
  7804.     $rel = substr($absFile, strlen($projectPath)); // e.g. Domain/Logic/Service/OrderService.php
  7805.     $dir = dirname($rel); // e.g. Domain/Logic/Service
  7806.     $allKeys = struct(":keys");
  7807.  
  7808.     return array_key_exists($dir, $allKeys) ? $dir : null;
  7809. }
  7810. # ctx end
  7811.  
  7812. # rank begin dev
  7813. // ═════════════════════════════════════════════════════════════════════════════
  7814. // rank()  —  public entry point (mirrors struct/migrate/ctx pattern)
  7815. // ═════════════════════════════════════════════════════════════════════════════
  7816.  
  7817. function rank(mixed ...$args): mixed
  7818. {
  7819.     $args = array_filter($args);
  7820.  
  7821.     if (empty($args)) {
  7822.         return implode(
  7823.             "\n",
  7824.             h("rank.help", [
  7825.                 "rank <file> Score every function in a file.",
  7826.                 "rank <file> <function> Score one function with improvement notes.",
  7827.                 "rank project Score every tracked file, sorted worst-first.",
  7828.                 "rank struct <structure> Score all files inside a struct path.",
  7829.             ]),
  7830.         );
  7831.     }
  7832.  
  7833.     if ($args[0] === "project") {
  7834.         $files = array_filter(array_map(fn($rel) => ROOT_PATH . $rel, _node_gitignore(":list:all")), fn($f) => file_exists($f) && str_ends_with($f, ".php"));
  7835.  
  7836.         if (empty($files)) {
  7837.             return r("rank: no tracked PHP files found.", "Info", "Nothing to rank.\n");
  7838.         }
  7839.  
  7840.         $rows = [];
  7841.         foreach ($files as $abs) {
  7842.             $src = @file_get_contents($abs) ?: "";
  7843.             $metrics = _node_rank_file_metrics($src);
  7844.             $rows[] = [
  7845.                 "file" => str_replace(ROOT_PATH, "", $abs),
  7846.                 "score" => array_sum($metrics),
  7847.             ];
  7848.         }
  7849.  
  7850.         usort($rows, fn($a, $b) => $a["score"] <=> $b["score"]);
  7851.  
  7852.         $out = "Project rank (" . count($rows) . " files):\n\n";
  7853.         $width = max(array_map(fn($r) => strlen($r["file"]), $rows));
  7854.         foreach ($rows as $row) {
  7855.             $pad = str_repeat(" ", $width - strlen($row["file"]) + 2);
  7856.             $out .= $row["file"] . $pad . number_format($row["score"], 1) . "\n";
  7857.         }
  7858.         return h("rank.project.output", $out, [$rows]);
  7859.     }
  7860.  
  7861.     if ($args[0] === "struct") {
  7862.         $structure = $args[1] ?? null;
  7863.         if (!$structure) {
  7864.             return r("rank struct: provide a structure name.", "Info", 1);
  7865.         }
  7866.         $path = _node_spath($structure);
  7867.         if (!$path) {
  7868.             return r("rank struct: unknown structure '{$structure}'.", "Info", 1);
  7869.         }
  7870.         $dir = _node_project("path") . $path;
  7871.         $files = glob($dir . D . "*.php") ?: [];
  7872.         if (empty($files)) {
  7873.             return "rank struct: no PHP files in {$path}.\n";
  7874.         }
  7875.         // Delegate each file to the file branch below, collect output
  7876.         $out = "Ranking [{$path}] — " . count($files) . " file(s):\n\n";
  7877.         foreach ($files as $abs) {
  7878.             $out .= rank($abs);
  7879.         }
  7880.         return $out;
  7881.     }
  7882.  
  7883.     $absFile = str_starts_with($args[0], ROOT_PATH) ? $args[0] : ROOT_PATH . $args[0];
  7884.     $targetFn = $args[1] ?? null;
  7885.  
  7886.     if (!file_exists($absFile)) {
  7887.         return r("rank: file not found: {$absFile}", "Info", "File not found.\n");
  7888.     }
  7889.  
  7890.     $src = file_get_contents($absFile);
  7891.     $functions = _node_rank_functions($src);
  7892.  
  7893.     if (empty($functions)) {
  7894.         return "rank: no functions found in " . str_replace(ROOT_PATH, "", $absFile) . "\n";
  7895.     }
  7896.  
  7897.     if ($targetFn && !in_array($targetFn, $functions)) {
  7898.         return r("rank: function '{$targetFn}' not found in file.", "Info", 1);
  7899.     }
  7900.  
  7901.     $fileMetrics = _node_rank_file_metrics($src);
  7902.     $fileTotal = array_sum($fileMetrics);
  7903.     $targets = $targetFn ? [$targetFn] : $functions;
  7904.  
  7905.     // Score all targets
  7906.     $analysis = [];
  7907.     foreach ($targets as $fn) {
  7908.         $body = _node_rank_extract($src, $fn);
  7909.         $fScore = _node_rank_function_score($src, $fn, $body);
  7910.         $analysis[$fn] = [
  7911.             "metrics" => $fScore,
  7912.             "raw" => array_sum($fScore),
  7913.             "score" => array_sum($fScore) + $fileTotal,
  7914.         ];
  7915.     }
  7916.  
  7917.     $analysis = h("rank.analysis", $analysis, [$absFile]);
  7918.  
  7919.     if ($targetFn) {
  7920.         return _node_rank_detail($targetFn, $analysis[$targetFn], $fileMetrics, $fileTotal);
  7921.     }
  7922.  
  7923.     return _node_rank_summary($analysis, $fileMetrics, $fileTotal, $absFile);
  7924. }
  7925.  
  7926. // ═════════════════════════════════════════════════════════════════════════════
  7927. // Extraction
  7928. // ═════════════════════════════════════════════════════════════════════════════
  7929.  
  7930. function _node_rank_functions(string $src): array
  7931. {
  7932.     return preg_match_all('/(?:public|protected|private|static|\s)+function\s+([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\s*\(/', $src, $m)
  7933.         ? $m[1]
  7934.         : (preg_match_all('/function\s+([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\s*\(/', $src, $m)
  7935.             ? $m[1]
  7936.             : []);
  7937. }
  7938.  
  7939. /**
  7940.  * Extract function body — delegates to existing helper, falls back to
  7941.  * brace-counting extractor. Both are already ported helpers.
  7942.  */
  7943. function _node_rank_extract(string $src, string $name): string
  7944. {
  7945.     return _node_get_function_body_with_docblock($src, $name) ?: _node_extract_function_with_brace_counting($src, $name);
  7946. }
  7947.  
  7948. // ═════════════════════════════════════════════════════════════════════════════
  7949. // Scoring — file level
  7950. // ═════════════════════════════════════════════════════════════════════════════
  7951.  
  7952. function _node_rank_file_metrics(string $src): array
  7953. {
  7954.     return h("rank.file.metrics", [
  7955.         "strict_types" => str_contains($src, "declare(strict_types=1)") ? 9.0 : -5.0,
  7956.         "namespace" => str_contains($src, "namespace ") ? 0.0 : -3.0,
  7957.         "no_superglobals" => -(preg_match_all('/\$\_(GET|POST|SESSION|COOKIE|SERVER|REQUEST|FILES)\b/', $src) * 3.0),
  7958.         "typed_properties" => _node_rank_typed_properties($src),
  7959.         "final_class" => _node_rank_final_class($src),
  7960.         "modern_visibility" => _node_rank_modern_visibility($src),
  7961.         "constructor_promotion" => preg_match_all('/public\s+function\s+__construct\s*\([^)]*\b(?:public|protected|private)\s+(?:readonly\s+)?[\w|?]+\s+\$\w+/s', $src) * 2.5,
  7962.         "union_types" => preg_match_all("/@(?:param|return)\s+[\w?]+\|/", $src) * 1.2,
  7963.         "nullsafe_operator" => preg_match_all("/\?\->/", $src) * 1.0,
  7964.         "match_expression" => _node_rank_match_vs_switch($src),
  7965.         "named_arguments" => preg_match_all("/\w+\s*\([^)]*?\b\w+\s*:/", $src) * 0.8,
  7966.         "attributes" => preg_match_all("/#\[(?!Deprecated\b)/", $src) * 2.0,
  7967.         "enums" => preg_match_all("/\benum\s+\w+/", $src) * 4.0,
  7968.         "readonly_properties" => preg_match_all('/\b(?:public|protected|private)\s+readonly\s+[\w?|]+\s+\$\w+/', $src) * 3.0,
  7969.         "never_return_type" => preg_match_all("/:\s*never\b/", $src) * 2.5,
  7970.         "array_is_list" => _node_rank_array_is_list($src),
  7971.         "first_class_callable" => preg_match_all("/\w+\s*\(\.\.\.\)/", $src) * 2.0,
  7972.         "immutable_objects" => _node_rank_immutability($src),
  7973.         "cohesion" => _node_rank_cohesion($src),
  7974.         "cyclomatic_complexity" => _node_rank_cyclomatic($src),
  7975.         "dependency_inversion" => _node_rank_dependency_inversion($src),
  7976.         "no_magic_numbers" => _node_rank_magic_numbers($src),
  7977.         "interface_segregation" => _node_rank_interface_segregation($src),
  7978.         "single_responsibility" => _node_rank_single_responsibility($src),
  7979.         "security" => _node_rank_security($src),
  7980.         "performance" => _node_rank_performance($src),
  7981.         "documentation" => _node_rank_documentation($src),
  7982.         "coding_standards" => _node_rank_coding_standards($src),
  7983.     ]);
  7984. }
  7985.  
  7986. // ═════════════════════════════════════════════════════════════════════════════
  7987. // Scoring — function level
  7988. // ═════════════════════════════════════════════════════════════════════════════
  7989.  
  7990. function _node_rank_function_score(string $src, string $name, string $body): array
  7991. {
  7992.     return h(
  7993.         "rank.function.metrics",
  7994.         [
  7995.             "calls" => _node_rank_calls($src, $name),
  7996.             "docs" => str_contains($body, "/**") ? substr_count($body, "@") * 1.5 : -15.0,
  7997.             "lines" => _node_rank_lines($body),
  7998.             "args" => _node_rank_parameters($name, $body),
  7999.             "branching" => _node_rank_branching($body),
  8000.             "divisions" => -(preg_match_all("/[^a-zA-Z0-9_]\s*\/\s*(?![\/*])/", $body) * 3.0),
  8001.             "string_ops" => _node_rank_string_ops($body),
  8002.             "builtins" => _node_rank_builtin_usage($body),
  8003.             "ifelse" => _node_rank_ifelse_balance($body),
  8004.         ],
  8005.         [$name],
  8006.     );
  8007. }
  8008.  
  8009. // ═════════════════════════════════════════════════════════════════════════════
  8010. // File-level metric helpers (collapsed from old _node_file_* functions)
  8011. // ═════════════════════════════════════════════════════════════════════════════
  8012.  
  8013. function _node_rank_typed_properties(string $src): float
  8014. {
  8015.     preg_match_all('/\b(?:public|protected|private)\s+(?:static\s+)?(?:readonly\s+)?(?:([\w?|]+)\s+)?(\$\w+)/', $src, $m, PREG_SET_ORDER);
  8016.     $total = count($m);
  8017.     if (!$total) {
  8018.         return 0.0;
  8019.     }
  8020.     $typed = count(array_filter($m, fn($x) => !empty($x[1])));
  8021.     $unions = count(array_filter($m, fn($x) => str_contains($x[1] ?? "", "|")));
  8022.     return -((($total - $typed) / $total) * 10.0) + $unions;
  8023. }
  8024.  
  8025. function _node_rank_final_class(string $src): float
  8026. {
  8027.     $total = preg_match_all("/\bclass\s+\w+/", $src);
  8028.     if (!$total) {
  8029.         return 0.0;
  8030.     }
  8031.     $final = preg_match_all("/\bfinal\s+class\b/i", $src);
  8032.     return -((($total - $final) / $total) * 5.0);
  8033. }
  8034.  
  8035. function _node_rank_modern_visibility(string $src): float
  8036. {
  8037.     return preg_match_all('/\b(?:public|private|protected)\s+\$/', $src) * 0.1 - preg_match_all('/\bvar\s+\$/', $src) * 5.0;
  8038. }
  8039.  
  8040. function _node_rank_match_vs_switch(string $src): float
  8041. {
  8042.     $switch = preg_match_all("/\bswitch\s*\(/", $src);
  8043.     return $switch ? (preg_match_all("/\bmatch\s*\(/", $src) / $switch) * 3.0 : 0.0;
  8044. }
  8045.  
  8046. function _node_rank_array_is_list(string $src): float
  8047. {
  8048.     $manual = preg_match_all('/array_keys\s*\([^)]+\)\s*===\s*range\s*\(|isset\s*\(\s*\$[^)]+\[\d+\])/', $src);
  8049.     return $manual ? min((preg_match_all("/\barray_is_list\s*\(/", $src) / $manual) * 2.0, 2.0) : 0.0;
  8050. }
  8051.  
  8052. function _node_rank_immutability(string $src): float
  8053. {
  8054.     $total = preg_match_all('/\b(?:public|protected|private)\s+(?:readonly\s+)?(?:static\s+)?[\w?|]+\s+\$\w+/', $src);
  8055.     if (!$total) {
  8056.         return 0.0;
  8057.     }
  8058.     $private = preg_match_all('/\bprivate\s+(?:readonly\s+)?[\w?|]+\s+\$\w+/', $src);
  8059.     $noSet = !preg_match("/public\s+function\s+set\w+\s*\(/", $src);
  8060.     return ($private / $total) * 5.0 + ($noSet ? 2.0 : 0.0);
  8061. }
  8062.  
  8063. function _node_rank_cohesion(string $src): float
  8064. {
  8065.     preg_match_all("/\bclass\s+\w+.*?\{(.*?)\}(?=\s*class|\Z)/s", $src, $classes, PREG_SET_ORDER);
  8066.     if (empty($classes)) {
  8067.         return 0.0;
  8068.     }
  8069.     $total = 0.0;
  8070.     $count = 0;
  8071.     foreach ($classes as $class) {
  8072.         preg_match_all("/(?:public|protected|private)\s+function\s+\w+\s*\([^)]*\)\s*\{(.*?)\}(?=\s*(?:public|protected|private)\s+function|\Z)/s", $class[1], $methods, PREG_SET_ORDER);
  8073.         $n = count($methods);
  8074.         if ($n < 2) {
  8075.             continue;
  8076.         }
  8077.         $shared = 0;
  8078.         for ($i = 0; $i < $n; $i++) {
  8079.             for ($j = $i + 1; $j < $n; $j++) {
  8080.                 preg_match_all('/\$this->(\w+)/', $methods[$i][1] . $methods[$j][1], $props);
  8081.                 if (count(array_unique($props[1] ?? [])) > 0) {
  8082.                     $shared++;
  8083.                 }
  8084.             }
  8085.         }
  8086.         $total += ($shared / (($n * ($n - 1)) / 2)) * 10.0;
  8087.         $count++;
  8088.     }
  8089.     return $count ? $total / $count : 0.0;
  8090. }
  8091.  
  8092. function _node_rank_cyclomatic(string $src): float
  8093. {
  8094.     $fns = preg_match_all("/function\s+\w+\s*\(/", $src);
  8095.     if (!$fns) {
  8096.         return 0.0;
  8097.     }
  8098.     $dp = preg_match_all("/\b(?:if|elseif|while|for|foreach|case|catch|match)\b|\|\||&&/", $src);
  8099.     $avg = $dp / $fns;
  8100.     return match (true) {
  8101.         $avg <= 5 => 0.0,
  8102.         $avg <= 10 => -3.0,
  8103.         $avg <= 15 => -6.0,
  8104.         $avg <= 20 => -9.0,
  8105.         default => -12.0,
  8106.     };
  8107. }
  8108.  
  8109. function _node_rank_dependency_inversion(string $src): float
  8110. {
  8111.     $total = preg_match_all("/function\s+\w+\s*\([^)]*\)/", $src);
  8112.     if (!$total) {
  8113.         return 0.0;
  8114.     }
  8115.     preg_match_all('/@param\s+(\w+)\s+\$\w+/', $src, $m);
  8116.     $abstract = count(array_filter($m[1] ?? [], fn($t) => preg_match("/^[A-Z]/", $t) && !preg_match('/^(int|string|bool|float|array|callable|mixed|void)$/', $t)));
  8117.     return ($abstract / $total) * 10.0;
  8118. }
  8119.  
  8120. function _node_rank_magic_numbers(string $src): float
  8121. {
  8122.     $magic = preg_match_all("/\b(?:[1-9]\d*|0)\b(?!\s*::)/", $src);
  8123.     return $magic ? (preg_match_all("/\bconst\s+\w+\s*=/", $src) / $magic) * 10.0 : 0.0;
  8124. }
  8125.  
  8126. function _node_rank_interface_segregation(string $src): float
  8127. {
  8128.     preg_match_all("/interface\s+\w+\s*\{[^}]*\}/s", $src, $ifaces);
  8129.     if (empty($ifaces[0])) {
  8130.         return 0.0;
  8131.     }
  8132.     $avg = array_sum(array_map(fn($i) => preg_match_all("/function\s+\w+\s*\(/", $i), $ifaces[0])) / count($ifaces[0]);
  8133.     return match (true) {
  8134.         $avg <= 3 => 0.0,
  8135.         $avg <= 5 => -3.0,
  8136.         $avg <= 8 => -6.0,
  8137.         default => -9.0,
  8138.     };
  8139. }
  8140.  
  8141. function _node_rank_single_responsibility(string $src): float
  8142. {
  8143.     preg_match_all("/\bclass\s+\w+(?:.*?)\{(.*?)\}(?=\s*class|\Z)/s", $src, $m, PREG_SET_ORDER);
  8144.     if (empty($m)) {
  8145.         return 0.0;
  8146.     }
  8147.     $avg = array_sum(array_map(fn($c) => substr_count($c[1], "\n"), $m)) / count($m);
  8148.     return match (true) {
  8149.         $avg <= 50 => 0.0,
  8150.         $avg <= 100 => -2.0,
  8151.         $avg <= 200 => -5.0,
  8152.         $avg <= 300 => -8.0,
  8153.         default => -12.0,
  8154.     };
  8155. }
  8156.  
  8157. function _node_rank_security(string $src): float
  8158. {
  8159.     $score = -(preg_match_all('/\$_(?:GET|POST)\s*\[.*?\]\s*\.\s*\$/', $src) * 15.0);
  8160.     $score -= preg_match_all('/echo\s+\$_(?:GET|POST|REQUEST)\s*\[/i', $src) * 12.0;
  8161.     $score -= preg_match_all('/(?:include|require)(?:_once)?\s*\(\s*\$/', $src) * 10.0;
  8162.     $score += preg_match_all("/htmlspecialchars|htmlentities|strip_tags/", $src) * 3.0;
  8163.     $score += preg_match_all("/password_hash|password_verify/", $src) * 4.0;
  8164.     $score += preg_match_all("/prepared.*statement|PDO::quote/i", $src) * 5.0;
  8165.     return $score;
  8166. }
  8167.  
  8168. function _node_rank_performance(string $src): float
  8169. {
  8170.     $score = -(preg_match_all("/SELECT\s*\*\s*FROM/i", $src) * 5.0);
  8171.     $score -= preg_match_all('/file_get_contents\s*\(\s*["\']http/', $src) * 3.0;
  8172.     $score += preg_match_all("/\byield\b|Generator\b/", $src) * 4.0;
  8173.     $score += preg_match_all("/\bcache\b|\bCache\b/i", $src) * 3.0;
  8174.     return $score;
  8175. }
  8176.  
  8177. function _node_rank_documentation(string $src): float
  8178. {
  8179.     $total = preg_match_all("/(?:(?:public|protected|private|static)\s+)*function\s+\w+\s*\(/i", $src);
  8180.     if (!$total) {
  8181.         return 0.0;
  8182.     }
  8183.     $docs = preg_match_all("/\/\*\*.*?\*\/\s*(?:(?:public|protected|private|static)\s+)*function\s+\w+/s", $src);
  8184.     $pct = ($docs / $total) * 100;
  8185.     return match (true) {
  8186.         $pct >= 90 => 0.0,
  8187.         $pct >= 75 => -2.0,
  8188.         $pct >= 50 => -5.0,
  8189.         $pct >= 25 => -8.0,
  8190.         default => -12.0,
  8191.     };
  8192. }
  8193.  
  8194. function _node_rank_coding_standards(string $src): float
  8195. {
  8196.     $v = 0;
  8197.     $lines = explode("\n", $src);
  8198.     foreach ($lines as $i => $line) {
  8199.         $t = rtrim($line);
  8200.         if ($t !== $line) {
  8201.             $v++;
  8202.         } // trailing whitespace
  8203.         if (strlen($t) > 120 && !preg_match("/^\s*(?:\/\/|\/\*|#|\*)/", $t)) {
  8204.             $v++;
  8205.         } // line length
  8206.         if (str_starts_with($line, "\t")) {
  8207.             $v++;
  8208.         } // tabs
  8209.         if (preg_match("/\b(?:if|for|foreach|while|function|class)\b/", $t) && !str_ends_with($t, "{")) {
  8210.             $next = trim($lines[$i + 1] ?? "");
  8211.             if ($next === "{") {
  8212.                 $v++;
  8213.             } // allman brace
  8214.         }
  8215.     }
  8216.     if (count($lines) > 1000) {
  8217.         $v += 5;
  8218.     }
  8219.     return -($v * 1.5);
  8220. }
  8221.  
  8222. // ═════════════════════════════════════════════════════════════════════════════
  8223. // Function-level metric helpers
  8224. // ═════════════════════════════════════════════════════════════════════════════
  8225.  
  8226. function _node_rank_calls(string $src, string $name): float
  8227. {
  8228.     // Skip penalising test functions for simply existing
  8229.     if (str_starts_with($name, "test")) {
  8230.         return 0.0;
  8231.     }
  8232.  
  8233.     static $cache = [];
  8234.     if (isset($cache[$name])) {
  8235.         return $cache[$name];
  8236.     }
  8237.  
  8238.     $pat = "/(?<!function\s)" . preg_quote($name, "/") . "\s*\(/";
  8239.     $count = preg_match_all($pat, $src);
  8240.  
  8241.     // Search all tracked files — uses gitignore index, not _node_structure_call()
  8242.     foreach (_node_gitignore(":list:all") as $rel) {
  8243.         $abs = ROOT_PATH . $rel;
  8244.         if (!str_ends_with($abs, ".php") || !file_exists($abs)) {
  8245.             continue;
  8246.         }
  8247.         $fc = @file_get_contents($abs) ?: "";
  8248.         $count += preg_match_all($pat, $fc);
  8249.     }
  8250.  
  8251.     return $cache[$name] = $count * 1.25 - 50.0;
  8252. }
  8253.  
  8254. function _node_rank_lines(string $body): float
  8255. {
  8256.     if (!preg_match("/\{([\s\S]*)\}/", $body, $m)) {
  8257.         return 0.0;
  8258.     }
  8259.     $lines = substr_count($m[1], "\n") + (trim($m[1]) && !str_ends_with($m[1], "\n") ? 1 : 0);
  8260.     return 20 + $lines * -0.25;
  8261. }
  8262.  
  8263. function _node_rank_parameters(string $name, string $body): float
  8264. {
  8265.     if (!preg_match("/function\s+" . preg_quote($name, "/") . "\s*\(([^)]*)\)/", $body, $m)) {
  8266.         return 0.0;
  8267.     }
  8268.     $p = trim($m[1]);
  8269.     return ($p === "" ? 0 : count(array_filter(explode(",", $p)))) * -0.5;
  8270. }
  8271.  
  8272. function _node_rank_branching(string $body): float
  8273. {
  8274.     $dp = preg_match_all("/\b(?:if|elseif|else|switch|case|default|for|foreach|while|do|catch|match)\b/", $body);
  8275.     $dp += preg_match_all("/\|\||&&/", $body);
  8276.     $q = preg_match_all("/\?/", $body);
  8277.     $col = preg_match_all("/:/", $body);
  8278.     $dp += min($q, $col) - $q;
  8279.     if (preg_match("/(?:if|for|foreach|while)\s*\([^)]{100,}\)/s", $body)) {
  8280.         $dp += 2;
  8281.     }
  8282.     return $dp * -2.5;
  8283. }
  8284.  
  8285. function _node_rank_string_ops(string $body): float
  8286. {
  8287.     $ops = preg_match_all("/\.=?/", $body);
  8288.     $ops += preg_match_all(
  8289.         "/\b(?:str_replace|str_ireplace|strpos|stripos|strrpos|substr|strtolower|strtoupper|trim|ltrim|rtrim|implode|explode|sprintf|preg_replace|preg_match|str_pad)\s*\(/i",
  8290.         $body,
  8291.     );
  8292.     $ops += preg_match_all('/\.\s*\$\w+\s*\.\s*\$\w+/', $body) * 2;
  8293.     return $ops * -2.0;
  8294. }
  8295.  
  8296. function _node_rank_builtin_usage(string $body): float
  8297. {
  8298.     static $builtin = null;
  8299.     $builtin ??= array_map("strtolower", get_defined_functions()["internal"] ?? []);
  8300.     preg_match_all("/\b([a-zA-Z_][a-zA-Z0-9_]*)\s*\(/", $body, $m);
  8301.     $skip = ["if", "else", "for", "foreach", "while", "switch", "match", "function", "class", "return", "echo", "new"];
  8302.     $score = 0.0;
  8303.     foreach ($m[1] as $fn) {
  8304.         if (in_array(strtolower($fn), $skip)) {
  8305.             continue;
  8306.         }
  8307.         if (in_array(strtolower($fn), $builtin)) {
  8308.             $score += 2.0;
  8309.         }
  8310.     }
  8311.     return $score;
  8312. }
  8313.  
  8314. function _node_rank_ifelse_balance(string $body): float
  8315. {
  8316.     $ifs = preg_match_all("/\bif\s*\(/i", $body);
  8317.     $elses = preg_match_all("/\belse(?:if)?\b/i", $body);
  8318.     $unbal = max(0, $ifs - $elses);
  8319.     return $unbal * -0.15;
  8320. }
  8321.  
  8322. // ═════════════════════════════════════════════════════════════════════════════
  8323. // Output formatters
  8324. // ═════════════════════════════════════════════════════════════════════════════
  8325.  
  8326. function _node_rank_detail(string $fn, array $data, array $fileMetrics, float $fileTotal): string
  8327. {
  8328.     $notes = h("rank.function.notes", [
  8329.         "calls" => "More call sites = higher value. Unused functions are dead weight.",
  8330.         "docs" => "Add a docblock with @param/@return. Every tag adds score.",
  8331.         "lines" => "Keep functions under 20 lines — easier to test and read.",
  8332.         "args" => "Fewer parameters (<4) is better. Group related args into objects.",
  8333.         "branching" => "Flatten branching. Extract conditions into named methods.",
  8334.         "divisions" => "Division risks precision errors — minimise or wrap.",
  8335.         "string_ops" => "Heavy string work belongs in a dedicated helper or template.",
  8336.         "builtins" => "Prefer built-in PHP functions over custom re-implementations.",
  8337.         "ifelse" => "Every unmatched if is a potential unhandled path.",
  8338.     ]);
  8339.  
  8340.     $fileNotes = h("rank.file.notes", [
  8341.         "strict_types" => "Add declare(strict_types=1) — prevents silent type coercion.",
  8342.         "namespace" => "Add a namespace — global scope is fragile.",
  8343.         "no_superglobals" => "Inject request data, never read superglobals directly.",
  8344.         "typed_properties" => "Type every class property (PHP 7.4+).",
  8345.         "final_class" => "Mark classes final unless inheritance is intentional.",
  8346.         "modern_visibility" => "Replace var with public/protected/private.",
  8347.         "constructor_promotion" => "Use PHP 8 constructor promotion for cleaner DI.",
  8348.         "union_types" => "Use TypeA|TypeB union types where appropriate.",
  8349.         "nullsafe_operator" => "Replace null-guards with ?-> operator.",
  8350.         "match_expression" => "Prefer match() over switch() — exhaustive and expression-based.",
  8351.         "named_arguments" => "Named arguments self-document call sites.",
  8352.         "attributes" => "Replace docblock annotations with PHP 8 #[Attributes].",
  8353.         "enums" => "Replace constant groups with enums (PHP 8.1+).",
  8354.         "readonly_properties" => "Mark immutable properties readonly.",
  8355.         "never_return_type" => "Use :never for functions that always throw or exit.",
  8356.         "array_is_list" => "Use array_is_list() instead of manual key checks.",
  8357.         "first_class_callable" => "Use fn(...) first-class callables for clarity.",
  8358.         "immutable_objects" => "No public setters + private properties = immutable.",
  8359.         "cohesion" => "Methods should share state — if they don't, split the class.",
  8360.         "cyclomatic_complexity" => "High branching per function — extract sub-functions.",
  8361.         "dependency_inversion" => "Type-hint interfaces, not concretions.",
  8362.         "no_magic_numbers" => "Extract literals into named constants.",
  8363.         "interface_segregation" => "Large interfaces — split into focused contracts.",
  8364.         "single_responsibility" => "Large classes — split by behaviour.",
  8365.         "security" => "Validate input, escape output, use prepared statements.",
  8366.         "performance" => "Avoid SELECT *, sync HTTP calls, N+1 patterns.",
  8367.         "documentation" => "All public methods need docblocks.",
  8368.         "coding_standards" => "120 char limit, no tabs, no trailing whitespace, K&R braces.",
  8369.     ]);
  8370.  
  8371.     $out = "Function: {$fn}()\n";
  8372.     $out .= "Score:     " . number_format($data["score"], 1);
  8373.     $out .= "  (fn " . number_format($data["raw"], 1) . " + file " . number_format($fileTotal, 1) . ")\n\n";
  8374.  
  8375.     $fnNeg = array_filter($data["metrics"], fn($v) => $v < 0);
  8376.     if ($fnNeg) {
  8377.         $out .= "Function issues:\n";
  8378.         foreach ($fnNeg as $k => $v) {
  8379.             $out .= "  " . str_pad($k, 14) . number_format($v, 1);
  8380.             if (isset($notes[$k])) {
  8381.                 $out .= "  // " . $notes[$k];
  8382.             }
  8383.             $out .= "\n";
  8384.         }
  8385.     } else {
  8386.         $out .= "Function: no issues.\n";
  8387.     }
  8388.  
  8389.     $fileNeg = array_filter($fileMetrics, fn($v) => $v < 0);
  8390.     if ($fileNeg) {
  8391.         $out .= "\nFile issues:\n";
  8392.         foreach ($fileNeg as $k => $v) {
  8393.             $out .= "  " . str_pad($k, 24) . number_format($v, 1);
  8394.             if (isset($fileNotes[$k])) {
  8395.                 $out .= "  // " . $fileNotes[$k];
  8396.             }
  8397.             $out .= "\n";
  8398.         }
  8399.     } else {
  8400.         $out .= "\nFile: no issues.\n";
  8401.     }
  8402.  
  8403.     return h("rank.detail.output", $out, [$fn, $data]);
  8404. }
  8405.  
  8406. function _node_rank_summary(array $analysis, array $fileMetrics, float $fileTotal, string $absFile): string
  8407. {
  8408.     uasort($analysis, fn($a, $b) => $a["score"] <=> $b["score"]);
  8409.  
  8410.     $relFile = str_replace(ROOT_PATH, "", $absFile);
  8411.     $width = max(array_map("strlen", array_keys($analysis)));
  8412.     $out = "File: {$relFile}  [" . number_format($fileTotal, 1) . "]\n\n";
  8413.  
  8414.     $fns = array_keys($analysis);
  8415.     $best = array_slice(array_reverse($fns), 0, 3);
  8416.     $worst = array_slice($fns, 0, min(5, count($fns)));
  8417.  
  8418.     if ($best) {
  8419.         $out .= "Best:\n";
  8420.         foreach ($best as $fn) {
  8421.             $out .= "  " . str_pad("$fn()", $width + 2) . number_format($analysis[$fn]["score"], 1) . "\n";
  8422.         }
  8423.     }
  8424.  
  8425.     $out .= "\nNeeds work:\n";
  8426.     foreach ($worst as $fn) {
  8427.         $d = $analysis[$fn];
  8428.         $neg = implode(
  8429.             "  ",
  8430.             array_map(fn($k, $v) => "{$k}:" . number_format($v, 1), array_keys(array_filter($d["metrics"], fn($v) => $v < 0)), array_filter($d["metrics"], fn($v) => $v < 0)),
  8431.         );
  8432.         $out .= "  " . str_pad("$fn()", $width + 2) . number_format($d["score"], 1) . "  " . $neg . "\n";
  8433.     }
  8434.  
  8435.     // File metric columns
  8436.     $pos = array_filter($fileMetrics, fn($v) => $v > 0);
  8437.     $neg = array_filter($fileMetrics, fn($v) => $v < 0);
  8438.     arsort($pos);
  8439.     asort($neg);
  8440.     $all = [...array_map(fn($k, $v) => "{$k} " . number_format($v, 1), array_keys($pos), $pos), ...array_map(fn($k, $v) => "{$k} " . number_format($v, 1), array_keys($neg), $neg)];
  8441.     $cols = 3;
  8442.     $rows = (int) ceil(count($all) / $cols);
  8443.     $w = max(array_map("strlen", $all) ?: [0]);
  8444.     $out .= "\nFile metrics:\n";
  8445.     for ($i = 0; $i < $rows; $i++) {
  8446.         $line = "";
  8447.         for ($c = 0; $c < $cols; $c++) {
  8448.             $item = $all[$i + $c * $rows] ?? "";
  8449.             $line .= str_pad($item, $w + 2);
  8450.         }
  8451.         $out .= "  " . rtrim($line) . "\n";
  8452.     }
  8453.  
  8454.     return h("rank.summary.output", $out, [$analysis, $absFile]);
  8455. }
  8456. # rank end
  8457.  
  8458. # build begin dev
  8459. /**
  8460.  * Normalize namespace_map entries by prepending target_namespace
  8461.  * to any entry that does not already start with it.
  8462.  * This allows build files to write short relative namespaces:
  8463.  *   "namespace_map": { "WordPress/Hook": "Hooks" }
  8464.  * instead of repeating the root every time:
  8465.  *   "namespace_map": { "WordPress/Hook": "MyPlugin\\Hooks" }
  8466.  */
  8467. function _node_build_normalize_namespaces(array $def): array
  8468. {
  8469.     $root = rtrim($def["target_namespace"] ?? "", "\\");
  8470.  
  8471.     if (empty($root) || empty($def["namespace_map"])) {
  8472.         return $def;
  8473.     }
  8474.  
  8475.     foreach ($def["namespace_map"] as $structPath => $ns) {
  8476.         // Only prepend if the entry is not already rooted at target_namespace
  8477.         if (!str_starts_with($ns, "$root\\") && $ns !== $root) {
  8478.             $def["namespace_map"][$structPath] = "$root\\" . ltrim($ns, "\\");
  8479.         }
  8480.     }
  8481.  
  8482.     return $def;
  8483. }
  8484.  
  8485. /**
  8486.  * Load a build definition by name, merging NodePHP installation base
  8487.  * with any project-level override — same pattern as struct documentation.
  8488.  *
  8489.  * @param  string $name  Build name without .json (e.g. "chrome.extension")
  8490.  * @return array         Merged build definition, or [] if neither file exists.
  8491.  */
  8492. function _node_build_load_merged(string $name): array
  8493. {
  8494.     // NodePHP installation base (read-only, shared across all projects)
  8495.     $basePath = __DIR__ . D . "NodePHP" . D . "Build" . D . "Map" . D . "{$name}.json";
  8496.  
  8497.     // Project-level override (optional, project-specific additions)
  8498.     $projPath = _node_project("path") . "Build" . D . "Map" . D . "{$name}.json";
  8499.  
  8500.     $base = [];
  8501.     $proj = [];
  8502.  
  8503.     if (file_exists($basePath)) {
  8504.         $raw = @file_get_contents($basePath);
  8505.         if ($raw) {
  8506.             $base = json_decode($raw, true) ?: [];
  8507.         }
  8508.     }
  8509.  
  8510.     if (file_exists($projPath)) {
  8511.         $raw = @file_get_contents($projPath);
  8512.         if ($raw) {
  8513.             $proj = json_decode($raw, true) ?: [];
  8514.         }
  8515.     }
  8516.  
  8517.     if (empty($base) && empty($proj)) {
  8518.         return [];
  8519.     }
  8520.  
  8521.     $merged = h("build.definition.merged", _node_build_deep_merge($base, $proj), [$name]);
  8522.  
  8523.     // Normalize before returning so every consumer gets clean namespaces
  8524.     return _node_build_normalize_namespaces($merged);
  8525. }
  8526.  
  8527. /**
  8528.  * Recursive merge where $override wins on scalar conflicts.
  8529.  * Arrays are merged recursively (not replaced), so "map" entries
  8530.  * from both files survive.
  8531.  */
  8532. function _node_build_deep_merge(array $base, array $override): array
  8533. {
  8534.     foreach ($override as $k => $v) {
  8535.         $base[$k] = isset($base[$k]) && is_array($base[$k]) && is_array($v) ? _node_build_deep_merge($base[$k], $v) : $v;
  8536.     }
  8537.     return $base;
  8538. }
  8539.  
  8540. /**
  8541.  * Resolve the effective dist path for a build definition.
  8542.  * node.json "build_dist" overrides the build file's "dist" key.
  8543.  * Returns absolute path with trailing D.
  8544.  */
  8545. function _node_build_dist_path(array $buildDef): string
  8546. {
  8547.     $nodeJson = _node_migrate_load(_node_project("path") . "node.json");
  8548.     $dist = $nodeJson["build_dist"] ?? ($buildDef["dist"] ?? "dist");
  8549.     // dist is always relative to project root — never absolute
  8550.     return _node_project("path") . trim($dist, D) . D;
  8551. }
  8552.  
  8553. /**
  8554.  * Rewrite namespace and use statements in a PHP file's content
  8555.  * to match the destination environment defined by the build map.
  8556.  *
  8557.  * Resolution order for the destination namespace of a file:
  8558.  *   1. Explicit entry in build map "namespace_map" for this struct path.
  8559.  *   2. Derived from "target_namespace" + the struct path segments.
  8560.  *   3. If neither is defined, content is returned unchanged.
  8561.  *
  8562.  * Use statements are rewritten by replacing any known source namespace
  8563.  * prefix (PROJECT_NAME\StructPath) with the corresponding destination
  8564.  * namespace — walking every entry in the combined namespace map so that
  8565.  * cross-struct dependencies resolve correctly in the destination.
  8566.  *
  8567.  * @param string $content     Raw PHP file content.
  8568.  * @param string $structPath  The NodePHP struct path this file came from
  8569.  *                            e.g. "Domain/Logic/Service".
  8570.  * @param array  $def         Merged build definition array.
  8571.  * @return string             Rewritten content, or original if no rewrite needed.
  8572.  */
  8573. function _node_build_rewrite_php(string $content, string $structPath, array $def): string
  8574. {
  8575.     $targetNs = $def["target_namespace"] ?? null;
  8576.     $namespaceMap = $def["namespace_map"] ?? [];
  8577.  
  8578.     // Build a full source→dest namespace translation table for every
  8579.     // mapped struct path so use statements resolve across the whole project.
  8580.     $projectNs = str_replace(D, "\\", _node_project("name"));
  8581.  
  8582.     $nsTable = [];
  8583.     foreach (array_keys($def["map"] ?? []) as $sp) {
  8584.         $srcNs = "$projectNs\\" . str_replace(D, "\\", $sp);
  8585.  
  8586.         if (isset($namespaceMap[$sp])) {
  8587.             // Explicit override wins
  8588.             $dstNs = $namespaceMap[$sp];
  8589.         } elseif ($targetNs !== null) {
  8590.             // Derive from target_namespace + struct segments
  8591.             $dstNs = rtrim($targetNs, "\\") . "\\" . str_replace(D, "\\", $sp);
  8592.         } else {
  8593.             // No rewrite rule for this path
  8594.             continue;
  8595.         }
  8596.  
  8597.         $nsTable[$srcNs] = $dstNs;
  8598.     }
  8599.  
  8600.     if (empty($nsTable)) {
  8601.         // No rewrite rules defined in this build map — return unchanged
  8602.         return $content;
  8603.     }
  8604.  
  8605.     $ownSrcNs = "$projectNs\\" . str_replace(D, "\\", $structPath);
  8606.  
  8607.     if (isset($namespaceMap[$structPath])) {
  8608.         $ownDstNs = $namespaceMap[$structPath];
  8609.     } elseif ($targetNs !== null) {
  8610.         $ownDstNs = rtrim($targetNs, "\\") . "\\" . str_replace(D, "\\", $structPath);
  8611.     } else {
  8612.         $ownDstNs = null;
  8613.     }
  8614.  
  8615.     if ($ownDstNs !== null) {
  8616.         // Handles both "namespace Foo\Bar;" and "namespace Foo\Bar {"
  8617.         $content = preg_replace("/^(namespace\s+)" . preg_quote($ownSrcNs, "/") . "(\s*[;{])/m", '${1}' . $ownDstNs . '${2}', $content);
  8618.  
  8619.         // If the original namespace was not the exact project path
  8620.         // (e.g. the file used a shorter/different root), catch it with
  8621.         // a broader replacement keyed on the struct path alone.
  8622.         if (!str_contains($content, "namespace {$ownDstNs}")) {
  8623.             $content = preg_replace(
  8624.                 "/^(namespace\s+\S+\\\\)" . preg_quote(str_replace(D, "\\", $structPath), "/") . "(\s*[;{])/m",
  8625.                 '${1}' . str_replace(D, "\\", $structPath) . '${2}',
  8626.                 $content,
  8627.             );
  8628.         }
  8629.     }
  8630.  
  8631.     // Sort by source namespace length descending so longer (more specific)
  8632.     // prefixes are replaced before shorter ones that might be substrings.
  8633.     uksort($nsTable, fn($a, $b) => strlen($b) - strlen($a));
  8634.  
  8635.     foreach ($nsTable as $srcNs => $dstNs) {
  8636.         // "use SrcNs\ClassName;" → "use DstNs\ClassName;"
  8637.         $content = preg_replace("/^(use\s+)" . preg_quote($srcNs, "/") . "(\\\\[^;]+;)/m", '${1}' . $dstNs . '${2}', $content);
  8638.  
  8639.         // "use SrcNs;" → "use DstNs;"
  8640.         $content = preg_replace("/^(use\s+)" . preg_quote($srcNs, "/") . "(\s*;)/m", '${1}' . $dstNs . '${2}', $content);
  8641.  
  8642.         // Group use: "use SrcNs\{Foo, Bar};" → "use DstNs\{Foo, Bar};"
  8643.         $content = preg_replace("/^(use\s+)" . preg_quote($srcNs, "/") . "(\s*\{[^}]+\};)/m", '${1}' . $dstNs . '${2}', $content);
  8644.     }
  8645.  
  8646.     return h("build.php.rewritten", $content, [$structPath, $def]);
  8647. }
  8648.  
  8649. /**
  8650.  * List all build map files available: from NodePHP installation + project.
  8651.  * Returns ["chrome.extension" => true, ...] deduplicated.
  8652.  */
  8653. function _node_build_available(): array
  8654. {
  8655.     $baseMaps = glob(__DIR__ . D . "NodePHP" . D . "Build" . D . "Map" . D . "*.json") ?: [];
  8656.     $projMaps = glob(_node_project("path") . "Build" . D . "Map" . D . "*.json") ?: [];
  8657.  
  8658.     $names = [];
  8659.     foreach ([...$baseMaps, ...$projMaps] as $f) {
  8660.         $names[basename($f, ".json")] = true;
  8661.     }
  8662.     ksort($names);
  8663.     return $names;
  8664. }
  8665.  
  8666. /**
  8667.  * Build command — assembles a project into a distribution folder
  8668.  * using a named build map (e.g. "chrome.extension", "website").
  8669.  *
  8670.  * build Show help
  8671.  * build list List available build maps with match %
  8672.  * build init <name> Scaffold missing resources from a build map
  8673.  * build <name> Execute a build into dist/latest/
  8674.  */
  8675. function build(mixed ...$args): mixed
  8676. {
  8677.     $args = array_filter($args, fn($a) => $a !== null && $a !== "");
  8678.  
  8679.     if (empty($args)) {
  8680.         return implode(
  8681.             "\n",
  8682.             h("build.help", [
  8683.                 "build list List available build maps ranked by project match.",
  8684.                 "build init <name> Scaffold missing resources from build map into project.",
  8685.                 "build <name> Execute build using named map (without .json).",
  8686.                 "",
  8687.                 "Build map files live in:",
  8688.                 "- " . __DIR__ . D . "NodePHP" . D . "Build" . D . "Map" . D . "*.json (base)",
  8689.                 "- " . _node_project("path") . "Build" . D . "Map" . D . "*.json (project override)",
  8690.                 "",
  8691.                 "node.json keys:",
  8692.                 "- \"build\" Name of the active build map (without .json).",
  8693.                 "- \"build_dist\" Overrides the dist path defined in the build map.",
  8694.             ]),
  8695.         );
  8696.     }
  8697.  
  8698.     if ($args[0] === "list") {
  8699.         $available = _node_build_available();
  8700.         if (empty($available)) {
  8701.             return "No build maps found.\n";
  8702.         }
  8703.  
  8704.         $projectFiles = _node_gitignore(":list:all");
  8705.         $projectFilesFlat = array_map(fn($f) => ltrim($f, "!"), $projectFiles);
  8706.  
  8707.         $results = [];
  8708.  
  8709.         foreach (array_keys($available) as $name) {
  8710.             $def = _node_build_load_merged($name);
  8711.             $map = $def["map"] ?? [];
  8712.  
  8713.             if (empty($map)) {
  8714.                 $results[] = ["name" => $name, "pct" => 0, "entries" => []];
  8715.                 continue;
  8716.             }
  8717.  
  8718.             $entries = [];
  8719.             $found = 0;
  8720.  
  8721.             foreach ($map as $structPath => $distPath) {
  8722.                 // Check if any tracked file lives under this struct path
  8723.                 $structAbs = _node_project("path") . $structPath;
  8724.                 $exists = false;
  8725.                 foreach ($projectFilesFlat as $rel) {
  8726.                     if (str_starts_with(ROOT_PATH . $rel, $structAbs)) {
  8727.                         $exists = true;
  8728.                         break;
  8729.                     }
  8730.                 }
  8731.                 // Also accept if the directory itself exists (even if no files tracked yet)
  8732.                 if (!$exists && is_dir($structAbs)) {
  8733.                     $exists = true;
  8734.                 }
  8735.                 if ($exists) {
  8736.                     $found++;
  8737.                 }
  8738.                 $entries[] = ["label" => "{$structPath} -> {$distPath}", "found" => $exists];
  8739.             }
  8740.  
  8741.             $pct = count($map) > 0 ? round(($found / count($map)) * 100) : 0;
  8742.             $results[] = ["name" => $name, "pct" => $pct, "entries" => $entries];
  8743.         }
  8744.  
  8745.         // Sort by match percentage descending
  8746.         usort($results, fn($a, $b) => $b["pct"] <=> $a["pct"]);
  8747.  
  8748.         $out = "";
  8749.         foreach ($results as $r) {
  8750.             if ($r["pct"] >= 75) {
  8751.                 $out .= "\n{$r["name"]} // {$r["pct"]}%\n";
  8752.                 foreach ($r["entries"] as $e) {
  8753.                     $tag = $e["found"] ? "[found]  " : "[missing]";
  8754.                     $out .= " * {$tag} {$e["label"]}\n";
  8755.                 }
  8756.             } else {
  8757.                 // Below threshold — list name only, no percentage
  8758.                 $out .= "\n{$r["name"]}\n";
  8759.             }
  8760.         }
  8761.  
  8762.         return $out ?: "No build maps found.\n";
  8763.     }
  8764.  
  8765.     if (str_starts_with($args[0], "init")) {
  8766.         $name = _node_argex($args, 1);
  8767.         if (!$name) {
  8768.             return r("build init: provide a build map name (without .json).", "Info", 1);
  8769.         }
  8770.  
  8771.         $def = _node_build_load_merged($name);
  8772.         if (empty($def)) {
  8773.             return r("build init: no build map found for '{$name}'.", "Info", 1);
  8774.         }
  8775.  
  8776.         $map = $def["map"] ?? [];
  8777.         $keys = struct(":keys");
  8778.         $out = "Initialising project for build [{$name}]:\n\n";
  8779.  
  8780.         foreach ($map as $structPath => $distPath) {
  8781.             // Check if this struct path exists in the combined key set
  8782.             if (!array_key_exists($structPath, $keys)) {
  8783.                 $out .= "  [skip]    {$structPath}  (not in struct definition)\n";
  8784.                 continue;
  8785.             }
  8786.  
  8787.             $absDir = _node_project("path") . $structPath;
  8788.  
  8789.             if (is_dir($absDir) && !empty(glob($absDir . D . "*"))) {
  8790.                 $out .= "  [exists]  {$structPath}\n";
  8791.                 continue;
  8792.             }
  8793.  
  8794.             // Use struct new to create a placeholder resource — this populates
  8795.             // gitignore, docs, and unit tests automatically.
  8796.             $structParts = explode(D, $structPath);
  8797.             $leafName = array_pop($structParts);
  8798.             $structure = implode(D, $structParts);
  8799.  
  8800.             // Determine type from the key definition
  8801.             $allowedTypes = $keys[$structPath];
  8802.             $type = in_array("class", $allowedTypes) ? "class" : (isset($allowedTypes[0]) && str_starts_with($allowedTypes[0], ".") ? null : $allowedTypes[0] ?? null);
  8803.  
  8804.             if ($type && !str_starts_with($type, ".")) {
  8805.                 $createResult = struct("new", $structure, $leafName, $type);
  8806.                 $out .= "  [created] {$structPath}  ({$type})\n";
  8807.                 if (is_string($createResult)) {
  8808.                     $out .= "            " . trim(str_replace("\n", "\n            ", $createResult)) . "\n";
  8809.                 }
  8810.             } else {
  8811.                 // Asset-only leaf — just make the directory and gitignore it
  8812.                 if (!is_dir($absDir)) {
  8813.                     mkdir($absDir, 0777, true);
  8814.                 }
  8815.                 $placeholder = $absDir . D . ".gitkeep";
  8816.                 if (!file_exists($placeholder)) {
  8817.                     file_put_contents($placeholder, "");
  8818.                     _node_gitignore($placeholder, "write");
  8819.                 }
  8820.                 $out .= "  [mkdir]   {$structPath}\n";
  8821.             }
  8822.         }
  8823.  
  8824.         // Set build key in node.json
  8825.         $nodeJsonFile = _node_project("path") . "node.json";
  8826.         if (file_exists($nodeJsonFile)) {
  8827.             $nodeData = _node_migrate_load($nodeJsonFile);
  8828.             if (($nodeData["build"] ?? null) !== $name) {
  8829.                 $nodeData["build"] = $name;
  8830.                 _node_migrate_save($nodeJsonFile, $nodeData);
  8831.                 $out .= "\nnode.json: build set to \"{$name}\"\n";
  8832.             }
  8833.         }
  8834.  
  8835.         return $out;
  8836.     }
  8837.  
  8838.     $name = $args[0];
  8839.     $def = _node_build_load_merged($name);
  8840.  
  8841.     if (empty($def)) {
  8842.         return r("build: no build map found for '{$name}'.", "Info", 1);
  8843.     }
  8844.  
  8845.     // node.json build_dist overrides the map's dist key
  8846.     $distRoot = _node_build_dist_path($def);
  8847.  
  8848.     $latestDir = "{$distRoot}latest" . D;
  8849.  
  8850.     if (is_dir($distRoot) && is_dir($latestDir)) {
  8851.         // Rename latest → next semver folder
  8852.         $version = _node_build_next_version($distRoot);
  8853.         rename($latestDir, "$distRoot$version" . D);
  8854.         r("build: archived previous build as {$version}", "Info", 0);
  8855.     }
  8856.  
  8857.     // Create fresh latest/
  8858.     if (!is_dir($latestDir)) {
  8859.         mkdir($latestDir, 0777, true);
  8860.     }
  8861.  
  8862.     $map = $def["map"] ?? [];
  8863.     $copied = 0;
  8864.     $skipped = 0;
  8865.     $missing = 0;
  8866.     $log = "";
  8867.  
  8868.     $nodeJsonData = _node_migrate_load(_node_project("path") . "node.json");
  8869.  
  8870.     foreach ($map as $structPath => $distRelPath) {
  8871.         $srcDir = _node_project("path") . $structPath;
  8872.  
  8873.         // If not in project, look in NodePHP installation
  8874.         if (!is_dir($srcDir)) {
  8875.             $srcDir = __DIR__ . D . "NodePHP" . D . $structPath;
  8876.         }
  8877.  
  8878.         // Also check dependency projects
  8879.         if (!is_dir($srcDir)) {
  8880.             foreach ($nodeJsonData["dependencies"] ?? [] as $dep) {
  8881.                 $depDir = ROOT_PATH . $dep . D . $structPath;
  8882.                 if (is_dir($depDir)) {
  8883.                     $srcDir = $depDir;
  8884.                     break;
  8885.                 }
  8886.             }
  8887.         }
  8888.  
  8889.         if (!is_dir($srcDir)) {
  8890.             $log .= "  [missing] {$structPath}\n";
  8891.             $missing++;
  8892.             continue;
  8893.         }
  8894.  
  8895.         $dstDir = $latestDir . trim($distRelPath, D) . D;
  8896.         if (!is_dir($dstDir)) {
  8897.             mkdir($dstDir, 0777, true);
  8898.         }
  8899.  
  8900.         $files = glob($srcDir . D . "*") ?: [];
  8901.         foreach ($files as $srcFile) {
  8902.             if (!is_file($srcFile)) {
  8903.                 continue;
  8904.             }
  8905.  
  8906.             $dst = $dstDir . basename($srcFile);
  8907.             $content = @file_get_contents($srcFile);
  8908.  
  8909.             if ($content === false) {
  8910.                 $log .= "  [error]   read failed: {$srcFile}\n";
  8911.                 continue;
  8912.             }
  8913.  
  8914.             // Rewrite namespace and use statements for PHP files
  8915.             if (str_ends_with(strtolower($srcFile), ".php")) {
  8916.                 $content = _node_build_rewrite_php($content, $structPath, $def);
  8917.             }
  8918.  
  8919.             if (file_put_contents($dst, $content) !== false) {
  8920.                 $copied++;
  8921.             } else {
  8922.                 $log .= "  [error]   write failed: {$dst}\n";
  8923.             }
  8924.         }
  8925.         $log .= "  [ok]      {$structPath} -> {$distRelPath}\n";
  8926.     }
  8927.  
  8928.     foreach (h("build.commands", $def["commands"] ?? []) as $cmd) {
  8929.         $result = shell_exec("$cmd 2>&1");
  8930.         $log .= "  [cmd]     {$cmd}\n";
  8931.         if ($result) {
  8932.             $log .= "            " . trim(str_replace("\n", "\n            ", $result)) . "\n";
  8933.         }
  8934.     }
  8935.  
  8936.     // Only performed if the build map defines a "node" output path.
  8937.     if (!empty($def["node"])) {
  8938.         $nodeDstRel = ltrim($def["node"], D);
  8939.         $nodeDst = "$latestDir$nodeDstRel";
  8940.  
  8941.         if (!is_dir(dirname($nodeDst))) {
  8942.             mkdir(dirname($nodeDst), 0777, true);
  8943.         }
  8944.  
  8945.         // 1. Copy node.php into a temp file — isolated from original
  8946.         $nodeSrc = __DIR__ . D . "node.php";
  8947.         $tmpNode = tempnam(sys_get_temp_dir(), "nodephp_build_") . ".php";
  8948.         copy($nodeSrc, $tmpNode);
  8949.  
  8950.         // 2. Run wrap("prod") on the temp copy, still inside temp dir
  8951.         $prevDir = getcwd();
  8952.         chdir(sys_get_temp_dir());
  8953.  
  8954.         // wrap() uses the file path to write an env-suffixed file.
  8955.         // We call it directly on the temp path.
  8956.         $wrapped = wrap($tmpNode, "prod");
  8957.  
  8958.         chdir($prevDir);
  8959.  
  8960.         // wrap() writes <filename>.prod.php — locate it
  8961.         $wrappedPath = preg_replace('/\.php$/', ".prod.php", $tmpNode);
  8962.  
  8963.         if (file_exists($wrappedPath)) {
  8964.             copy($wrappedPath, $nodeDst);
  8965.             unlink($wrappedPath);
  8966.             $log .= "  [node]    node.php (prod) -> {$nodeDstRel}\n";
  8967.         } elseif (file_exists($tmpNode)) {
  8968.             // wrap produced no env file — copy plain version as fallback
  8969.             copy($tmpNode, $nodeDst);
  8970.             $log .= "  [node]    node.php (unwrapped fallback) -> {$nodeDstRel}\n";
  8971.         } else {
  8972.             $log .= "  [node]    ERROR: could not produce node.php for {$nodeDstRel}\n";
  8973.         }
  8974.  
  8975.         // Clean up temp file
  8976.         if (file_exists($tmpNode)) {
  8977.             unlink($tmpNode);
  8978.         }
  8979.     }
  8980.  
  8981.     // ── dist is intentionally NOT added to .gitignore ─────────────────────────
  8982.     // The dist folder is always transient output — never tracked.
  8983.     // We explicitly ensure it stays out by doing nothing here.
  8984.  
  8985.     $summary = sprintf("Build [%s] complete: %d copied, %d missing -> %s\n", $name, $copied, $missing, str_replace(_node_project("path"), "", $latestDir));
  8986.  
  8987.     migrate("store", "build {$name}");
  8988.  
  8989.     return h("build.result", "$summary\n$log", [$name, $def]);
  8990. }
  8991.  
  8992. /**
  8993.  * Determine the next version folder name inside a dist root.
  8994.  * Scans for existing semver-named folders (0.0.1, 0.0.2 ...) and increments patch.
  8995.  */
  8996. function _node_build_next_version(string $distRoot): string
  8997. {
  8998.     $existing = glob("{$distRoot}[0-9]*", GLOB_ONLYDIR) ?: [];
  8999.     if (empty($existing)) {
  9000.         return "0.0.1";
  9001.     }
  9002.  
  9003.     $versions = array_map("basename", $existing);
  9004.     usort($versions, "version_compare");
  9005.     $last = end($versions);
  9006.  
  9007.     $parts = explode(".", $last);
  9008.     $patch = (int) array_pop($parts);
  9009.     $parts[] = $patch + 1;
  9010.  
  9011.     return implode(".", $parts);
  9012. }
  9013. # build end
  9014.  
  9015. # cli begin dev
  9016. if (PHP_SAPI === "cli" && isset($argv) && is_array($argv)) {
  9017.     p("boot", function ($phase, $state) use ($argv) {
  9018.         /**
  9019.          * @var object $this from Context class.
  9020.          */
  9021.         $this->global("time.start", microtime(true));
  9022.         $this->global("cli.arg0.isSelfName", in_array(basename($argv[0]), h("cli.escape.args", [NAME, NAME . ".php"])));
  9023.  
  9024.         $memory = number_format(memory_get_peak_usage() / 1024 / 1024, 2);
  9025.         $errors = implode(" ", array_map(fn($c) => ltrim($c, ":"), r(":inbox")));
  9026.  
  9027.         $this->global("cli.header", PROJECT_NAME . " php" . PHP_VERSION . " @{$memory}MB,");
  9028.         $this->global("cli.footer", PROJECT_NAME . " finished with " . (empty($errors) ? "no logs" : "{$errors};") . "");
  9029.     });
  9030.  
  9031.     p("discover", function ($phase, $state) use ($argv) {
  9032.         /**
  9033.          * @var object $this from Context class.
  9034.          */
  9035.         if (empty($argv) || ($this->global("cli.arg0.isSelfName") && count($argv) === 1)) {
  9036.             $this->private(
  9037.                 "globals",
  9038.                 array_filter(
  9039.                     array_map(
  9040.                         fn($k) => is_array($GLOBALS[$k])
  9041.                             ? (!empty($GLOBALS[$k])
  9042.                                 ? h("cli.globals.array", "\${$k}[" . count($GLOBALS[$k]) . "];")
  9043.                                 : null)
  9044.                             : "\${$k} = " . trim((string) h("cli.globals.val", $GLOBALS[$k])) . ";",
  9045.                         array_filter(array_keys($GLOBALS), fn($x) => $GLOBALS[$x] !== $this->global("cli.header") && $x),
  9046.                     ),
  9047.                 ),
  9048.             );
  9049.  
  9050.             $printHeader = $this->global("cli.header") . " help:\n";
  9051.             $phases = p(":dump")["phases"];
  9052.             $phaseOrder = p(":order");
  9053.             $phaseCursor = max(p(":cursor"), array_search($phase, $phases));
  9054.             die(
  9055.                 $printHeader .
  9056.                     implode("\n", [
  9057.                         ...["Globals:", implode(" ", $this->private("globals")), ""],
  9058.                         ...["Constants:", implode(", ", h("cli.constants", array_keys(get_defined_constants(true)["user"]))), ""],
  9059.                         ...["Functions:", implode(", ", h("cli.functions", array_filter(get_defined_functions()["user"], fn($f) => !str_starts_with($f, "_node_")))), ""],
  9060.                         ...[
  9061.                             "Phases:",
  9062.                             implode(", ", array_map(fn($k) => array_search($k, $phaseOrder) . ":{$k}[" . count($phases[$k]) . "]", array_keys($phases))) . " @{$phaseCursor}",
  9063.                             "",
  9064.                         ],
  9065.                     ]) .
  9066.                     "\n" .
  9067.                     $this->global("cli.footer") .
  9068.                     " @" .
  9069.                     round(microtime(true) - $this->global("time.start"), 4) .
  9070.                     "ms\n" /* .
  9071.                  vpd(f("sample2.vpd", "read"))*/
  9072.             );
  9073.         }
  9074.  
  9075.         return $this;
  9076.     });
  9077.  
  9078.     p("finalize", function ($phase, $state) use ($argv) {
  9079.         /**
  9080.          * @var object $this from Context class.
  9081.          */
  9082.         $argv = h("cli.argv", $this->global("cli.arg0.isSelfName") ? array_slice($argv, 1) : $argv);
  9083.  
  9084.         if (($argv[0] ?? "") === "run") {
  9085.             $entryArg = $argv[1] ?? node(":entry");
  9086.  
  9087.             if (empty($entryArg)) {
  9088.                 die(
  9089.                     $this->global("cli.header") .
  9090.                         " run: no entry point given and no entry in node.json.\nUsage: php node.php run <ProjectName/path/to/entry.php>\nOr set one with: node entry <path>\n"
  9091.                 );
  9092.             }
  9093.  
  9094.             // Derive project name from first segment of the given path
  9095.             $entryRel = ltrim(str_replace(["\\", "/"], D, $entryArg), D);
  9096.             $segments = explode(D, $entryRel);
  9097.             $derivedProject = $segments[0];
  9098.  
  9099.             // If the entry is a bare relative path inside current project,
  9100.             // prepend the current project name
  9101.             if (!is_dir(ROOT_PATH . $derivedProject)) {
  9102.                 $derivedProject = _node_project("name");
  9103.                 $entryRel = $derivedProject . D . $entryRel;
  9104.             }
  9105.  
  9106.             $absEntry = realpath(ROOT_PATH . $entryRel);
  9107.  
  9108.             if (!$absEntry || !file_exists($absEntry)) {
  9109.                 die($this->global("cli.header") . " run: entry point not found: " . ROOT_PATH . $entryRel . "\n");
  9110.             }
  9111.  
  9112.             // Switch project context
  9113.             _node_project("name", $derivedProject);
  9114.  
  9115.             $missing = node(":check");
  9116.             empty($missing) or die($this->global("cli.header") . " run: missing dependencies: " . implode(", ", $missing) . "\n" . "Expected at: " . ROOT_PATH . "<name>\n");
  9117.  
  9118.             $deps = node(":deps");
  9119.  
  9120.             // ── Execute dependency phases first, in declared order ─────────────
  9121.             // Each dependency's entry point (if it has one) runs its phase
  9122.             // registrations so their boot/discover/resolve handlers are loaded
  9123.             // before the current project's phases execute.
  9124.             p(":depload", "1");
  9125.             foreach (h("run.deps", $deps) as $dep) {
  9126.                 $depPath = ROOT_PATH . $dep . D;
  9127.                 $depNodeFile = "{$depPath}node.json";
  9128.  
  9129.                 if (!file_exists($depNodeFile)) {
  9130.                     continue; // Dep has no node.json, no phases to pre-load
  9131.                 }
  9132.  
  9133.                 $depManifest = json_decode(file_get_contents($depNodeFile), true);
  9134.                 $depEntry = $depManifest["entry"] ?? null;
  9135.  
  9136.                 if ($depEntry) {
  9137.                     $depEntryAbs = realpath($depPath . ltrim($depEntry, D));
  9138.                     if ($depEntryAbs && file_exists($depEntryAbs)) {
  9139.                         _node_project("name", $dep);
  9140.                         include_once $depEntryAbs;
  9141.                         _node_project("name", $derivedProject);
  9142.                     }
  9143.                 }
  9144.             }
  9145.             p(":depload", "");
  9146.  
  9147.             _node_project("name", $derivedProject);
  9148.             include $absEntry;
  9149.             exit(0);
  9150.         }
  9151.  
  9152.         if (function_exists($argv[0])) {
  9153.             $args = h(
  9154.                 "cli.args",
  9155.                 array_map(
  9156.                     fn($x) => !is_string($x)
  9157.                         ? $x
  9158.                         : (!($t = trim($x))
  9159.                             ? $x
  9160.                             : (($l = strtolower($t)) === "true"
  9161.                                 ? true
  9162.                                 : ($l === "false"
  9163.                                     ? false
  9164.                                     : ($l === "null"
  9165.                                         ? null
  9166.                                         : ($t === (string) (int) $t
  9167.                                             ? (int) $t
  9168.                                             : (is_numeric($t) && (string) (float) $t === $t
  9169.                                                 ? (float) $t
  9170.                                                 : ((($t[0] === "[" && $t[-1] === "]") || ($t[0] === "{" && $t[-1] === "}")) && ($d = json_decode($t, true)) !== null
  9171.                                                     ? $d
  9172.                                                     : $x))))))),
  9173.                     array_map("trim", explode(",", implode(" ", array_slice($argv, 1)))),
  9174.                 ),
  9175.             );
  9176.  
  9177.             $r = call_user_func($argv[0], ...$args);
  9178.             $r = h("cli.call.result", $r);
  9179.  
  9180.             $_nodeJson = _node_migrate_load(_node_project("path") . "node.json");
  9181.             if (!empty($_nodeJson["autorecord"])) {
  9182.                 $_recordedFns = [...MIGRATE_AUTORECORD_FUNCTIONS, ...$_nodeJson["autorecord_functions"] ?? []];
  9183.                 if (in_array($argv[0], $_recordedFns)) {
  9184.                     # Store the exact CLI invocation as-is
  9185.                    migrate("store", implode(" ", [...[$argv[0]], ...array_map(fn($a) => is_string($a) ? $a : json_encode($a), $args)]));
  9186.                 }
  9187.             }
  9188.  
  9189.             $rtLog = r(":runtime");
  9190.  
  9191.             echo $this->global("cli.header") .
  9192.                 " call:\n" .
  9193.                 w(":view") .
  9194.                 "\n" .
  9195.                 (empty($rtLog)
  9196.                     ? ""
  9197.                     : implode("\n", array_map(fn($k) => "{$k} (" . count($rtLog[$k]) . "):\n" . implode("\n", array_map(fn($e) => "{$e}", $rtLog[$k])) . "\n", array_keys($rtLog))) .
  9198.                         "\n") .
  9199.                 "Called [" .
  9200.                 implode(" ", $argv) .
  9201.                 "], returned:\n" .
  9202.                 (is_string($r) ? $r : (is_int($r) && !empty($rtLog) ? "Error with {$argv[0]}() : {$r}" : var_export($r, true))) .
  9203.                 "\n\n" .
  9204.                 $this->global("cli.footer") .
  9205.                 " @" .
  9206.                 round(microtime(true) - $this->global("time.start"), 4) .
  9207.                 "ms\n";
  9208.         } elseif (($writeResult = w(":opened") ? w(implode(" ", $argv)) : null) === null) {
  9209.             $code = h("cli.code", implode(" ", $argv));
  9210.             $eval = h("cli.eval", "return {$code};");
  9211.  
  9212.             if (empty(lint($eval))) {
  9213.                 try {
  9214.                     $r = h("cli.eval.result", eval($eval));
  9215.                     echo $this->global("cli.header") .
  9216.                         " php:\n" .
  9217.                         (is_string($r) ? $r : var_export($r, true)) .
  9218.                         "\n\n" .
  9219.                         $this->global("cli.footer") .
  9220.                         " @" .
  9221.                         round(microtime(true) - $this->global("time.start"), 4) .
  9222.                         "s\n";
  9223.                 } catch (Throwable $e) {
  9224.                     # Tiny msg.
  9225.                    $msg = $e->getMessage();
  9226.  
  9227.                     # Pass to shell.
  9228.                    echo $this->global("cli.header") .
  9229.                         " threw({$msg}), shell:\n" .
  9230.                         (shell_exec("{$code} 2>&1") ?? "") .
  9231.                         "\n\n" .
  9232.                         $this->global("cli.footer") .
  9233.                         " @" .
  9234.                         round(microtime(true) - $this->global("time.start"), 4) .
  9235.                         "ms\n";
  9236.                 }
  9237.             } else {
  9238.                 echo $this->global("cli.header") .
  9239.                     " shell:\n" .
  9240.                     (shell_exec("{$code} 2>&1") ?? "") .
  9241.                     "\n\n" .
  9242.                     $this->global("cli.footer") .
  9243.                     " @" .
  9244.                     round(microtime(true) - $this->global("time.start"), 4) .
  9245.                     "ms\n";
  9246.             }
  9247.         } else {
  9248.             echo "\033[2J\033[H" .
  9249.                 $this->global("cli.header") .
  9250.                 " editor:\n" .
  9251.                 w(":view") .
  9252.                 "Action [" .
  9253.                 implode(" ", $argv) .
  9254.                 "] returned: {$writeResult}\n\n" .
  9255.                 $this->global("cli.footer") .
  9256.                 " @" .
  9257.                 round(microtime(true) - $this->global("time.start"), 4) .
  9258.                 "ms\n";
  9259.         }
  9260.  
  9261.         # Return state.
  9262.        return $this;
  9263.     });
  9264. }
  9265. # cli end
  9266.  
  9267. # Run Node.php
  9268. p() or die(r(":PhaseException", "last"));
Add Comment
Please, Sign In to add comment