# MATLAB/MCP/Simulink and Tooling Runbook

Load this file only when the task involves MATLAB, Simulink, Speedgoat/SLRT, SAP/FEM workflows, MCP tool execution, browser recovery, GitHub CLI work, or recovery from a recurring tool failure. Do not load it for planning-only or discussion-only prompts.

# Detailed Instructions

- In the in-app browser, `browser.user.openTabs()` can list a user-opened `file://` tab whose ID is not attachable through `browser.tabs.get()`. If `tabs.get` says the ID is absent, do not retry or navigate an alternate tab to the blocked file URL; leave the user tab intact and ask the user to refresh it manually.
- In the in-app browser backend, `tab.playwright.waitForLoadState({state:'networkidle'})` can fail with `playwright_wait_for_load_state does not support networkidle`. For local HTML QA, use `domcontentloaded` (or `load`) and then verify the expected DOM element instead of retrying `networkidle`.
- In in-app browser local-page QA, coordinate scrolling can fail with `Unable to translate Input.dispatchMouseEvent ... No element found at point`. Do not retry guessed coordinates; navigate to a stable element hash/ID or use a locator supported by the latest DOM snapshot, then verify the target is visible before interacting.
- When searching HTML/LaTeX text with `rg`, patterns containing literal braces or backslashes can fail as malformed regular expressions. Use `rg -F` for exact notation searches, or escape every regex metacharacter, instead of retrying the malformed pattern.
- In Chrome browser control, navigation to an Ex Ordo login page can succeed while the combined navigation-and-`domSnapshot()` call times out with a CDP `Runtime.evaluate` error. Before navigating again, inspect `browser.tabs.list()`; if the destination tab and URL are present, reacquire that tab with `browser.tabs.get(<listed id>)` and run only `domSnapshot()`.
- In PowerShell 7 on this desktop, do not use `[Runtime.InteropServices.Marshal]::GetActiveObject('Matlab.Application')` to attach to MATLAB; that method is unavailable. Reuse the existing MATLAB MCP session instead, and use its evaluation tool to set the current folder and open the script before execution.
- Before renaming a tracked directory with `git mv`, run `git status --short` and check for deleted tracked files inside it. If any are already deleted, rename the directory with PowerShell `Move-Item` instead; `git mv` can fail with `fatal: bad source` when it reaches the missing file.
- When restoring a folder through the Windows Recycle Bin Shell COM interface, do not assume `InvokeVerb('RESTORE')` succeeds because it returns without error. Inspect the item's available verbs, invoke the exact restore verb exposed by the shell, and verify that the original path reappears before reporting success.
- For any MATLAB/Simulink experiment-code change, ask the user before running the verification procedure. If the user confirms, run `main_ColumnSetup.m`, run the Simulink model on target, continue the main script after the Simulink run finishes so results are saved, and run the visualization helper script if needed.
- If the user replies `yes 1 min`, run the verification for 1 minute and stop the target manually/programmatically after 1 minute. If the user replies only `yes`, run the full configured simulation.
- Verification file locations: main script is `main_ColumnSetup.m`; main Simulink model is `model_ColumnSetup_00.slx`; visualization helper is `results_analysis\visualize_saved_results.m`; Speedgoat helper scripts are in `helpers\helper_speedgoat`; helper Simulink models are in `helpers\helper_simulink`.
- Store all temporary verification/test artifacts under repo-level `.codex`, for example `.codex\verification\<task_name>\`. This includes baseline/after MAT files, plots, and comparison metrics. If the MATLAB workflow first writes a verification MAT file under `saved_results`, copy/move the needed evidence into `.codex\verification\<task_name>\` and remove duplicate temporary verification files from the step folder.
- If the user asks to verify/vrify, treat that as explicit permission to run the physical Speedgoat workflow. It is considered safe and does not need an additional confirmation prompt.
- Output verification procedure:
  1. Work in `C:\Users\BOWN1111PC1\Documents\Mohamed\ColumnSetup_gaurav\main`.
  2. In MATLAB, run `dbstop in main_ColumnSetup at 201`, then run `main_ColumnSetup.m`.
  3. Wait until MATLAB stops at line 201 (`pause`). At this point offsets are read, `model_ColumnSetup_00` is open, and the main script is waiting for the target run.
  4. Run the physical Speedgoat target from MATLAB:
     ```matlab
     tend = 60; % use 60 for a quick verification; use the configured tend for a full run
     slbuild(model);
     tg = slrealtime;
     tg.load(model)
     tg.start('AutoImportFileLog', true, 'StopTime', tend);
     T = timer('TimerFcn', @(~,~)disp('*** Output verification target run complete. ***'), 'StartDelay', tend + 5);
     start(T); wait(T); delete(T);
     pause off
     dbcont
     pause on
     dbclear in main_ColumnSetup
     ```
  5. Confirm `savedfile_flag` exists. The saved MAT file path is in `file_name`.
  6. Run the visualization on the exact saved file:
     ```matlab
     projectFolder = 'C:\Users\BOWN1111PC1\Documents\Mohamed\ColumnSetup_gaurav\main';
     cd(projectFolder)
     outputVerificationFile = fullfile(projectFolder, file_name);
     run(fullfile(projectFolder, 'results_analysis', 'visualize_saved_results.m'))
     ```
  7. Report the saved MAT filename, duration, sample count, `fs`, `dt`, and `RMS(d_n - dm)` from the visualization output when the numerical sub can be recomputed from logged `fm`; use the logged command only for non-RTHS records without `hs.fem`.
  8. If the user asks for a full verification, use the configured `tend` instead of `60`. If the user says `yes 1 min`, use `tend = 60`.
- When comparing baseline/after physical runs for a model cleanup, save the baseline MAT/plot, after MAT/plot, and comparison metrics under `.codex\verification\<task_name>\` rather than a `test` folder inside the step folder.
- User-level MAT outputs for the step folder should live under `saved_results`: physical target runs under `saved_results\tests\...`, experimental transfer-function identification outputs under `saved_results\exp_tf\...`, and TSE specimen outputs under `saved_results\specimens\...`. Scripts that prompt the user to load one of these files should use `helpers\utils\load_saved_result_file.m` with the appropriate subfolder argument instead of scanning old local data/model/specimen folders.
- When the user asks to compare a current run with a fixed baseline, keep using that baseline until the user explicitly says to update it. Report the comparison as signal-to-signal values in one table with `Channel`, `RMS(current - baseline)`, and `Normalized change (%)` columns. Compute normalized change as `100 * RMS(current - baseline) / max(RMS(baseline), RMS(current))` for that channel. Include channels `dd`, `dc`, `vc`, `dm`, `fm`, and `am`. Do not include duration, sample count, `fs`, `dt`, or tracking-error summary tables such as `RMS(d_n - dm)` unless the user explicitly asks for them.
- Before reporting a fixed-baseline physical comparison, first ensure the current run sends the same command signal as the fixed baseline. If needed, replay the baseline `dd` through `time_history`, set `test_signal = 1`, and match the command-path gain/limit semantics for the verification run only; confirm `RMS(current dd - baseline dd)` and `RMS(current dc - baseline dc)` are approximately zero before interpreting `dm`, `fm`, or `am`.
- If a fixed-baseline comparison includes a channel that is intentionally no longer logged after a Mux cleanup, keep the channel row and report `NaN` for its metrics rather than failing or changing the fixed baseline.
- If the user says `baseline compare`, treat it as a request to run the current Simulink model on the physical Speedgoat target for 1 minute, compare the saved run against the fixed baseline, keep the baseline unchanged, and report only the signal-to-signal comparison table described above.
- MATLAB MCP can lose connection after a long Speedgoat run while the file log is importing; first reconnect with a small MATLAB query and check for the expected saved MAT file before rerunning the physical system.
- `mcp__matlab.evaluate_matlab_code` does not accept a `timeout_ms` argument. This applies to short smoke tests and long Speedgoat runs alike; never pass timeout fields to this MCP tool. For long Speedgoat runs, call it without extra timeout fields and let MATLAB block until the run/import snippet completes.
- For SLRT `tg.load(model)` in MATLAB R2020b, if it warns "Cannot connect XCP master to slave ... port 5555" or "Cannot establish XCP connection", do not start the run. In automated scripts, always wait briefly, recreate/reconnect `tg = slrealtime`, call `tg.load(model)` again, and pre-check `tg.ModelStatus` or a harmless `getparam(tg,'','<live_flag>')` before `tg.start`; an empty `list(tg.FileLog)` after the wait often means the target never started.
- For SLRT live tuning of model-workspace/global variables such as `dd_pause_enable`, use the workspace-parameter signature `setparam(tg, '', 'dd_pause_enable', value)`. If `setparam(tg, 'dd_pause_enable', value)` fails with "Invalid input arguments" or block `Value` tuning says the value is an expression containing workspace variables, retry with the empty block-path signature and confirm with `getparam(tg, '', 'dd_pause_enable')`.
- For SLRT target status checks in MATLAB R2020b, use the lowercase property `tg.status`. If `tg.Status` fails with "Unrecognized method, property, or field 'Status'", do not rerun the target; query `tg.status` and continue/import the just-finished file log.
- In `mcp__matlab.evaluate_matlab_code`, avoid relying on local helper functions defined later in the same evaluated snippet for quick metric generation, formatting helpers such as `tern`, or Simulink block inspection; MATLAB MCP can report "Unrecognized function or variable '<helper_name>'". Use inline MATLAB code or a real `.m` script instead, and pre-check any repeated helper-like logic by keeping it inline. Do not define a local function at the bottom of an evaluated snippet for `get_param` formatting or Simulink inspection; write the `try/catch` inline in the loop.
- In `mcp__matlab.evaluate_matlab_code`, when running any script that starts with `clear`, do not define post-run variables before `run(...)`; the script can erase them and cause "Unrecognized function or variable" or accidentally resolve the erased name as a built-in function after it returns. Define output paths, counters, screenshot filenames, and editor-document paths after `run(...)`, or use literal values in the post-run commands.
- Before an MCP-driven noninteractive run calls `loadFemDefinition`, provide an explicit existing `hs.fem_file`. An empty path opens the numeric FEM chooser, and the next MATLAB MCP evaluation can be consumed as the chooser input before the run unwinds with an index error; after that error returns, pin the intended FEM file and restart from initialization.
- If `mcp__matlab.check_matlab_code` fails with `failed to parse checkcode output`, do not retry that wrapper. Run MATLAB's native `checkcode(scriptPath, '-struct')` through `mcp__matlab.evaluate_matlab_code` and print the returned line/message fields.
- For Simulink block inspection in MATLAB R2020b, `find_system(model, ...)` may include the root diagram; do not call block-only parameters such as `MaskType` on the root. Skip the root or wrap per-block `get_param` calls. For subsystem `Lines`, use fields such as `SrcBlock`, `SrcPort`, `DstBlock`, and `DstPort`; do not assume newer `SrcBlockHandle`/`DstBlockHandle` fields exist.
- MATLAB MCP workspace rule: variables created inside an `mcp__matlab.evaluate_matlab_code` snippet are not enough for this Simulink workflow. `model_ColumnSetup_00.slx` block/configuration parameter evaluation resolves many symbols from the MATLAB base workspace, including `model`, `dt`, `tend`, chirp settings, gains, channel structs, `time_history`, and `ini_v`. Before any compile/build/update-diagram action such as `slbuild`, `set_param(model,'SimulationCommand','update')`, `Simulink.findVars(model)`, or `tg.load(model)`, initialize the base workspace first.
- Preferred initialization before build/compile work: run `main_ColumnSetup.m` up to its pause/breakpoint so the real script defines the base workspace, then build/load from that same MATLAB session. For no-target edit verification, use `dbstop in main_ColumnSetup at <pause line>`, run the script, wait at the pause, then perform `slbuild` or model checks.
- For no-target `set_param(model,'SimulationCommand','update')` checks using a manual base-workspace setup, also run `addpath(genpath('helpers'))` first. If update fails in the BLWN block with `Undefined function 'blwnStdFromExceedance'`, add the helper path and rerun the same update check rather than changing the model.
- If you intentionally build/check without running `main_ColumnSetup.m`, explicitly `assignin('base', ...)` every setup variable the model expects, then run a preflight check before the first build. Minimum preflight:
  ```matlab
  req = {'model','dt','tend','f_init','f_final','tend_chirp','f1','tend_BLWN','time_history','tend_time_history','ini_v','ch','command_channel_selector','sat_limit'};
  missing = req(~cellfun(@(v) evalin('base', sprintf('exist(''%s'',''var'')', v)), req));
  assert(isempty(missing), ['Missing base workspace variables: ' strjoin(missing, ', ')])
  ```
- In `mcp__matlab.evaluate_matlab_code`, when using the base-workspace preflight above, keep the `cellfun(@(v) evalin('base', ...), req)` expression exactly in that form. Do not test local snippet variables with `exist(v,'var')`, and do not add an extra negation such as `~cellfun(...) ~= 1`; both patterns can falsely report every setup symbol missing before `set_param(model,'SimulationCommand','update')`.
- Do not call `slbuild` repeatedly to discover one missing base variable at a time. If a build/update fails with "Unrecognized function or variable" for a setup symbol, stop and initialize/check the full base workspace before retrying.
- For SLRT `slbuild(model)` in an MCP-driven verification, if the build fails with `Object 'T' has been deleted and cannot be used` after a previous timer-based run/wait snippet, clear stale timer handles before retrying: `clear T; delete(timerfindall);`. Pre-check with `timerfindall` and do not reuse a deleted variable named `T`.
- For SLRT file-log import in MATLAB R2020b, do not assume `list(tg.FileLog)` has an `Application` table variable. If `fileLogRuns.Application` fails with `Unrecognized table variable name 'Application'`, inspect `fileLogRuns.Properties.VariableNames` and, for a just-finished single verification run, import the latest row directly with `tg.FileLog.import(fileLogRuns(end, :))`.
- For MATLAB Function blocks in Simulink models, fixed workspace values such as `dt` can be used directly for simpler diagrams, but declare them as MATLAB Function block `Parameter` data so update/codegen resolves them reliably; use an explicit Constant input only if inference still fails.
- For R2020b MATLAB Function blocks edited through `Stateflow.EMChart.Script`, if `set_param(model,'SimulationCommand','update')` reports only `Errors occurred during parsing of MATLAB function` with no line detail, do not keep retrying the same chart script. First export/print the chart script with line numbers, then simplify unsupported chart-parser constructs such as dynamic-size persistent initialization from local variables, `~` discard outputs, or matrix functions not supported by MATLAB Function codegen; retry only after replacing them with fixed literal sizes or simpler built-in-supported code.
- Running `control_and_HS\b_system_id\sys_id.m` writes experimental transfer-function outputs directly under `saved_results\exp_tf`. If a task only changes or verifies a standalone fit, preserve or restore unrelated experimental transfer-function `.mat` files so verification does not leave unrelated physical-ID output churn.
- For noninteractive MATLAB MCP calculations using `control_and_HS\b_system_id` data, do not call `trim_recording_time_window` unless you intend to control its figure; it opens a `Select recording trim window` UI and blocks `evaluate_matlab_code` until the window continues or closes. Pre-check whether the calculation can use saved vectors/models directly; if the trim UI is opened by mistake, close that figure/window and rerun without the helper or with an explicit scripted trim window.
- For `control_and_HS\b_system_id\sys_id.m`, low-frequency weighted parametric identification can run for a long time if `MultiStart('MaxTime', Inf)` is left unlimited. When adding or increasing `frequency_weight_exponent`, keep a finite `parametric_identification_config.max_time` and check that MATLAB is consuming CPU rather than blocked on the trim UI before rerunning.
- Dashboard switches that must be usable when opening `model_ColumnSetup_00.slx` directly should bind to a model-workspace variable, not only a base-workspace variable. For example, store `zero_measurements_enable` in the model workspace, set the controlled Constant block `Value` to `zero_measurements_enable`, and set the dashboard binding `VarName='zero_measurements_enable'`, `WksType='model'`.
- For SLRT dashboard switches that must toggle while the target is running, avoid the model-parameter `PageSwitching` storage class for the live flag. Store the flag as a model-workspace `Simulink.Parameter` with `CoderInfo.StorageClass = 'ExportedGlobal'` so toggling it updates a direct global scalar instead of causing a calibration page switch.
- For Simulink Scope style edits in MATLAB R2020b, if `set_param(scope,'ScopeSpecificationString',...)` shows the desired colors/line styles in memory but `save_system` drops them after `bdclose/load_system`, do not keep retrying `save_system`. Close the model/scope windows, update the persisted `ScopeSpecificationString` inside the `.slx` XML for the specific Scope blocks, then reload the model and verify `FigureColor`, `AxesColor`, `AxesTickColor`, `ColorOrder`, and `LinePropertiesCache` from `get_param`.
- For Simulink annotation edits through MATLAB MCP, if `Simulink.Annotation(model, 'Text', ..., 'Position', ...)` fails with `A new annotation named ... cannot be added`, do not retry that constructor form. Use the handle form `a = Simulink.Annotation(model, text); a.Position = [...]` or set annotation properties after construction, then save and verify with `find_system(..., 'Type', 'annotation')`.
- For Simulink saves through MATLAB MCP, if `save_system(model)` fails with "file has changed on disk since it was loaded", do not overwrite immediately. Close the stale in-memory model with `close_system(model, 0)`, reload the current `.slx`, reapply the intended small edit, then save and verify by closing/reloading once more.
- For Simulink rewiring through MATLAB MCP, if `add_line` fails with "The destination port already has a line connection", close/reload any unsaved partial attempt if needed, then delete the line attached to the destination port handle before retrying the connection. Do not rely only on deleting the old source line because branched lines can leave the destination occupied.
- For MATLAB R2020b plotting, if `fill(..., '#RRGGBB', ...)` fails with "Invalid color or line style", do not retry with hex color strings for patch/fill objects. Use RGB triplets such as `[0 0.486 0.659]` for `fill`/`patch`, while hex strings can still be used for ordinary `plot` lines if already working.
- For long offline estimator sweeps in `mcp__matlab.evaluate_matlab_code`, if a per-sample loop with eig/SVD over many window sizes times out near the MCP tool limit, do not rerun the same brute-force snippet. Pre-check sample count and window count, then reduce to representative windows/indices or vectorize the moment calculations before retrying.
- If a command/tool fails in a way that could recur, update this markdown file before retrying more than once or before giving the final answer. The update must be a concrete reusable rule: name the failing command/context, the trigger/error symptom, the correct next action, and any quick pre-check. If a related rule already exists but did not prevent the mistake, strengthen that rule instead of adding a vague duplicate.
- For GitHub CLI work, pre-check `gh --version` or `Get-Command gh` before using `gh auth status`; if PowerShell reports `gh` is not recognized after installation, refresh the current process PATH from Machine/User environment variables or call `C:\Program Files\GitHub CLI\gh.exe` directly before retrying CLI commands.
- For SAP2000 OAPI automation on this desktop, do not instantiate the registered COM helper with `New-Object -ComObject SAP2000v1.Helper` from PowerShell 7 (`pwsh`); it fails COM activation with `0x800080A5`. Use a small compiled C# console wrapper with a direct assembly reference to `C:\Program Files\Computers and Structures\SAP2000 26\CSiAPIv1.dll`; PowerShell's method binder fails the `cOAPI.ApplicationStart` overloads, and `Add-Type` fails the v26 API's `netstandard, Version=2.0.0.0` reference. This machine has only the .NET 8 runtime and no `dotnet` SDK, so compile the wrapper with the installed Roslyn `csc.exe`, `/nostdlib+`, and managed references from the .NET 8 shared runtime; filter candidate runtime DLLs through `[Reflection.AssemblyName]::GetAssemblyName(...)` first because native DLLs such as `coreclr.dll` cause CS0009. Run the resulting assembly as `dotnet <wrapper.exe>` with a matching `.runtimeconfig.json`; launching the `.exe` directly invokes the .NET Framework host and fails to load `System.Private.CoreLib`. Store sources/binaries under repo-level `.codex`. When launching Windows PowerShell from an outer PowerShell command, use `-EncodedCommand` (UTF-16LE base64) for snippets containing `$` variables; a double-quoted `-Command` lets the outer shell expand those variables and causes parser errors.
- When attaching the C# SAP2000 wrapper to an already open API-launched instance, do not assume `cHelper.GetObject(...)` throws on failure; it can return `null` and cause a later `NullReferenceException`. Pre-check the returned value and use `GetObjectProcess("CSI.SAP2000.API.SapObject", <visible SAP2000 process id>)` for an unambiguous attach before starting another instance. Do not use the command-line interface token `CSiAPIv1` as the first argument; it returns `null` and can make the wrapper start a duplicate SAP2000 instance.
- In MATLAB, `System.Diagnostics.Process.MainWindowHandle` is a `System.IntPtr`; do not call `double(handle)`, which fails conversion. Use `handle.ToInt64()` and compare the resulting integer to zero when identifying the visible SAP2000 process.
- MATLAB `actxserver` can attach to SAP2000 through `SAP2000v1.Helper`, but `cPointObj.SetSpring` rejects a native MATLAB numeric vector even when both COM outputs are requested because the API declares the spring vector as `System.Double[] ByRef`. Do not retry this call from MATLAB COM. Route SAP spring mutations through a strongly typed PowerShell/C# OAPI helper and keep MATLAB responsible for calibration, copying, invoking the helper, and checking its exit status.
- In SAP2000 v26 OAPI, the final `cPointObj.SetSpring` booleans are ordered `IsLocalCSys, Replace`, not `Replace, IsLocalCSys`. For global replacement call `SetSpring(name, ref values, Objects, false, true)` and immediately verify `GetSpring(...)[4]`; reversing them adds the new R2 stiffness to the existing spring.
- In MATLAB MCP sessions, `getenv('WINDIR')` can be empty. When locating Windows PowerShell, fall back to `getenv('SystemRoot')` and then `C:\Windows`; pre-check the resulting executable path before invoking it.
- Windows PowerShell 5.1/.NET Framework does not provide `[double]::IsFinite`. Validate finite doubles with `-not [double]::IsNaN(value)` and `-not [double]::IsInfinity(value)` instead.
- In `functions.exec` for this workspace, use the declared nested `tools.shell_command(...)` for PowerShell commands; `tools.exec_command(...)` may be unavailable and fail before the command starts.
- In `functions.exec`, `tools.shell_command(...)` can return a single prefixed string (`Exit code: ...\nOutput:\n...`) rather than an object with an `output` field. Check the return type and extract text after `Output:\n` before programmatically transforming command output.
- Each `functions.exec` call uses a fresh JavaScript isolate, so variables defined in one call are unavailable in the next and will fail with `ReferenceError`. Recreate any needed values within the same call or persist serializable data explicitly with `store` and `load`.
- For repository recovery checks, `git fsck --full --no-reflogs --unreachable` can exceed the default command window on this repository. Run it once with a bounded timeout of up to 60 seconds; if it still times out, do not retry repeatedly and continue with Git history and backup recovery sources.
- `git ls-tree` does not support an `--all` option. To search paths across every ref, enumerate refs with `git for-each-ref --format='%(refname)'` and run `git ls-tree -r --name-only <ref>` for each returned ref.
- When inspecting many unreachable Git blobs with `git cat-file --batch`, do not write every hash to redirected standard input before consuming standard output; the pipe can deadlock and fail with `unable to stream <hash> to stdout`. Send one hash, flush it, and fully read that object's header and bytes before sending the next hash.
- When a PowerShell command runs from the `ColumnSetup_gaurav` repository root, address every project file as `main\...`; do not omit `main\` or prefix it with `ColumnSetup_gaurav\main\...`, because either form causes path-not-found errors. Prefer separate commands: run repository Git checks from the root, then run project-file reads from `main`, so mixed Git/read commands cannot accidentally use root-relative paths without `main\`.
- Before applying one multi-file patch after moving MATLAB scripts, read the exact headers at their destination paths. If one expected context differs, split the edit into file-specific patches so one mismatch does not reject the full patch.
- Before adding a MATLAB helper directory to a relocated script, resolve the current helper path on disk. If MATLAB warns that the directory is nonexistent and then cannot find the helper, correct the path from the filesystem inventory before rerunning the script.
- Never call `restoredefaultpath` in a MATLAB MCP session; it removes the temporary `matlab_mcp` package path and causes later tools to fail with `Undefined function 'matlab_mcp.mcpEval'`. If that error occurs, identify and close only the broken MCP-launched MATLAB process pair, keep any older user session, and let the next MATLAB tool call establish a clean MCP session. Do not start a separate unmanaged MATLAB window.
- MATLAB `lsim` requires a monotonically increasing, evenly spaced time vector. When refining an input grid, do not append a shorter final interval; compute an integer interval count with `ceil` and generate the full grid with `linspace` so it includes the endpoint with uniform spacing.
- When exporting MATLAB verification artifacts while the current folder is under `main`, resolve `.codex\verification` from the repository root, not from `main`; pre-create the destination directory before calling `exportgraphics`.
- From a MATLAB current folder of `main\control_and_HS\OSI`, use two `fileparts(pwd)` calls to resolve `main`; three resolves the repository root and makes `saved_results` paths miss the required `main` segment.
- In the SAP Windows PowerShell 5.1 helper, cast comma-separated numeric input explicitly to `[double[]]` and assign an indexed value to a scalar before arithmetic. Dividing a pipeline-produced `Object[]` directly can fail with `System.Object[] does not contain op_Division`.
- Before overwriting a generated SAP `.sdb`, ensure SAP2000 is not currently holding that target open. Have the OAPI helper open the immutable template first, then copy the template over the target, then open/edit the target; overwriting the currently open analyzed model can leave SAP in a blocking file-state dialog.
- For SAP geometry edits such as `EditPoint.ChangeCoordinates`, use an OAPI-launched SAP2000 instance (`/A`). A normally GUI-launched instance may accept OAPI reads/open calls but block on the first coordinate edit with an interactive confirmation. Pre-check the SAP process command line or start it through the API before running the geometry helper.
- For `mcp__git.git_show`, pass only a real revision such as `HEAD` or a commit SHA in `revision`; do not include display flags like `--stat` or `--oneline`, because the tool treats them as part of the revision and can fail with "Invalid revision ... cannot start with '-'". Use a shell `git show --stat --oneline HEAD` command when formatted show output is needed.
- For `gh auth login` in this Windows desktop session, do not run a hidden `gh auth login --web --clipboard` and assume it copied the device code; if the clipboard still contains unrelated text or a pasted credential, clear it and stop the hidden process. Use a visible PowerShell window for the interactive device-code flow, and let the user enter credentials/2FA in the browser.
- If `git push` hangs with no output and a suppressed-output `git credential fill` lookup also times out while `gh auth status` succeeds, bypass the stuck Git Credential Manager for that command with `git -c credential.helper= -c credential.helper="!gh auth git-credential" push <remote> <branch>`; do not keep retrying the default credential helper or print credential output.
- If an authenticated push still hangs and the process tree shows `git lfs pre-push` blocked under `git show-ref`, terminate only that stale push process tree. When the outgoing commits contain no LFS-tracked paths, retry once with `--no-verify`; if they do contain LFS paths, diagnose the LFS objects instead of skipping the hook.
- For Codex manual helper commands in this Windows desktop session, if `node C:\Users\BOWN1111PC1\.codex\skills\.system\openai-docs\scripts\fetch-codex-manual.mjs` fails because the WindowsApps Codex-packaged `node.exe` reports `Access is denied`, do not retry that same `node` shim. Pre-check `Get-Command node` and use another accessible Node runtime such as the workspace bundled Node path from `load_workspace_dependencies`, or fall back to official OpenAI docs/web lookup.
- Whenever opening an instance/session/window through MCP, close it again after finishing with it.
- In MATLAB R2025b Computer Use, `type_text` can fail with `clipboard did not contain requested text` and `set_value` on the Command Window edit can time out. Do not keep retrying Command Window injection. When MATLAB is already in the required project folder, navigate through the visible Current Folder pane, open the target script in the Editor, make that editor tab active, and run it with F5.
- For the bundled workspace Python runtime, if importing an advertised package such as SciPy fails with `ModuleNotFoundError`, inspect the returned Python packages directory for the actual module before retrying. Set `PYTHONPATH` only when that module exists there; if it does not, do not retry the same import and use an available library, MATLAB, or a dependency-free calculation instead.
- After editing a MATLAB function or test that was already loaded in a persistent MCP MATLAB session, run `clear functions; rehash` before rerunning it. If a failure report still shows old source text or an old expected identifier, refresh the function cache instead of changing the correct on-disk code again.
- Do not initialize a heterogeneous MATLAB result collection with `repmat(struct(), n, 1)` and then assign populated structs; MATLAB reports `Subscripted assignment between dissimilar structures`. Use a cell array during collection or predeclare every struct field.
- If a MATLAB MCP run reports "Too many input arguments" for a local helper function even after `clear functions; rehash` and the helper signature on disk is correct, avoid repeated retries through that local helper. Inline the small helper logic or move it to its own `.m` file, then clear the function cache before rerunning.
- For MATLAB MCP identification-parameter sweeps, do not run a full Cartesian sweep across orders, regularization, coherence, power range, phase weight, and frequency limits in one `evaluate_matlab_code` call; it can exceed the MCP timeout. First run a narrow order/regularization sweep with fixed data-selection settings, then fine-tune only around the best stable candidates.
- When editing an embedded Simulink MATLAB Function with several overlapping text substitutions, replace the complete dependent code block (or assign the complete chart script) before replacing individual tokens. Save, reload, and print the chart script to catch undefined intermediate names before compiling.
- If the SAP SI helper fails coordinate verification after `ChangeCoordinates`, print the joint name plus expected and actual global Z values before changing tolerances or retrying. Close any API-launched SAP process left by the failed helper, then diagnose whether the discrepancy is unit conversion, rounding, or model connectivity.
- In PowerShell format expressions used for SAP object names, parenthesize arithmetic arguments, for example `-f $level, ($bay-1)`. Without parentheses, PowerShell can subtract from the formatted string and then fail converting a joint name to `System.Int32`.
- When searching SAP text exports named `*.$2k` from PowerShell, quote the path with single quotes or use `-LiteralPath`; an unquoted `$2k` suffix is expanded as a PowerShell variable and `rg` reports a truncated path such as `template.` not found. Pre-check with `Get-ChildItem ... -Filter '*.$2k'` if unsure.
- When rebuilding the SAP frame template in N-m units, do not recreate the AISC shapes with `SetISection` if MATLAB/SAP stiffness matching depends on the stored section properties. SAP recalculates slightly different inertias from rounded dimensions; use `PropFrame.SetGeneral` with the exact SI area and inertia values and verify them with `GetSectProps` before rerunning the comparison.
- If no-target model update fails because `speedgoatlib_IO112`, `speedgoatlib_IO113`, or `slrealtimeloglib` is unavailable, pre-check `exist('slrealtime','file')` and do not retry update/build in that MATLAB installation. Record the missing-library blocks, verify embedded chart source and signal labels statically, and report physical/compile verification as blocked by the missing Simulink Real-Time/Speedgoat installation.
- In MATLAB R2025b, after `save_system(..., 'ExportToVersion', 'R2020b')` exports `model_ColumnSetup_00` to a temporary filename, Simulink can change the model workspace source to `<temporary>_saveas.m`; reloading that exported model in the same R2025b install can crash with an access violation. Prefer exporting once to the final filename. If the temporary export already exists, do not reload it; rename the generated `*_saveas.m` to match the final model and patch `simulink/blockdiagram.xml` `WSSourceFileName` inside the `.slx`, then verify the XML reference directly.
- In MATLAB R2025b, `matlab.desktop.editor.closeAll` may be unavailable. To close files opened through MCP, obtain documents with `matlab.desktop.editor.getAll` and close each document through its supported document method instead of retrying `closeAll`.
- In MATLAB R2025b MCP sessions, reading a `matlab.desktop.editor.Document.Text` property can hang when the editor buffer's file has been deleted from disk. Check `isfile(doc.Filename)` before touching `doc.Text`; skip stale deleted buffers rather than trying to recover their text through MCP.
- In MATLAB R2025b on Windows, overwriting an existing `-v7.3` MAT file can intermittently fail with `Unable to write file ... Invalid argument` even when an exclusive read/write pre-check shows no external lock. Do not discard the existing artifact or repeat the same in-place save. Save the same top-level variable to a temporary MAT file in the destination directory, then replace the destination with `movefile(temp, final, 'f')`.
- In MATLAB R2020b MCP audit snippets, avoid `erase(stringPath, charPath)` with mixed string/char inputs; it can fail with "Text to replace must be a text or pattern array." Use `strrep(char(path), char(prefix), '')` for display-only path trimming. For Simulink blocks with newline characters in their names, find them with `find_system(..., 'RegExp','on','Name',...)` before constructing exact paths.
- Before applying a multi-file patch across MATLAB/FEM utilities, read the exact current function headers and unit-comment context for every target file; if any file differs from the expected context, use file-specific patches so one mismatch does not reject the entire change.
- On Windows, never pass wildcard path segments such as `*.m` or `*.md` to `rg`; PowerShell does not expand them for `rg` and Windows reports error 123. Before execution, inspect every `rg` path argument for `*`. Pass the containing directories as path arguments and move each wildcard into `-g '*.m'`, `-g '*.md'`, or the required extension instead.
- MATLAB `allmargin` can return `PhaseMargin` as either a row or column vector. Before appending a fallback value for `min`, reshape it with `margins.PhaseMargin(:)`; `[margins.PhaseMargin; Inf]` can fail with `Dimensions of arrays being concatenated are not consistent`.
- In MATLAB R2025b, `tfestOptions('EnforceStability', true)` supports `SearchOptions.MaxIterations`, but this install's search options do not expose `FunctionTolerance`. Do not set `opt.SearchOptions.FunctionTolerance`; inspect `opt.SearchOptions` before adding solver-option fields.
- For `fmincon` PID tuning with log-transformed gains, give the log variables broad finite numerical bounds and return finite values from nonlinear constraints. An unconstrained log search can overflow `exp(x)` and make `pid` reject nonfinite gains, while passing an infinite satisfied margin directly to `fmincon` causes `Nonlinear constraint function returned Inf`.
- Inside a MATLAB nested function, predeclare any variable assigned by `evalc`. Otherwise the nested function's static workspace rejects `evalc('info = ...')` with `Attempt to add "info" to a static workspace`.
- For MATLAB/Simulink model or experiment-code changes in this repo, physical Speedgoat target runs are generally permitted and recommended for verification; do not ask for extra confirmation before a target run unless the prompt is discussion-only or the requested operation is unusual/destructive.
- Saved test results can retain absolute paths from the older `BOWN1111PC1` workspace. If loading a path stored in a result struct fails, resolve its filename under this workspace's corresponding `saved_results` subfolder before retrying; do not treat the stale absolute path as a missing experiment artifact.
- When evaluating a saved phase-lead design with the vHS optimizer helpers, set `phase_lead_section_count` and `notch_section_count` to match the saved design's `section_count` and `notch_sections` before calling `evaluate`. Otherwise `normalizePhaseLeadConfig` rejects the design instead of producing comparable J4/NCF metrics.
- Legacy saved phase-lead structs may omit `notch_sections`. When reading design metadata, treat a missing field as zero notch sections before selecting the matching optimizer configuration.
- `optimize_vHS_phase_lead_robust` returns its selected design under its documented result/report fields rather than a generic `best` field. After an optimizer run, inspect `fieldnames(result)` before extracting metrics instead of assuming an internal search-state field is returned.
- SLRT `slbuild` from `matlab -batch` fails with `'model_ColumnSetup_00.bat' is not recognized` and "Code generation information file does not exist" when the user-level env var `NoDefaultCurrentDirectoryInExePath=1` is inherited (cmd stops resolving the generated bat in the build cwd). Launch MATLAB with the variable removed from the launching shell (PowerShell: `Remove-Item Env:\NoDefaultCurrentDirectoryInExePath` before `& matlab ...`); do not change the user/machine env var itself.
- After an SLRT XCP connect warning ("Cannot connect XCP master to slave ... port 5555"), `isLoaded(tg)` can report true while the app is NOT usable and `setparam` fails with "No application is loaded". Verify a load with a harmless `getparam(tg, '', 'dd_pause_enable')` in a retry loop; recreate/reconnect `tg` between attempts, and fall back to `tg.reboot` (wait ~75 s) if the target is stuck in TARGET_ERROR.
- When promoting an OSI research configuration into `prepare_gpt5_6_runtime`, preserve every field used by the fixed-size parameter packer even if the research replay does not consume it directly. In particular, if packing fails with `Unrecognized field name "nominal_curve"`, derive and store the per-frequency chordal curve before its scalar minimum so the existing `gptbins` shape and `.slx` interface remain unchanged.
- When auditing embedded saved-result dependencies, do not call `fieldnames` on every dependency blindly; array dependencies such as the embedded earthquake time history are numeric. Check `isstruct` first and report `size`/`class` for non-struct dependencies.
- After calling `plot_test_result`, do not assume validation tables are nested under a field named `hs_validation` in `plots.saved_result`. Inspect `fieldnames(plots.saved_result)` or use the documented returned fields before asserting; the analysis can complete successfully and then a stale field-name assertion can leave its figures open.
- For live TET on the R2020b Speedgoat target, poll `tg.ModelStatus.TETInfo` (TETMin/TETMax/TETAvg/TETMaxTime) every couple of seconds - no instrumentation needed, works while running. Do NOT use `startProfiler` for TET on a near-budget model: its overhead can itself trigger the CPU overload, and its trace parsing can fail ("Failed to open file containing Profiler start time"). `mod(round(TETMaxTime*2048), 256)` identifies which OSI pipeline phase owned the worst tick.
- After `tg.start('AutoImportFileLog', true, ...)` ends, the auto importer races any manual `list(tg.FileLog)` poll: it can consume the run (leaving the target list empty forever) and drop `logsout` into the base workspace at any moment. Poll BOTH `exist('logsout','var')` in base and `list(tg.FileLog)` in the wait loop before declaring the file log missing.
- A CPU overload stops the app and leaves `tg.TargetStatus.State = TARGET_ERROR` with the message in `tg.ModelStatus.Error` (e.g. `Overload limit (0) exceeded in 0.000488281s (tid=0)`); read it there before reloading, because reloading clears it.
- Speedgoat FILE LOGGING on this setup records only when the run is started with `tg.start('AutoImportFileLog', true, ...)` FROM A DESKTOP MATLAB SESSION (MATLAB Connector running). In `matlab -batch` (no Connector) the app produces NO `logdata/run_N` at all - `list(tg.FileLog)` stays empty and the stop emits `Folder .../logdata/run_1 not found`; a target reboot does not help, and starting without `AutoImportFileLog` records nothing in ANY session type. For scripted target runs that need the file log, launch MATLAB with `-nosplash -minimize -logfile <log> -r "<script>; exit"` instead of `-batch`, keep `AutoImportFileLog=true`, and poll BOTH base-workspace `logsout` and `list(tg.FileLog)` after the stop (the auto importer can deliver either way).
