@renanlido/tia-openness-mcp 1.12.3 → 1.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +2 -0
  2. package/dist/index.js +149 -57
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -166,6 +166,8 @@ is covered by relation tests and `test/compare-wiring.test.ts`, not those histor
166
166
  | `tia_ob_create` | `POST /plcs/{plc}/obs` | M-off — an OB by `eventClass` (one of 15; `400 invalid_event_class` lists them) with an optional `number` (`400 invalid_ob_number` when not permitted for the class, `409 ob_number_in_use`, `409 ob_number_exhausted`); a singleton class (Status, Update, Profile, ...) holds ONE OB: `409 ob_singleton_exists`. Put the logic in afterwards with `tia_source_put` or `tia_import_xml`. |
167
167
  | `tia_block_group_delete` | `DELETE /plcs/{plc}/blockgroups/{group}?recursive=true` | M-off — `group` is a user group name or a `/` path such as `Motors/Conveyor`; a group that holds blocks or subgroups is `409 group_not_empty` (`details.blocks`, `details.groups`) unless `recursive:true`. |
168
168
  | `tia_export_type` | `GET /plcs/{plc}/types/{type}/xml` | R, job — one UDT as inline SimaticML with `sha256`, `normalizedSha256`, `bytes` and `contentHash`; it never compiles: an inconsistent type is `409 inconsistent` (run `tia_compile`), an unknown one `404 not_found`. |
169
+ | `tia_export_sd` | `GET /plcs/{plc}/blocks/{block}/sd`, `GET /plcs/{plc}/types/{type}/sd` | R, job — one block (OB, FB, FC, DB) or type as inline SIMATIC SD text: `s7dcl`, `s7res` (null when TIA wrote none), byte counts, `state`, `messages` and the `contentHash` that `tia_export_block` / `tia_export_type` return, read before and after the export so it always belongs to the text (`null` with `contentHashError` when the object changed during the export or the block is not consistent); it never compiles. `409 sd_export_failed` carries TIA's messages. TIA re-quotes some identifiers on export: compare ignoring quotes. |
170
+ | `tia_import_sd` | `POST /plcs/{plc}/sd/import` | M-off, job — creates or replaces ONE block or type from SD text (the only way to create one from SD text; VCI updates mapped objects only). Run `dryRun:true` first; `expectedContentHash` guards an existing object. An existing OB of ANY event class is `409 sd_existing_ob_unsupported` (TIA gives every OB imported from SD a new number: a ProgramCycle OB 123 came back as OB 1): change it with `tia_export_block` + `tia_import_xml`; a NEW OB can be created from SD. The DB flags an import resets (`IsOnlyStoredInLoadMemory`, `IsWriteProtectedInAS`, `DBAccessibleFromOPCUA`) are reported in `changeImpact.dbAttributeChanges`, never restored automatically: `tia_block_set_attribute` restores `IsOnlyStoredInLoadMemory` and `IsWriteProtectedInAS`; a person sets `DBAccessibleFromOPCUA` again in TIA Portal (the block's properties) when that route refuses it (V21 2100.0.121.1: its `400` `details.writable` omits it on an optimized global DB); then compile. Comments only through `s7res`; quote YAML values with `:` or `#`; FBD `wire#` consumer rung before its producer. A refused text is `400 sd_import_failed` (`details.messages`, `details.changed`). |
169
171
  | `tia_type_source` | `GET /plcs/{plc}/types/{type}/source` | R, job — one UDT as SCL source with the `sha256` of the code and `bytes`; its `contentHash` is that of the SimaticML export of the same type, so what you read as SCL can guard a `tia_source_put` TYPE source or a `tia_types_import`; same `inconsistent` / `not_found` refusals. |
170
172
  | `tia_crossrefs` | `GET /plcs/{plc}/crossrefs?target=&kind=&filter=&limit=&cursor=` | R, job — cross-references of ONE object (`target`; `kind` plc, block, type, tag, constant, tagtable or blockgroup, auto-detected when omitted: several matches `409 ambiguous_target`, none `404 not_found`, `blockgroup` never auto-detected) or, without `target`, of the whole PLC (minutes on a large project: scope the read). `filter` is AllObjects (default), ObjectsWithReferences, ObjectsWithoutReferences or UnusedObjects; UnusedObjects are candidates, not proof (OBs and objects used only from outside the PLC show as unreferenced), so recommend and let the human decide. Paged; each page re-reads the PLC, so paging bounds the size, not the time. Claim that nothing uses an object only when `coverage.complete` is true on every page and every page was read. `409 crossrefs_unavailable` when the target or the TIA/CPU version offers none. |
171
173
 
package/dist/index.js CHANGED
@@ -28958,10 +28958,11 @@ async function tiaFetch(path, init = {}, opts = {}) {
28958
28958
  if (baseProblem) throw new TiaApiError(baseProblem, { kind: "invalid_api_base" });
28959
28959
  const url2 = `${BASE}${path}`;
28960
28960
  const timeout = opts.timeoutMs ?? TIMEOUT_MS;
28961
- const headers = {
28962
- Accept: "application/json",
28963
- ...init.headers
28964
- };
28961
+ const headers = new Headers(init.headers);
28962
+ if (!headers.has("Accept")) headers.set("Accept", "application/json");
28963
+ if (init.body !== void 0 && init.body !== null && !headers.has("Content-Type")) {
28964
+ headers.set("Content-Type", "application/json; charset=utf-8");
28965
+ }
28965
28966
  const dispatcher = timeout > FETCH_HEADERS_TIMEOUT_MS ? unboundedDispatcher() : void 0;
28966
28967
  const controller = new AbortController();
28967
28968
  const timer = setTimeout(() => controller.abort(), timeout);
@@ -29226,7 +29227,7 @@ var GATES_GUARDS = '# Gates vs guards\n\n## GATES vs GUARDS\n\n- **GATES (human-
29226
29227
  var GUI_GATES = '# GUI gates \u2014 expected human interaction points\n\n## Human interaction points (GUI gates) \u2014 EXPECTED, not an error\n\nExpected handoffs include trust, fresh-CPU setup and firmware-change recovery.\nOn the validated 1214C V4.4, no direct setter for PUT/GET, license selection or HR mapping was verified;\na **prepared station master copy inherits all three**. Do not blindly retry a missing setting: give the human the exact steps.\n\n| # | Signal you\'ll see | Why it\'s expected | Tell the human (exact GUI steps) |\n|---|---|---|---|\n| **G1 trust** | `EngineeringSecurityException` or a failed start with `details.cause:"trust"` \u2192 `requires_human_action` / `trust_dialog`. Neither `running` nor the 20-minute client timeout (`STARTING_UNCONFIRMED`) proves G1 or success. | First attach may prompt **per serve process**. | Human on the **serve host**: click **"Yes to all"** only on a visible trust dialog. While a job runs, poll `tia_job_status`; do not queue calls. A timeout does not cancel it: inspect the host, wait for completion before status/retry. After explicit G1 handoff, retry with `resumeToken`. For `TRUST_DIALOG_DENIED_OR_EXPIRED`, inspect `closedPids`/`stillRunningPids`/`unknownPids`: close only verified remaining TIA started by serve **with no open project**, then retry with a human ready. |\n| **OPC UA license** | `tia_compile` **ERROR**: *"The selected OPC UA license is not sufficient\u2026"* | No verified direct setter on this 1214C; a fresh project or firmware change can leave it unset | CPU \u2192 **Properties \u2192 General \u2192 Runtime licenses \u2192 OPC UA** \u2192 required **"SIMATIC OPC UA S7-1200 Basic"**; purchased \u2192 the license the owner declares for this CPU. Recompile. |\n| **OPC UA interface** | OPC UA client connects but the DB nodes aren\'t there (`ns=4` empty / no `ServerInterfaces`) | The validated **S7-1200** requires a configured server interface to expose DBs | CPU \u2192 **OPC UA communication \u2192 Server interfaces \u2192 Add new server interface** \u2192 type **Interface** \u2192 drop the **`HR` array** (`ModbusData.HR`), not the DB or individual elements. Recompile. |\n| **PUT/GET** | S7 client connects on port 102 but reads return access-denied | No verified direct setter on this 1214C | CPU \u2192 **Properties \u2192 Protection & Security \u2192 Connection mechanisms** \u2192 check **"Permit access with PUT/GET communication from remote partner"**. Compile + human-gated download (`hardware:true`). |\n| **FW-change reset** | After `tia_device_change_version`: OPC UA server off, the license error on compile, blocks `isConsistent:false` | `DeviceItem.ChangeType` **resets GUI-gated comm settings** (server activation + license); the interface & PUT/GET survive | `tia_project_archive` **before** the FW change. After: re-set `OpcUaServer:true` via `tia_obj_set_attributes` (scriptable), re-select the license (row above), recompile. |\n\n**Bounded connect:** `connect_incomplete` / `CONNECT_UNCONFIRMED` (`serve_host_inspection`)\nnames the last phase, not G1 or success. No cancellation or TIA kill: don\'t repeat or queue work.\nHuman: inspect the host and answer pending Siemens dialogs. If none is pending and unresponsive,\nsave stdout (CLI) or `%APPDATA%\\TIAOpenness\\startup.log` (tray, overwritten on launch),\nthen restart the **process** (tray: Exit/relaunch, not API Stop/Start).\nTIA may remain running: inspect it and verify project state before reconnecting.\nA finished MCP job carrying this handoff isn\'t connection proof.\n\n**Prepared station:** `tia_library_mastercopy_create {device}`, then `tia_device_from_mastercopy {masterCopy}`\nclones all three settings and HR mappings. Not an existing-CPU setter or license grant.\nCertificates are not copied: on the NEW "OPC UA" item, `OpcUaServer:false` then `true` regenerated one; compile afterwards.\nGUI type **Interface** maps to `SimaticInterface` (Export, no Import).\nThe separate `ServerInterface.Import` did not reproduce its HR mappings.\n\n**1214C/V21 bench, 2026-10-26:** `HR[0..2]` IDs in `ns=4`: HR array \u2192 `13,14,15`;\nindividual elements \u2192 `12,23,34`; whole DB \u2192 `14,15,16`.\nSelection/order affects IDs; probe after construction/import.\n';
29227
29228
  var GOTCHAS = '# Hard-won gotchas (runtime-validated)\n\n## Hard-won gotchas\n\n1. **Always compile before deploy.** `tia_compile` aggregates **hardware + software**; a\n **clean** compile (`errors:0`) is the precondition for download and for S7 connections.\n `tia_download` compiles too and leaves the project modified (`projectModified` in plan/result):\n save (`tia_project_save`) before switching projects; Openness does not say what changed.\n First download over another project\'s or TIA version\'s program: plan\n `allowUpgradeTargetDevice:true`, or a refusal may leave the CPU stopped (the plan cannot predict it).\n2. **One serial worker:** never concurrent `tia_*` calls; a hung operation may need a serve restart.\n3. **FB edits:** software-scope `tia_compile`; export regenerated DBs (`blockChanges`).\n Still inconsistent: `tia_block_delete` + `tia_instancedb_create`, recompile.\n **Global DB source put** re-creates it: `IsOnlyStoredInLoadMemory` resets\n (no source support; pragma ignored); nested starts need `BEGIN`.\n UDT put/`tia_types_import` did not reset DB values. Save XML/text/flags.\n Inspect `changeImpact.dbAttributeChanges`/`readGaps` (unknown; `trackChanges:false` opts out).\n Restore flag=true: `tia_block_set_attribute`, compile; starts: saved XML/text, not attributes.\n **N warnings then 0:** hardware compile produced OPC UA guest/unsecured + missing\n protection-level warnings; next skipped hardware. Check `messages[]` "Hardware configuration".\n4. **Firmware rule: project FW \u2264 device FW.** Bump the project FW **in-place** with\n `tia_device_change_version` (`DeviceItem.ChangeType`), which preserves the **program** \u2014 never\n set the project higher than the physical CPU. **\u26A0\uFE0F It RESETS GUI-gated comm settings** (the\n **OPC UA server activation** + **runtime-license**; the server interface and PUT/GET survive):\n **archive first** (`tia_project_archive`) on a CPU with hand-configured OPC UA, recompile after\n (it marks blocks inconsistent), and re-verify. Same-version `ChangeType` is rejected.\n5. **Use a NON-optimized DB** for Modbus (`MB_HOLD_REG`) and S7 (absolute addressing); OPC UA\n works with optimized or not.\n6. **Order numbers use `/V<fw>`, not `:V<fw>`** (guard Gd5).\n7. **A station upload (`tia_upload`) ADDS a new station to the open project \u2014 back up into a\n dedicated EMPTY project.** Bench (S7-1200 1214C, 2026-09-26): 0 \u2192 1 device in ~75 s, twice,\n with the CPU in RUN throughout. Protect the working project FIRST: `tia_project_create` closes\n it and is refused (`409 unsaved_changes`) while it has unsaved changes, so `tia_project_save` +\n `tia_project_archive` first (never `discardUnsavedChanges` to get past the refusal), with the\n archive `name` WITH the `.zap21` extension (absent or extension-less fails).\n **A V17 program does not upload into V21 (2026-10-31):** use the TIA version the program was\n made with. `upload_incompatible_version` is definite: check versions and `stationAdded` in\n `details`; a partial station is not a backup. Approval stays single-use.\n8. **One wrong know-how password can lock a block for the session.** Observed on the bench\n (2026-10-12): after one rejected unprotect (`tia_block_protect {protect:false}`), TIA refused\n the CORRECT password of that block for the rest of the session (cause not confirmed \u2014 possibly\n brute-force protection). Never retry with a guess \u2014 ask the human for the password (G6); if a\n password the human confirms is refused, stop and hand off instead of retrying.\n9. **`unsaved_changes` and `binding_conflict` are refusals, not faults: nothing was changed.**\n `tia_connect`, `tia_project_close`, `tia_disconnect` and `tia_project_create` answer\n `409 unsaved_changes` when the call would close a project with unsaved changes (the error lists\n each one). ASK the human; the recommended answer is to repeat the same call with\n `saveUnsavedChanges:true`. Pass `discardUnsavedChanges:true` (data loss) ONLY when the human\n explicitly decides to throw the work away, never to make the error go away (the client then asks\n the human to confirm in its own dialog; `declined_by_human` = nothing was sent, stop).\n `409 binding_conflict` means the project this session is bound to is no longer the one open in\n the bound TIA (closed, replaced or Save As done by hand; `tia_status` shows `boundProjectPath`\n and `bindingDrift`): ask the human which project is intended, then `tia_connect` with the bound\n path (back to it) or the open one (adopt it) \u2014 do not repeat the refused call first.\n10. **`503 audit_unavailable`: the serve could not write its audit log, so it refused the call BEFORE\n running (nothing reached the PLC).** Have the human fix the disk or permissions, then re-plan.\n An `auditWarning` in a response = the call ran but was not fully recorded: report it.\n\n## Prerequisites (environment)\n\n- The **`tia` serve must be running** (default `http://localhost:5000`, e.g.\n `TIAOpenness.exe serve 5000`). The MCP is a pure HTTP client; point it at the serve host via\n `TIA_API_BASE` if it runs elsewhere.\n- The Windows user must belong to the **"Siemens TIA Openness"** local group.\n- A first connection per serve process may show a trust dialog; a human confirms it on the serve host. A slow start or timeout alone is not G1 evidence.\n';
29228
29229
  var PIPELINE = '# The build pipeline (spec \u2192 verified project)\n\nTIA version preflight: `tia_guide {"topic":"recipes"}`, \'TIA version evidence and SimaticML\', before authoring.\n\n| # | Stage | Tool(s) | Class | What it does |\n|---|---|---|---|---|\n| 0 | Validate the spec | `tia_spec_validate` | R (pure) | Partial shape checks + the cross-field rules the tool implements: unique names, IP inside the subnet CIDR, Gd5 order-number format, no STL/GRAPH on S7-1200, the G5 safety rule, at most 8 SMs on an S7-1200. It does NOT run the JSON Schema or per-model module limits; the `spec-validate` skill covers both. Needs no serve. |\n| 1 | Plan | `tia_spec_plan` | R (pure) | Turns a VALID spec into the ordered list of M-off operations. Nothing mutates. |\n| 2 | Scaffold | `tia_spec_apply` (or the M-off tools manually) | M-off | Creates part of the project content in dependency order (scope below). Stops at every gate. |\n| 3 | Verify | `tia_compile` | M-off | THE offline verifier: aggregates hardware + software. Gd8: only ERRORs block. `errors:0` is the Gd9 precondition for any deploy. |\n| 4 | Handoff / deploy | `tia_download` | GATE G3 | `dryRun:true` verifies compile, connection and software fingerprint \u2192 `planHash` \u2192 HUMAN approval \u2192 `approved:true` + SAME single-use `planHash`. Serve re-checks software (`plan_stale` if changed). Approval binds connection/options and covered software, NOT hardware: humans must confirm hardware has not changed since that dryRun; changed hardware needs a NEW plan and approval, never the old token. Fingerprint covers user blocks, UDTs and tag tables only; exclusions and `source:"dates"` fallback: `tia_guide {"topic":"recipes"}`, \'Reference \u2014 download plan fingerprint limits\'. Never self-approve; resolve connection via `tia_pg_interfaces` (no scan). |\n\nFor the first download over another project\'s or another TIA version\'s program, plan with\n`allowUpgradeTargetDevice:true`; without it, a refusal may leave the CPU stopped.\nThe offline plan cannot predict whether TIA will request that confirmation.\n\nFor the first download over another project\'s or another TIA version\'s program, plan with\n`allowUpgradeTargetDevice:true`; without it, a refusal may leave the CPU stopped.\nThe offline plan cannot predict whether TIA will request that confirmation.\n\nScaffold order (UDTs BEFORE the blocks that use them): by hand, `tia_guide {"topic":"recipes"}`, \'Pipeline order\'. `tia_spec_apply` automates only subnets, devices, modules, network, tag tables, tags, FB shells, control-module instance DBs and the compile; protection, constants, UDTs and all logic stay manual. The FB shells it creates are empty: add their logic with `tia_source_put` (SCL) or `tia_import_xml` (LAD/FBD).\n\nUse the PlcSoftware name from `tia_plcs`, not the device name.\n\n## The approval envelope (what a gate handoff looks like)\n\nGated tools return `status:"requires_human_action"` with:\n\n- `gate` \u2014 which gate (e.g. `download_approval`, `station_upload`, `go_online`, `trust_dialog`);\n- `youMustDo` \u2014 what the human must confirm, in plain words;\n- `plan` + `planHash` \u2014 exactly what would be executed (the hash binds the approval to\n this exact plan; a changed plan needs a new approval); the download\'s plan also carries\n `fingerprint` (the software content the plan was verified against \u2014 show it too);\n- `nextSteps` \u2014 how to resume after the human\'s yes.\n\nRelay the envelope to the human, wait for an explicit yes, resume exactly as\ninstructed. The AI never approves, never invents a secret, never deploys F-logic.\n\n**Confirmation dialog.** When the client supports elicitation, the crossing calls (`tia_download` with\n`approved:true`; `tia_upload`, `tia_online`, `tia_accessible_devices` with `confirm:true`) first ask the\nhuman in a dialog; clients without it behave as before. The dialog only checks the human\'s answer: the\n`planHash` and serve\'s approval token stay the authority.\nPasswords (G6) are never asked there. `declined_by_human` / `cancelled_by_human` = the human refused:\nnothing was sent, no retry unless asked. `elicitation_failed` (`isError`) = the dialog could not be\nshown or answered, nothing was sent (fails closed).\n\n## After scaffolding\n\n- Re-run `tia_compile` after ANY authoring change.\n- `tia_project_save` regularly; `tia_project_archive` BEFORE risky operations\n (firmware change \u2014 see `tia_guide {"topic":"gotchas"}`).\n- Auditing an existing project is class R (`tia_plc_*` reads); baseline: `tia_guide {"topic":"recipes"}`, \'Reference \u2014 network, audit and CAx how-to\'.\n- `tia_crossrefs` (R, Long; poll `tia_job_status` for `jobId`): `UnusedObjects` returns\n CANDIDATES, not proof (OBs, external-only uses and library TYPEs can look unused).\n Before edits, use `target`, `kind`, `filter:"ObjectsWithReferences"`; the human interprets\n TIA\'s `referenceType` (`Uses`/`UsedBy`) and `access`. Page containers/whole PLCs with\n `limit` + unchanged `nextCursor` until null. App 1.8+ caches whole-PLC walks until mutation/close/cursor expiry;\n older serves re-read pages. Read coverage on every page, not only the first:\n a later page can report less than an earlier one. On `cursor_stale`, restart from the first\n page; differing counts restart the walk once from the first page. On omission retry the same request with smaller `limit`,\n never its cursor. Claim complete/no uses ONLY after a finished walk with identical counts,\n no omissions and `coverage.complete:true` on EVERY page; else NOT complete\n (inspect `coverage.unavailableOwners`).\n- **FAT/SAT I/O list** (`tia-verify` step 6): `tia_io_map`; recipe: `tia_guide {"topic":"recipes"}`, \'Recipe \u2014 generate the FAT/SAT I/O list\'.\n- **Prove the project matches what\'s versioned** (a raw hash is NOT proof): `tia_guide {"topic":"recipes"}`, \'Recipe \u2014 prove the project matches the versioned XML\'.\n\n## Network lifecycle (subnets, PROFINET names, IO systems)\n\nRead first (`tia_subnet_get`, `tia_device_network`, `tia_io_systems`), then run each write\'s `dryRun` (answered by\nthe serve, needs an open project). Order, PROFINET names, `disconnectNodes`: `tia_guide {"topic":"recipes"}`, \'Reference \u2014 network, audit and CAx how-to\'.\n\n- **Refused, nothing changed:** `tia_subnet_delete` of a non-empty subnet (`409 subnet_not_empty`);\n `tia_io_system_connect` across subnets (`409 cross_subnet_assignment`: `tia_network_connect` the device to that subnet first).\n- **`409 postcheck_failed`:** the write did not take effect as asked: re-read, never repeat blindly.\n\n## Libraries, HMI, CAx and PLC security\n\nReads are class R; every change is class M-off (offline, with `dryRun`) and reaches the CPU\nonly through a later `tia_compile` + human-gated `tia_download` (G3). Every file path is a\npath ON THE SERVE HOST.\n\n- **Guarded PLC writes** (`tia_tag_update`, `tia_constant_update`, `tia_constant_delete`,\n `tia_tagtable_delete`, `tia_block_group_delete`, `tia_ob_create`, `tia_block_compile`): the serve\n answers their `dryRun` (it needs an open project) with the guard verdict (name collision, default\n tag table, non-empty group, singleton OB).\n- **Project library:** `tia_library_mastercopies` / `tia_library_types` read it;\n `tia_library_mastercopy_create` turns a DEVICE into a master copy (a block cannot be a source);\n `tia_device_from_mastercopy` inherits PUT/GET, OPC UA license selection and HR mappings into a NEW station; regenerate its certificate;\n `tia_block_from_mastercopy` needs one that holds PLC blocks.\n- **Global libraries** (in the TIA Portal session, not the project): `tia_global_libraries`,\n `tia_global_library_create` / `_open` / `_save` / `_close`; save/close take the name from\n `tia_global_libraries` (exact name first, then ignoring case). REFUSED, nothing saved or closed\n (`404 not_found` / `409 conflict`): a name that picks no single open USER library (unknown, read-only\n system/corporate, several matches ignoring case) and a save of a `readWrite:false` library. Up to app\n 1.6.3 an unknown name can report success without saving or closing anything: check `tia_global_libraries`.\n- **HMI:** `tia_hmis` and `tia_hmi_screens` read any HMI; screen files\n (`tia_hmi_screen_export`, `tia_hmi_screens_import`) work for WinCC **Classic** only, and the\n import OVERWRITES same-named screens.\n- **CAx (AutomationML):** `tia_cax_export` / `tia_cax_import` (scope, `option` values: recipes). Archive the\n project before an overwrite. A failed transfer is an error after app 1.6.3; on an older serve check the\n devices with `tia_devices`.\n- **Error contracts by app version:** `tia_guide {"topic":"recipes"}`, \'Reference \u2014 global library and CAx error contracts (by app version)\'.\n- **PLC security:** `tia_certificates` / `tia_certificate_template` / `tia_password_policy`\n read; `tia_certificate_import` / `_export` / `_delete`, `tia_password_policy_set` and\n `tia_block_protect` change the project. **G6:** a block or certificate password and the\n password-policy values come from a HUMAN \u2014 never invent, guess or reuse one; dryRun plans\n show a password as `[redacted]`. A CPU without the certificate manager or a policy service\n answers 409.\n- **Multiuser:** `tia_project_servers`, `tia_server_projects` read Project Servers; `tia_local_session_open` needs NO open project (`tia_project_close`, `tia_start`). Nothing is ever checked in.\n';
29229
- var RECIPES = '# TIA version evidence, verified recipes & scaffold order\n\n## TIA version evidence and SimaticML\n\n**Delivery boundary:** App 1.8.0 retains the V21 baseline and ships no legacy layers. The following `minVersion` notes are the lowest **API major observed in the inspected V17\u2013V21 references**, not a legacy runtime-support promise or a universal introduction release. V16 has no measured gap matrix. Host version, PublicAPI version and CPU firmware are different values.\n\nBefore authoring, read selected host/API diagnostics when available. An installed compatibility DLL is not another installed host; if the target is unknown, ask rather than assume V21. Detection is not compatibility. Never bypass a version refusal through generic object calls, substitute delete/recreate or silently upgrade/downgrade.\n\n| Operation or field | Observed API `minVersion` | Evidence limit |\n|---|---|---|\n| Free-text `tia_catalog`, `tia_crossrefs`, `tia_device_change_version`, password-policy services; `tia_library_types`\' `LibraryType.Namespace` field | 18 | V17 gap; V18\u2013V20 uses bind. CPU/project service availability and legacy runtime behavior unverified. The library minimum is field-level, not a minimum for every library read. |\n| Unified tags/alarms/screens/connections/validation | 18 | V17 gap; V18 lacks alarm `TriggerBitAddress` and `TriggerAddress`; those fields bind from V19. This is not a reason to reject all V18 Unified reads. |\n| `tia_accessible_devices`, current certificate-export overload and CAx structured-result API | 19 | V17/V18 gap or signature adaptation; legacy execution unverified. Scan still requires human G7. |\n| Current VCI mapped-object/status/export model; multiuser groups and marking mutations | 20 | V17\u2013V19 gaps; two-argument VCI workspace creation already binds from V18. Older read surfaces are not equivalent to current mutations. |\n| S7 connection authoring; generic self-description type/support fields | 21 | Gaps across inspected V17\u2013V20; V21 is the reference baseline. |\n| Other tools and SimaticML import compatibility | null | No cross-version minimum/import matrix established; a V21 recipe does not establish legacy support. |\n\nThese notes derive from the V17 and V18\u2013V20 spikes (ADR 0041), which did **not** test cross-version LAD/FBD/SCL/UDT imports. An API that binds can still refuse a CPU/project; no silent fallback or invented data.\n\n**LAD/FBD/GRAPH authoring:** start from a real export made for the selected target Portal/API and preserve its `<Engineering version="...">`, interface, instruction and FlgNet/StructuredText namespaces. Do not copy a V21 template to a legacy target by changing version strings or namespaces. Import UDTs before dependent blocks; compile, export and compare on that same target. A matching marker is not proof of import compatibility. `tia_block_render` is review-only, never a version converter.\n\n**Import diagnostics:** V21 keeps its current import behavior, including Openness diagnostics; no new V21 version rejection. Legacy-only unsupported-version refusals must come from the authoritative target boundary before importing, for both inline XML and server-local `path`. Relay `409 feature_unsupported_in_version` and its operation/host/API/minimum/reason details when returned; do not infer a compatibility matrix from a namespace or claim all older XML is importable.\n\n**Hashes:** keep `sha256`, `normalizedSha256` and `contentHash` distinct. Normalization does not erase Engineering versions or schema namespaces and is not down-conversion. Keep a fresh `contentHash` from the same target/object for guarded writes; never reuse a V21 hash as a legacy baseline.\n\n**Live check (#213):** collect real V17 and V20 LAD/FBD/SCL/UDT exports at version acceptance, recording the host, loaded API, installed update and export options, then retain them as fixtures beside the V21 originals. Exercise import, compile, re-export and normalized comparison on each accepted target; record refusals and unknown combinations explicitly. V16 and V18/V19 also need their accepted evidence; V18/V19 acceptance is scoped to their APIs on the V20 host. Current fixtures prove V21 behavior only; synthetic marker edits are not real legacy exports.\n\n## Pipeline order (dependency-correct)\n\n`tia_spec_apply` automates only steps 1-4, the tag tables and tags of 6, the FB shells and control-module instance DBs of 8, and the compile of 9. Protection (5), constants (6), UDTs (7), OB/FC/DB blocks and all block logic stay manual: declaring `dataTypes` in the spec imports nothing. The FB shells of 8 are empty: their logic is step 8 by hand.\n\n1. **Subnets** (`tia_subnet_create`) \u2014 before connecting devices to them.\n2. **Devices** (`tia_device_create`, `OrderNumber:<MLFB>/V<fw>`) \u2014 CPUs first.\n3. **Modules** (`tia_device_plug`) \u2014 into existing devices, by slot.\n4. **Network** (`tia_network_connect`, IP, `createIoSystem`) \u2014 CPU + its IO-devices on the\n **same** subnet; exactly one `createIoSystem` per IO-system.\n5. **Protection recipe** (below) \u2014 so the CPU can compile clean.\n6. **Tag tables** (`tia_tagtable_create`) \u2192 **tags** (`tia_tag_create`) \u2192 **constants**.\n7. **UDTs first** (`tia_types_import`), **then** blocks that use them.\n8. **Blocks** \u2014 the FB comes with its logic: `tia_source_put` (SCL) or `tia_import_xml` (LAD/FBD/GRAPH), Gd6 format\n routing (`tia_fb_create` only makes an empty FB shell); then its instance DB (`tia_instancedb_create`).\n9. **Compile** (`tia_compile`) \u2014 the verifier; only `Error` blocks. It compiles the **software**\n scope (not just the CPU device item), so it makes freshly-generated blocks consistent and, in\n most cases, **regenerates** any instance DB left inconsistent by an FB interface change.\n **Recompile first**; only if the DB still reports inconsistent after a compile, delete it\n (`tia_block_delete`), recreate it (`tia_instancedb_create`) and recompile.\n\n**The PlcSoftware name.** TIA names the PlcSoftware of a CPU created through `tia_device_create` or `tia_spec_apply` after the CPU device item (default `PLC_1`), not the device, so `plc` in steps 6-9 is the name from `tia_plcs`. The spec plan carries `{plc}`; `tia_spec_apply` resolves it after the device step (`plc.resolve` in `applied`) and stops with kind `plc_unresolved` rather than guess. `devices[].plcName` names the CPU item.\n\n## Recipe \u2014 edit an existing block or type without overwriting a newer change (stale-write guard)\n\nRead it with `tia_export_block` (block) or `tia_export_type` / `tia_type_source` (type) and keep its `contentHash`: `contentHash`, `normalizedSha256` and `sha256` are different hash contracts over different normalizations, so never substitute one for another and pass only the `contentHash` of a fresh read as `expectedContentHash`. Edit, then write it back with `tia_import_xml`, `tia_source_put` or `tia_types_import` passing `expectedContentHash:<that contentHash>` (one object per write); on `state_changed` NOTHING was written \u2014 re-read, merge your edit onto the current content and retry with the new `contentHash`; a guarded write never compiles, so a block that is not consistent is refused with `409 inconsistent` (NOTHING written) \u2014 `tia_compile`, re-read with `tia_export_block` for the current `contentHash`, retry; an object whose current export is not well-formed XML has no hash (its read answers `contentHashError` instead of `contentHash`) and a guarded write over it is refused with `409 unverifiable` (NOTHING written) \u2014 repair or re-export it in TIA Portal, or retry WITHOUT `expectedContentHash` (an unguarded write); a verified write returns `contentGuard`.\n\n## Recipe \u2014 unlock a freshly-created CPU so it compiles clean (VERIFIED V21, firmware-dependent)\n\nA bare CPU added via Openness may fail `compile` with **protection** errors: the\n*confidential-PLC-configuration-data* password is unset, the *communication certificate*\ncan\'t be generated without it, and (on newer firmware) the *access control* defaults to a\nprotected level needing a password. **The recipe differs by CPU family/firmware \u2014 there is\nno single universal form.** Fix, in order:\n\n**Tell the human first.** The recipe lowers the CPU\'s protection in the project: it sets the\nconfidential-configuration password (typed by the human) and then either sets the access level\nto **Full access** (S7-1500) or turns access control **off** (S7-1200, FW V4.5+). The CPU runs\nwith that protection after the next download. Name these changes when you ask for the password\nand list them in the report; the human may pick a stricter level in the TIA GUI before deploying.\n\n**(1) Confidential-data password \u2192 also auto-generates the certificate** (common to both\nfamilies):\n\n```\n# find the CPU device-item handle:\ntia_obj_roots -> the device handle (role:"device")\ntia_obj_items { handle:<device>, composition:"DeviceItems" } -> the CPU item handle\n# acquire the service ON THE CPU MODULE (not the rack) and invoke Protect:\ntia_obj_service { handle:<cpu>, type:"Siemens.Engineering.HW.Features.PlcMasterSecretConfigurator" } -> <svc>\ntia_obj_invoke { handle:<svc>, name:"Protect", args:["<password>"] }\n```\n\n**(2) Clear the access-control error \u2014 pick the variant for the CPU\'s family/firmware:**\n\n- **S7-1500 V2.9** (verified 2026 on real hardware \u2014 a 1516-3 V2.9, 3 errors \u2192 0): set\n `PlcProtectionAccessLevel = "FullAccess"` **on the CPU device item**:\n\n ```\n tia_obj_set_attributes { handle:<cpu>, attributes:{ "PlcProtectionAccessLevel":"FullAccess" } }\n ```\n\n- **S7-1200 V4.7** (new security model, FW \u2273 V4.5; per `docs/HARNESS-KNOWLEDGE.md` \xA72,\n runtime-observed): set `PlcAccessControlConfiguration = "Disabled"` on the\n **`PlcAccessControlConfigurationProvider`** SERVICE \u2014 not a direct attribute on the CPU\n item:\n\n ```\n tia_obj_service { handle:<cpu>, type:"Siemens.Engineering.HW.Features.PlcAccessControlConfigurationProvider" } -> <svc2>\n tia_obj_set_attributes { handle:<svc2>, attributes:{ "PlcAccessControlConfiguration":"Disabled" } }\n ```\n\n \u26A0\uFE0F **The two variants are mutually exclusive \u2014 the wrong one returns HTTP 500 on the\n other family:** `PlcAccessControlConfiguration` isn\'t on a 1500\'s CPU item, and\n `PlcProtectionAccessLevel` isn\'t the right model on a 1200 V4.7 item. Detect the\n family/FW \u2014 or the compile-error signature \u2014 before picking a variant.\n\n- **S7-1200 V4.0** (old security model): nothing to do here \u2014 the same bare-CPU condition\n is only a **WARNING**, not an error; a plain `tia_compile` already returns `errors: 0`.\n\nThen `tia_compile` \u2192 `state: Warning, errors: 0` (any remaining warnings \u2014 e.g. CPU-display\npassword \u2014 are benign and do **not** block; Gd8).\n\n> **Requires the `tia_obj_service` tool** (acquire `GetService<T>` \u2192 handle) for step 1 and\n> for the S7-1200 V4.7 variant of step 2. Without it the MCP cannot run either.\n\n### Policy \u2014 who supplies the confidential password\n\n`Protect()` sets an **offline project** password (it is not the online master secret / G6), but\nit protects confidential configuration data, so **the human supplies it, every time** (the\nrecommended policy, pending the product owner\'s confirmation): the project-spec has no field\nfor it, and a skill never invents, defaults, stores or logs it. The online master secret (`tia_mastersecret_set`, G6) is **always**\nhuman-supplied too.\n\n## S7 connection precondition (G2)\n\n`tia_connection_create` needs **\u2265 2 CONSISTENT CPUs** (both compile clean). Two *bare* CPUs\nnever form a valid S7 connection \u2014 apply the protection recipe + `tia_compile` to make each\nconsistent first, then create the connection. Use `tia_connections_diagnose` on failure.\n\n## Recipe \u2014 bump the project firmware **in-place** (keeps the program) (VERIFIED, V21 / S7-1200 1214C)\n\nBumped a project **V4.0 \u2192 V4.4** on a real S7-1200 1214C **without losing blocks or tags**\n(verified 2026-06-07). Use this for **auto-FW-match**: align the project to the firmware\nactually read from the CPU. `DeviceItem.ChangeType(typeIdentifier)` changes the item type\nin place and **preserves the software** \u2014 it does **not** require delete/recreate.\n\n```\n# archive first (see the warning below), then change the CPU\'s type to the SAME MLFB with the target /V<fw>:\ntia_device_change_version { plc:"<plc>", typeIdentifier:"OrderNumber:6ES7 214-1HG40-0XB0/V4.4" }\n# then recompile \u2014 a regenerated FB may need a fresh compile before download:\ntia_compile { ... }\n```\n\n(`tia_device_change_version` runs `ChangeType` on the CPU item for you; the raw form, `tia_obj_invoke`\nwith `name:"ChangeType"` on the CPU item handle from `tia_obj_roots` / `tia_obj_items`, does the same.)\n\n- **Rule: `project FW \u2264 device FW`** \u2014 never set the project firmware **higher** than the physical\n device\'s (download would be rejected). Bumping the project *up to* the device FW is the safe move.\n- Keep the **same MLFB**, swap only the `/V<fw>` suffix. The program (blocks/tags) survives.\n- After `ChangeType` the CPU/blocks can be inconsistent; **always recompile** before any handoff.\n- **\u26A0\uFE0F `ChangeType` RESETS GUI-gated comm settings** (runtime-validated on the 1214C): it **disabled\n the OPC UA server** (`OpcUaServer`\u2192`false`) and **cleared the OPC UA runtime-license** selection\n (the custom server interface and PUT/GET *survived*). So **`tia_project_archive` first** on a CPU\n with hand-configured OPC UA/PUT-GET, and **re-verify after**. Recovery: `tia_obj_set_attributes\n {handle, attributes:{OpcUaServer:true}}` on the "OPC UA" device-item (it **is** writable; re-select the license in the\n GUI). `ChangeType` to the **same** version is rejected ("Cannot change the type of the device item").\n\n## Recipe \u2014 enable a **Modbus TCP server** (`MB_SERVER`) on the S7-1200 (VERIFIED, FW V4.0)\n\nLets an external client (e.g. a Node backend) read/write the CPU over **Modbus TCP, port 502**\n(verified 2026-06-07; full backend/app detail in `docs/COMM-SCENARIOS.md`).\n\n1. **Non-optimized DB with an `Array of Word`** for the holding-register block (`MB_HOLD_REG`).\n Modbus needs a byte-addressable (non-optimized) DB \u2014 optimized access won\'t map.\n2. **On FW V4.0 use `MB_SERVER` V1.x**, which takes **`CONNECT_ID` + `IP_PORT`** parameters\n (**not** `CONNECT`/`TCON`, which the newer instruction versions use). Pin the instruction\n version when generating the FB.\n3. Instantiate `MB_SERVER` as a **multi-instance inside an FB** (its instance lives in the FB\'s\n instance DB), call it cyclically.\n4. **Map a holding register \u2192 a command tag** (e.g. `MB_HOLD_REG[0]` \u2192 `LedCmd`), so writing the\n register drives the output.\n\n> **Instance-DB gotcha (the big one):** when you regenerate the FB via `tia_source_put`, the\n> existing **instance DB** can go inconsistent (its interface no longer matches the FB).\n> **Recompile first** \u2014 a software-scope `tia_compile` regenerates the instance DB in most cases.\n> Only if it still reports inconsistent after a compile (typical when the interface was edited via\n> source), delete + recreate it, then recompile:\n>\n> ```\n> tia_compile { ... } # try first\n> tia_block_delete { ... the stale instance DB ... } # only if still inconsistent\n> tia_instancedb_create { ... fresh instance DB for the FB ... }\n> tia_compile { ... }\n> ```\n>\n> (Matches the \xA7Pipeline note: recompile first, delete+recreate only as the fallback.)\n\n## Recipe \u2014 enable **S7 / PUT-GET** on the S7-1200 (port 102)\n\nLets an external S7 client (e.g. `nodes7`) read/write the CPU over **S7comm, port 102**.\n\n1. For a fresh CPU, ask the human to enable PUT/GET: *Properties \u2192 Protection & Security \u2192\n Connection mechanisms \u2192 "Permit access with PUT/GET communication"*. No direct setter was\n verified on the 1214C V4.4. Alternatively, `tia_device_from_mastercopy` inherits this\n permission from an owner-prepared station; do not script the GUI.\n2. **Non-optimized DB** for the data the client touches (PUT/GET addresses absolute offsets, so\n the DB must be byte-addressable / non-optimized).\n3. Compile + download as usual; the client then reads/writes the DB by area+offset.\n\n## Recipe \u2014 enable **OPC UA** on the S7-1200 (port 4840)\n\nLets an external OPC UA client read/write the CPU over **OPC UA, port 4840**.\nUse the manual sequence for a fresh CPU, or clone an owner-prepared station as described below.\n\n**Prerequisite \u2014 firmware \u2265 V4.4.** OPC UA server isn\'t available on V4.0. If the project is on\nan older FW, bump it in-place first (see *bump the project firmware in-place* above \u2014\n`ChangeType` to `.../V4.4`).\n\nFor a fresh CPU, step 1 is scriptable; steps 2\u20133 require human configuration:\n\n1. **Activate the OPC UA server** \u2014 *Properties \u2192 OPC UA \u2192 Server* (enable). *(This step **is**\n scriptable via Openness: `tia_obj_set_attributes {handle, attributes:{OpcUaServer:true}}` on the "OPC UA"\n device-item \u2014 it auto-generates the server certificate.)*\n2. **Select the runtime license** \u2014 *"SIMATIC OPC UA S7-1200 Basic"* (Runtime licenses).\n3. **Create a server interface** (type **Interface**) and drop the **`ModbusData.HR` array**, not the\n DB or separate elements. The S7-1200 does not auto-expose DBs. Browse the resulting node IDs.\n\n**Finding the node IDs (client side):** browse `ns=3;s=ServerInterfaces` with any OPC UA client;\nthe actual data nodes show up under **`ns=4`**. Use those node IDs from the backend.\n\n**Prepared-station path (V21 / 1214C V4.4):** capture the configured source with\n`tia_library_mastercopy_create`, then `tia_device_from_mastercopy {masterCopy}`. This creates a new\nstation, preserving PUT/GET, selected runtime license and the HR interface; it is not an existing-CPU\nsetter or a license grant. TIA may rename the new PLC. Certificates are not copied: inspect its\n"OPC UA" item; `OpcUaServer:false` then `true` regenerated the certificate in the measured clone.\nCompile, save/reopen and check the exported HR mappings before any human-gated download.\nThe GUI type **Interface** is exposed as `SimaticInterface` (Export/Delete, no Import);\n`ServerInterface.Import` did not reproduce its HR mapping. See `tia_guide {"topic":"gui-gates"}`.\n\n## Recipe \u2014 WinCC Unified HMI: read, then guarded writes\n\nOnly for a WinCC **Unified** HMI (`tia_hmis` \u2192 `kind:"unified"`). A Classic HMI answers `409 hmi_not_unified`; use the screen export/import there. Everything below is offline (M-off): it edits the project, never the panel or the PLC.\n\n1. **Read first.** `tia_hmis` for the HMI name, then `tia_hmi_tag_tables`, `tia_hmi_tags` (`table`), `tia_hmi_alarm_classes`, `tia_hmi_alarms` (`kind`: `discrete`|`analog`) and `tia_hmi_connections`. Every read pages (`limit` 1..1000, `cursor`): follow `nextCursor` UNCHANGED, and on `cursor_stale` restart from the first page. Read `inventoryGaps` too: a non-empty list means a value reads `null` because Openness refused it, so do not write on the strength of that value.\n2. **Baseline.** `tia_hmi_validate` (scope `all`, or `tags`/`alarms`/`connections`/`screens`) aggregates the per-object `Validate()` results into `errors`, `warnings` and `findings`. Unified has NO compile: a clean validate is not a clean compile, and it can be slow (Long).\n3. **`dryRun:true` on EVERY write first** (`tia_hmi_tag_table_create|delete`, `tia_hmi_tag_create|update|delete`, `tia_hmi_alarm_create|update|delete`). The plan runs the same guards as the real call and changes nothing; repeat without `dryRun` only when it answers `plan_ok`. The real answer carries `postcheck` (`verified:true`, `requested` equal to `actual`). `409 postcheck_failed` is NOT a success: read the object again before going on (`rollback` says what was undone; a delete is never rolled back).\n4. **What the guards enforce \u2014 fix the cause, do not retry the same call.** Names: letters, digits and `_`, starting with a letter or `_` (tag tables may also hold spaces and `-` inside), at most 128 characters (`invalid_name`), unique ignoring case (`name_collision`). `dataType` is an allow-list: Bool, Byte, Char, DInt, DWord, Int, LInt, LReal, LWord, Real, SInt, String, UDInt, UInt, ULInt, USInt, Word, WChar, WString, DateTime, Time (`invalid_data_type`). A tag without `connection` is internal and needs `dataType`; with `connection` it is external and takes exactly one of `plcTag` or `address`. A PLC-bound tag needs a `plcTag` that EXISTS in the connected PLC (`plcName` when the connection\'s partner does not resolve to one PLC): `plc_unresolved` / `reference_not_found` mean fix the link, never invent a tag. A PLC tag whose own name contains a dot or a bracket is sent as ONE quoted token (`"A.B"`, `"Valve[1]"`): unquoted, `A.B` is member `B` of data block `A` and `Valve[1]` is an indexed name, so the call is refused. A discrete alarm needs an existing `alarmClass` and `triggerTag` and a `triggerBit` inside the width of the tag\'s type (Bool: 0, Word: 0..15; `trigger_bit_out_of_range`); an analog alarm has ONE `condition` and ONE `conditionValue` on a numeric tag (no limit ordering exists), and the value must fit the type (`condition_value_out_of_range`).\n5. **Alarm values, event text and what a read shows.** TIA stores the condition value of an alarm as a double: on an `LInt`, `ULInt` or `LWord` trigger tag a whole `conditionValue` above 2^53 in absolute value is refused `409 condition_value_out_of_range` (a `dryRun` too, nothing written); 2^53 itself is accepted, sent as a string, and `Real` and `LReal` values are always JSON numbers. `eventText` is PLAIN single-paragraph text per active project language: the serve wraps it as the rich text TIA stores (`<body><p>\u2026</p></body>`) and escapes `&`, `<` and `>`, so send no markup; a line break, an XML-invalid character (a tab is allowed), an unpaired surrogate, a blank text or more than 1024 characters is `400 bad_request`, and a text cannot be cleared by a write. A read answers the plain text (an event-text item without text is `""`, a language without an item `null`; any other markup comes back as raw rich text, which cannot be written back). TIA\'s placeholders read as `null`: an internal tag has `connection`, `plcName`, `plcTag`, `address`, `accessMode`, `acquisitionMode` and `acquisitionCycle` all `null` (TIA reads its connection back as a placeholder such as `<Internal tag>`), and an alarm class without a common class has `commonAlarmClass` `null` (`<No alarm class>`). The attribute list of an alarm itself is never read: `hmi_attribute_list_unavailable` and `hmi_attribute_not_writable` apply to tags and to the event text item of each culture (its list unreadable, `Text` not writable, or no item for that language), never to another alarm attribute.\n6. **Deleting.** A tag, or a tag table that holds one, is refused with `tag_in_use` while an alarm references it; a non-empty table needs `recursive:true` (`tag_table_not_empty`); the default table is refused. References from screens, scripts and logging are NOT scanned, so run `tia_hmi_validate` again after a delete.\n7. **Finish** with `tia_hmi_validate` and compare `errors` and `findings` with the baseline.\n\nLimits to remember: a **create\'s `dryRun` cannot check writability** (a `plan_ok` can still end in `hmi_attribute_not_writable`, after which the new object is removed again); an **update checks only what it changes** (a tag change against the stored bit or value, a connection change against its link), never a reference it leaves alone, and never switches a tag between `plcTag` and `address` \u2014 `tia_hmi_validate` finds a dangling carried reference; send a whole `conditionValue` as a **JSON integer or a string** (`5.0` and `1e3` are refused, and so is a whole value above 2^53 on an `LInt`, `ULInt` or `LWord` tag: step 5); a system tag may be an alarm trigger tag; `tia_hmi_validate` is Long, so it may answer `status:"running"` with a `jobId`: follow `tia_job_status` and never repeat the call.\n\nNo tool creates an HMI connection: when `tia_hmi_connections` is empty, PLC-bound tags cannot be created \u2014 ask the human to create the connection in TIA Portal.\n\n## Recipe \u2014 diff a project against a VCI workspace, or round-trip a block through a new one\n\nA VCI workspace is a folder on the serve host that mirrors project objects as files, so a diff tool or git can version\nthem. VCI takes **leaf objects only** (PLC blocks, PLC data types, tag tables): a device, a PLC, a group or the library is\nrefused with `409 vci_not_leaf` before VCI is called. Every write takes `dryRun:true` first (Gd11), a call holds at most 50\nobjects, and a batch is NOT a transaction: it stops at the first failure.\n\n**(1) A workspace that already has mapped objects is a baseline: its diff is READ-ONLY.**\n\n```\ntia_vci_workspaces -> `mappedObjects` above 0: a baseline exists\ntia_vci_status { workspace:"WS_1", limit:100 } -> follow nextCursor until it is null\n```\n\nClassify every row. `equal` is the only verified match. `projectChanged` (the project object changed), `workspaceChanged`\n(the file changed), `conflict` (both), `workspaceFileMissing` (the file is gone) and `unequal` (a difference of unknown\nside) are differences: report each by name, they are the result, not something to repair. `unknown`, `unsupported` and\n`statusFailed` prove nothing, neither equality nor a diff: report them by name, and the diff is NOT complete. **Never\nexport or import just to make a comparison equal.** `tia_vci_export` over a mapped object REPLACES its workspace file\nwith the project content (the plan says `action:"synchronize"`) and `tia_vci_import` replaces the project object with\nthe file, so either one destroys the difference you were asked to see. Refreshing the baseline is an explicit decision\nof the human: name the objects, ask, and only then export with `dryRun:true` first and read which files the plan\nreplaces.\n\n**(2) A NEW workspace, or new objects: export, then prove it.**\n\n```\n(a) tia_vci_workspaces -> reuse a workspace that is listed\n # none yet: ask the HUMAN for the root folder on the serve host. Never choose or invent a rootPath.\n tia_vci_workspace_create { name:"WS_1", rootPath:"<the folder the human gave>", dryRun:true }\n tia_vci_workspace_create { name:"WS_1", rootPath:"<the same folder>" } -> created | reused\n(b) tia_vci_export { workspace:"WS_1", objects:[{ kind:"block", name:"FB_Motor" }], dryRun:true }\n tia_vci_export { workspace:"WS_1", objects:[{ kind:"block", name:"FB_Motor" }] } -> the file(s) written\n(c) tia_vci_status { workspace:"WS_1", limit:100 } -> follow nextCursor until it is null\n(d) tia_export_block { plc:"PLC_1", block:"FB_Motor" } -> contentHash\n tia_block_set_attribute { plc:"PLC_1", block:"FB_Motor", name:"HeaderAuthor", value:"<a new text>" } -> an edit IN PLACE: the mapping survives\n tia_block_compile { plc:"PLC_1", block:"FB_Motor" }\n tia_export_block { plc:"PLC_1", block:"FB_Motor" } -> a DIFFERENT contentHash\n tia_vci_status { workspace:"WS_1", limit:100 } -> that row is now projectChanged\n(e) tia_vci_import { workspace:"WS_1", objects:[{ kind:"block", name:"FB_Motor" }], dryRun:true }\n tia_export_block { plc:"PLC_1", block:"FB_Motor" } -> a fresh contentHash\n tia_vci_import { workspace:"WS_1", objects:[{ kind:"block", name:"FB_Motor", expectedContentHash:"<fresh>" }] }\n tia_export_block { plc:"PLC_1", block:"FB_Motor" } -> the import REPLACED the project object: read it again by name\n tia_vci_status { workspace:"WS_1", limit:100 } -> that row is equal again\n```\n\n- **(b) Read the plan.** `action:"export"` creates a new file; `willCreateDirectory:true` on an object means the serve will\n create its target folder (the first export into a fresh workspace has none yet), and the dry run creates nothing. An\n object the plan lists as `synchronize` is already\n mapped and its file would be REPLACED: stop and go back to (1). `format` chooses the file format of an UNMAPPED object\n only (leave it out unless the serve answers `400 bad_request` with `details.supportedFormats`); a mapped object keeps its\n mapping\'s format and the selector is neither applied nor validated for it.\n- **(b) A `skip` is not a write.** An object the plan lists as `skip` (`reason:"already_equal"`) is already mapped and its\n status is `equal`: TIA refuses to synchronize an equal mapping, so the serve writes nothing for it and the answer lists it\n as `skip`.\n- **(c) Verify an export.** Every row of every page must be `equal`. Read `coverage` on EVERY page: `summary` and\n `coverage` describe only the rows of that response (the serve compares only the rows of the page), so fold them over all\n pages before saying the workspace is in sync. `409 cursor_stale` (a mapping appeared or went) restarts the walk once.\n- **(d) Edit the project IN PLACE, never by regenerating.** A block attribute (`tia_block_set_attribute`, a header attribute such as `HeaderAuthor`) keeps the project object, so its mapping stays and the row becomes `projectChanged` (measured on V21). If `tia_export_block` shows the same `contentHash` afterwards, that attribute is not part of the exported XML: try another header attribute (`HeaderFamily`, `HeaderName`). `tia_source_put` (regenerating the block from SCL) REPLACES the project object, and V21 DROPS its VCI mapping (measured): the row vanishes from `tia_vci_status` and `tia_vci_import` answers `409 not_mapped`, which is the correct answer, not a fault; `tia_import_xml` over an existing block replaces it the same way (not measured separately). Export the new object again to map it: `tia_vci_export` is refused `409 vci_path_collision` (`reason:"file_exists"`) while the old workspace file is still in the folder, so ask the human to remove or move that file first; on a baseline you were asked to diff, report the dropped mapping instead of exporting over it.\n- **(d) What a row says.** Only `equal` is a match. After a human edits a workspace file its row should show\n `workspaceChanged`; a row that still says `equal` after a known edit means the status is not live (V21 has no refresh\n call): say so and treat the check as NOT verified.\n- **(e) Read the plan before importing, and read the hash per kind.** The dry run shows per object `statusBefore` and\n `overwritesProjectChanges` (`true` for `projectChanged` and `conflict`: the import discards an edit that exists only in\n the project, there is no undo, so ask the human). An object that is already `equal` is skipped. The hash reader depends\n on the kind: a block uses `tia_export_block`, a type uses `tia_export_type { plc:"PLC_1", type:"UDT_Motor" }`, and a tag\n table has NO hash (the serve and the MCP refuse `expectedContentHash` for it), so rely on the dry run and the postcheck.\n A wrong `expectedContentHash` is `409 state_changed` and nothing was written.\n- **(e) A refused file, a changed attribute.** A workspace file that TIA refuses (an SD parser error, a corrupted resource\n file) is `400 bad_request` with TIA\'s text and nothing changed: fix the file, never retry it unchanged. A postcheck whose\n `attributeChanges` lists the `SecondaryType` or `Number` of an OB, or `IsOnlyStoredInLoadMemory`, `IsWriteProtectedInAS`\n or `DBAccessibleFromOPCUA` of a data block, means TIA changed the object while importing it (a SIMATIC SD import does):\n the object WAS written, so report the before and after and do not call the import done.\n- **An import REPLACES the project object.** After a real import the old object is disposed: a handle of it (`tia_obj_*`) and every value read before are stale, so re-read the block by name (`tia_export_block`, `tia_plc_blocks`) and then `tia_vci_status`. The serve does the same for its postcheck: an object it cannot find again by name, or whose mapping the replacement dropped, is `409 import_unverified` (the object WAS written). In a batch, an object that can no longer be found or mapped when its turn comes stops the batch there: `409 vci_batch_incomplete` naming it, or `409 conflict` when nothing was imported yet; nothing more is written.\n- **Verified only with a postcheck.** An import is done only when every imported object has `postcheck.verified:true`. Every\n other answer means it is NOT verified: `409 import_unverified` (the object WAS written, review it with `tia_export_block`\n or `tia_export_type`), `409 vci_batch_incomplete` (`done` lists the objects written and the skipped ones, `action: skip`, nothing written for them), a status row `unsupported`,\n `statusFailed` or `unknown`, `coverage.complete:false`, an omission marker that survives smaller `limit` retries, or a\n page walk that did not finish.\n- **Unknown outcomes.** `504 worker_restarted`, a `timeout` or a lost session during an export or an import leaves the\n outcome UNKNOWN or partial: walk `tia_vci_status` and re-read the object before repeating anything.\n- **Refusals before any write** (nothing changed): `vci_path_collision` (two objects, another mapping or an existing file\n share a target; `reason:"alias_unverifiable"` means the short 8.3 name of an existing file in the target folder could not\n be read, so a collision with its alias cannot be excluded), `vci_path_too_long`, `vci_mapping_outside_workspace` for an\n EXISTING mapping rejected in the plan, `not_mapped` (export it first), `workspace_file_missing`, `workspace_exists`,\n `workspace_root_in_use`, `workspace_ambiguous` (ask the human which workspace is meant) and `vci_inventory_incomplete`\n (the workspace inventory could not be read completely: report it and stop, never guess a workspace).\n- **`vci_mapping_outside_workspace` has TWO outcomes.** An existing mapping rejected in the plan changed nothing. After a\n NEW export the same kind means the file WAS written outside the workspace root: read its message and `details`\n (`object`, `directory`, `root`, `done`), report it, hand the cleanup to the human and never retry blindly.\n\n## Reference \u2014 global library and CAx error contracts (by app version)\n\n**Project library** (`tia_block_from_mastercopy`). A device copy is refused (`409 mastercopy_not_blocks` after app 1.6.3; up to 1.6.3 a 500).\n\n**Global libraries** (`tia_global_library_save` / `_close`). After app 1.6.3 a name that picks no single open USER library is refused, nothing saved or closed: `404 not_found` (`details.userLibraries` lists the names that work), or `409 conflict` for a read-only system/corporate library or a name several user libraries match only ignoring case; up to 1.6.3 the serve reports success even for an unknown name. A library opened read-only (`readWrite:false`) cannot be saved: `409 conflict` (`details.readOnly`) after app 1.6.3, a 500 up to 1.6.3 \u2014 close it and open it again with `readWrite:true` to change and save it.\n\n**CAx (AutomationML)** (`tia_cax_export` / `tia_cax_import`). A failed transfer is an error (`500 cax_transfer_failed`) after app 1.6.3; up to 1.6.3 the serve returns an opaque `result` even on failure \u2014 check the devices with `tia_devices`.\n\n## Reference \u2014 download plan fingerprint limits\n\n**Fingerprint limits** (`tia_download`): user program blocks, UDTs and tag tables only \u2014 no hardware configuration, system block groups, S7-1500 software units or technology objects; per-object fallback to modification dates (`source:"dates"`, warned in the plan \u2014 dates can false-positive `plan_stale`).\n\n## Recipe \u2014 generate the FAT/SAT I/O list (tia_io_map)\n\n**Generate the FAT/SAT I/O list** (`tia-verify` step 6). `tia_io_map` (`jobId` \u2192 `tia_job_status`), one\nlist per PLC, `limit:100`, `cursor` = previous `nextCursor` unchanged until null. Read `coverage` on every\npage; `cursor_stale` or differing coverage restarts once; omission marker: same call and cursor, half the\n`limit`, max 3 times, never follow its cursor. Rows: one per tag on a `channel`, or on a `range` with\nstatus `matched`; per unmatched `tag` entry; and (empty tag) per unmatched `channel` or channelless\n`range`; none for a `range` with status `channels`; a tag spanning channels: ONE row (`table`+`name`)\nlisting them; statuses `matched`|`unmatched`|`conflict` only. Unresolved channels/ranges and unparsed\ntags: "Could not be mapped". Print `coverage` numbers, `coverage.limits`, DERIVED addresses (spot-check in\nTIA). Complete ONLY after a finished walk with no marker left on ANY page and `coverage.complete: true`,\nsame counts, on every page; else start "NOT complete", say why. An unmatched tag is never\n"unused"/"orphan"; never invent, round or fix an address. Read-only; the human signs.\n\nLengths: a `range`\'s `start` is a byte number and its `length` is in BYTES (Openness reports an address length in bits and the map converts it, rounding up to whole bytes); `from` and `to` are its first and last bit (2 bytes from `%I0.0` end at `%I1.7`). `tia_device_tree` shows the raw Openness value, in BITS: convert before comparing the two.\n\n## Recipe \u2014 prove the project matches the versioned XML (tia_block_compare)\n\n**The project matches what\'s versioned \u2014 prove it, don\'t assume it.** A raw hash of an\nexport is NOT proof (two exports of the same block differ in `<Created>`/UIds). Use\n`tia_export_block` to pull a block inline and `tia_block_compare` to diff it against the\ncommitted XML (normalized \u2014 ignores formatting/BOM/`<Created>`; UIds are canonically renumbered,\npreserving wiring); `verdict:"equal"` is\nthe actual round-trip proof. After `tia_compile`/`tia_source_put`, read `blockChanges` and\nexport/commit any regenerated instance DBs before calling the project verified.\nComparison hashes (`normalizedSha256`) from older MCP builds that stripped UIds may change:\nrecompute stored comparison baselines.\n\n## Reference \u2014 network, audit and CAx how-to\n\n**Network lifecycle.** `tia_subnet_delete` on a non-empty subnet is refused (`409 subnet_not_empty`); `disconnectNodes:true` disconnects its nodes and removes its IO systems. A subnet rename (`tia_subnet_update` `name`) takes at most 24 characters: a longer name is `400 invalid_subnet_name` (a `dryRun` too, nothing changed) although `tia_subnet_create` accepts longer names; a name equal to the current one is not a rename, and the serve counts UTF-16 code units, spaces included. PROFINET name (`tia_pn_name_set`): lower-case DNS labels (`a-z0-9-`) split by `.`, not an IP look-alike. A node in its default state (automatic name generation on, `PnDeviceName` read-only) takes a `name`: the serve switches auto-generation off first and writes the name second, and its `dryRun` cannot prove that the name becomes writable, so a `plan_ok` can still be followed by `409 pn_name_unsupported` from the real call; the serve then writes the previous auto-generation back and verifies it, the error ends with "Nothing was changed." only when that read-back confirmed it, and otherwise `409 conflict` names `autoGeneration` as NOT restored: re-read with `tia_device_network`. IO system first: `tia_io_system_create` on the controller, then `tia_io_system_connect` per device; `409 cross_subnet_assignment`: connect the device to that subnet (`tia_network_connect`) first.\n\n**Audit** (class R). Read blocks/types/tags via `tia_plc_*` and check the engineering baseline: optimized access, 100% symbolic, UDT-typed interfaces, FB + instance-DB, uniform naming. Scope `tia_crossrefs` with `target`/`kind` on a big project: a whole-PLC read can take minutes.\n\n**CAx (AutomationML).** `tia_cax_export` exports one device or the whole project; `tia_cax_import` takes `option`: `RetainTiaDevice` (default) / `OverwriteTiaDevice` / `MoveToParkingLot`.\n\n## Where to stop\n\nEverything above is **offline (M-off)**. `tia_download` / `tia_online` (G3/G4) are **not**\npart of scaffold \u2014 they belong to `tia-handoff` and require explicit human approval.\n';
29230
+ var RECIPES = '# TIA version evidence, verified recipes & scaffold order\n\n## TIA version evidence and SimaticML\n\n**Delivery boundary:** App 1.8.0 retains the V21 baseline and ships no legacy layers. The following `minVersion` notes are the lowest **API major observed in the inspected V17\u2013V21 references**, not a legacy runtime-support promise or a universal introduction release. V16 has no measured gap matrix. Host version, PublicAPI version and CPU firmware are different values.\n\nBefore authoring, read selected host/API diagnostics when available. An installed compatibility DLL is not another installed host; if the target is unknown, ask rather than assume V21. Detection is not compatibility. Never bypass a version refusal through generic object calls, substitute delete/recreate or silently upgrade/downgrade.\n\n| Operation or field | Observed API `minVersion` | Evidence limit |\n|---|---|---|\n| Free-text `tia_catalog`, `tia_crossrefs`, `tia_device_change_version`, password-policy services; `tia_library_types`\' `LibraryType.Namespace` field | 18 | V17 gap; V18\u2013V20 uses bind. CPU/project service availability and legacy runtime behavior unverified. The library minimum is field-level, not a minimum for every library read. |\n| Unified tags/alarms/screens/connections/validation | 18 | V17 gap; V18 lacks alarm `TriggerBitAddress` and `TriggerAddress`; those fields bind from V19. This is not a reason to reject all V18 Unified reads. |\n| `tia_accessible_devices`, current certificate-export overload and CAx structured-result API | 19 | V17/V18 gap or signature adaptation; legacy execution unverified. Scan still requires human G7. |\n| Current VCI mapped-object/status/export model; multiuser groups and marking mutations | 20 | V17\u2013V19 gaps; two-argument VCI workspace creation already binds from V18. Older read surfaces are not equivalent to current mutations. |\n| S7 connection authoring; generic self-description type/support fields | 21 | Gaps across inspected V17\u2013V20; V21 is the reference baseline. |\n| Other tools and SimaticML import compatibility | null | No cross-version minimum/import matrix established; a V21 recipe does not establish legacy support. |\n\nThese notes derive from the V17 and V18\u2013V20 spikes (ADR 0041), which did **not** test cross-version LAD/FBD/SCL/UDT imports. An API that binds can still refuse a CPU/project; no silent fallback or invented data.\n\n**LAD/FBD/GRAPH authoring:** start from a real export made for the selected target Portal/API and preserve its `<Engineering version="...">`, interface, instruction and FlgNet/StructuredText namespaces. Do not copy a V21 template to a legacy target by changing version strings or namespaces. Import UDTs before dependent blocks; compile, export and compare on that same target. A matching marker is not proof of import compatibility. `tia_block_render` is review-only, never a version converter.\n\n**Import diagnostics:** V21 keeps its current import behavior, including Openness diagnostics; no new V21 version rejection. Legacy-only unsupported-version refusals must come from the authoritative target boundary before importing, for both inline XML and server-local `path`. Relay `409 feature_unsupported_in_version` and its operation/host/API/minimum/reason details when returned; do not infer a compatibility matrix from a namespace or claim all older XML is importable.\n\n**Hashes:** keep `sha256`, `normalizedSha256` and `contentHash` distinct. Normalization does not erase Engineering versions or schema namespaces and is not down-conversion. Keep a fresh `contentHash` from the same target/object for guarded writes; never reuse a V21 hash as a legacy baseline.\n\n**Live check (#213):** collect real V17 and V20 LAD/FBD/SCL/UDT exports at version acceptance, recording the host, loaded API, installed update and export options, then retain them as fixtures beside the V21 originals. Exercise import, compile, re-export and normalized comparison on each accepted target; record refusals and unknown combinations explicitly. V16 and V18/V19 also need their accepted evidence; V18/V19 acceptance is scoped to their APIs on the V20 host. Current fixtures prove V21 behavior only; synthetic marker edits are not real legacy exports.\n\n## Pipeline order (dependency-correct)\n\n`tia_spec_apply` automates only steps 1-4, the tag tables and tags of 6, the FB shells and control-module instance DBs of 8, and the compile of 9. Protection (5), constants (6), UDTs (7), OB/FC/DB blocks and all block logic stay manual: declaring `dataTypes` in the spec imports nothing. The FB shells of 8 are empty: their logic is step 8 by hand.\n\n1. **Subnets** (`tia_subnet_create`) \u2014 before connecting devices to them.\n2. **Devices** (`tia_device_create`, `OrderNumber:<MLFB>/V<fw>`) \u2014 CPUs first.\n3. **Modules** (`tia_device_plug`) \u2014 into existing devices, by slot.\n4. **Network** (`tia_network_connect`, IP, `createIoSystem`) \u2014 CPU + its IO-devices on the\n **same** subnet; exactly one `createIoSystem` per IO-system.\n5. **Protection recipe** (below) \u2014 so the CPU can compile clean.\n6. **Tag tables** (`tia_tagtable_create`) \u2192 **tags** (`tia_tag_create`) \u2192 **constants**.\n7. **UDTs first** (`tia_types_import`), **then** blocks that use them.\n8. **Blocks** \u2014 the FB comes with its logic: `tia_source_put` (SCL) or `tia_import_xml` (LAD/FBD/GRAPH), Gd6 format\n routing (`tia_fb_create` only makes an empty FB shell); then its instance DB (`tia_instancedb_create`).\n9. **Compile** (`tia_compile`) \u2014 the verifier; only `Error` blocks. It compiles the **software**\n scope (not just the CPU device item), so it makes freshly-generated blocks consistent and, in\n most cases, **regenerates** any instance DB left inconsistent by an FB interface change.\n **Recompile first**; only if the DB still reports inconsistent after a compile, delete it\n (`tia_block_delete`), recreate it (`tia_instancedb_create`) and recompile.\n\n**The PlcSoftware name.** TIA names the PlcSoftware of a CPU created through `tia_device_create` or `tia_spec_apply` after the CPU device item (default `PLC_1`), not the device, so `plc` in steps 6-9 is the name from `tia_plcs`. The spec plan carries `{plc}`; `tia_spec_apply` resolves it after the device step (`plc.resolve` in `applied`) and stops with kind `plc_unresolved` rather than guess. `devices[].plcName` names the CPU item.\n\n## Recipe \u2014 edit an existing block or type without overwriting a newer change (stale-write guard)\n\nRead it with `tia_export_block` (block) or `tia_export_type` / `tia_type_source` (type) and keep its `contentHash`: `contentHash`, `normalizedSha256` and `sha256` are different hash contracts over different normalizations, so never substitute one for another and pass only the `contentHash` of a fresh read as `expectedContentHash`. Edit, then write it back with `tia_import_xml`, `tia_source_put` or `tia_types_import` passing `expectedContentHash:<that contentHash>` (one object per write); on `state_changed` NOTHING was written \u2014 re-read, merge your edit onto the current content and retry with the new `contentHash`; a guarded write never compiles, so a block that is not consistent is refused with `409 inconsistent` (NOTHING written) \u2014 `tia_compile`, re-read with `tia_export_block` for the current `contentHash`, retry; an object whose current export is not well-formed XML has no hash (its read answers `contentHashError` instead of `contentHash`) and a guarded write over it is refused with `409 unverifiable` (NOTHING written) \u2014 repair or re-export it in TIA Portal, or retry WITHOUT `expectedContentHash` (an unguarded write); a verified write returns `contentGuard`.\n\n## Recipe \u2014 unlock a freshly-created CPU so it compiles clean (VERIFIED V21, firmware-dependent)\n\nA bare CPU added via Openness may fail `compile` with **protection** errors: the\n*confidential-PLC-configuration-data* password is unset, the *communication certificate*\ncan\'t be generated without it, and (on newer firmware) the *access control* defaults to a\nprotected level needing a password. **The recipe differs by CPU family/firmware \u2014 there is\nno single universal form.** Fix, in order:\n\n**Tell the human first.** The recipe lowers the CPU\'s protection in the project: it sets the\nconfidential-configuration password (typed by the human) and then either sets the access level\nto **Full access** (S7-1500) or turns access control **off** (S7-1200, FW V4.5+). The CPU runs\nwith that protection after the next download. Name these changes when you ask for the password\nand list them in the report; the human may pick a stricter level in the TIA GUI before deploying.\n\n**(1) Confidential-data password \u2192 also auto-generates the certificate** (common to both\nfamilies):\n\n```\n# find the CPU device-item handle:\ntia_obj_roots -> the device handle (role:"device")\ntia_obj_items { handle:<device>, composition:"DeviceItems" } -> the CPU item handle\n# acquire the service ON THE CPU MODULE (not the rack) and invoke Protect:\ntia_obj_service { handle:<cpu>, type:"Siemens.Engineering.HW.Features.PlcMasterSecretConfigurator" } -> <svc>\ntia_obj_invoke { handle:<svc>, name:"Protect", args:["<password>"] }\n```\n\n**(2) Clear the access-control error \u2014 pick the variant for the CPU\'s family/firmware:**\n\n- **S7-1500 V2.9** (verified 2026 on real hardware \u2014 a 1516-3 V2.9, 3 errors \u2192 0): set\n `PlcProtectionAccessLevel = "FullAccess"` **on the CPU device item**:\n\n ```\n tia_obj_set_attributes { handle:<cpu>, attributes:{ "PlcProtectionAccessLevel":"FullAccess" } }\n ```\n\n- **S7-1200 V4.7** (new security model, FW \u2273 V4.5; per `docs/HARNESS-KNOWLEDGE.md` \xA72,\n runtime-observed): set `PlcAccessControlConfiguration = "Disabled"` on the\n **`PlcAccessControlConfigurationProvider`** SERVICE \u2014 not a direct attribute on the CPU\n item:\n\n ```\n tia_obj_service { handle:<cpu>, type:"Siemens.Engineering.HW.Features.PlcAccessControlConfigurationProvider" } -> <svc2>\n tia_obj_set_attributes { handle:<svc2>, attributes:{ "PlcAccessControlConfiguration":"Disabled" } }\n ```\n\n \u26A0\uFE0F **The two variants are mutually exclusive \u2014 the wrong one returns HTTP 500 on the\n other family:** `PlcAccessControlConfiguration` isn\'t on a 1500\'s CPU item, and\n `PlcProtectionAccessLevel` isn\'t the right model on a 1200 V4.7 item. Detect the\n family/FW \u2014 or the compile-error signature \u2014 before picking a variant.\n\n- **S7-1200 V4.0** (old security model): nothing to do here \u2014 the same bare-CPU condition\n is only a **WARNING**, not an error; a plain `tia_compile` already returns `errors: 0`.\n\nThen `tia_compile` \u2192 `state: Warning, errors: 0` (any remaining warnings \u2014 e.g. CPU-display\npassword \u2014 are benign and do **not** block; Gd8).\n\n> **Requires the `tia_obj_service` tool** (acquire `GetService<T>` \u2192 handle) for step 1 and\n> for the S7-1200 V4.7 variant of step 2. Without it the MCP cannot run either.\n\n### Policy \u2014 who supplies the confidential password\n\n`Protect()` sets an **offline project** password (it is not the online master secret / G6), but\nit protects confidential configuration data, so **the human supplies it, every time** (the\nrecommended policy, pending the product owner\'s confirmation): the project-spec has no field\nfor it, and a skill never invents, defaults, stores or logs it. The online master secret (`tia_mastersecret_set`, G6) is **always**\nhuman-supplied too.\n\n## S7 connection precondition (G2)\n\n`tia_connection_create` needs **\u2265 2 CONSISTENT CPUs** (both compile clean). Two *bare* CPUs\nnever form a valid S7 connection \u2014 apply the protection recipe + `tia_compile` to make each\nconsistent first, then create the connection. Use `tia_connections_diagnose` on failure.\n\n## Recipe \u2014 bump the project firmware **in-place** (keeps the program) (VERIFIED, V21 / S7-1200 1214C)\n\nBumped a project **V4.0 \u2192 V4.4** on a real S7-1200 1214C **without losing blocks or tags**\n(verified 2026-06-07). Use this for **auto-FW-match**: align the project to the firmware\nactually read from the CPU. `DeviceItem.ChangeType(typeIdentifier)` changes the item type\nin place and **preserves the software** \u2014 it does **not** require delete/recreate.\n\n```\n# archive first (see the warning below), then change the CPU\'s type to the SAME MLFB with the target /V<fw>:\ntia_device_change_version { plc:"<plc>", typeIdentifier:"OrderNumber:6ES7 214-1HG40-0XB0/V4.4" }\n# then recompile \u2014 a regenerated FB may need a fresh compile before download:\ntia_compile { ... }\n```\n\n(`tia_device_change_version` runs `ChangeType` on the CPU item for you; the raw form, `tia_obj_invoke`\nwith `name:"ChangeType"` on the CPU item handle from `tia_obj_roots` / `tia_obj_items`, does the same.)\n\n- **Rule: `project FW \u2264 device FW`** \u2014 never set the project firmware **higher** than the physical\n device\'s (download would be rejected). Bumping the project *up to* the device FW is the safe move.\n- Keep the **same MLFB**, swap only the `/V<fw>` suffix. The program (blocks/tags) survives.\n- After `ChangeType` the CPU/blocks can be inconsistent; **always recompile** before any handoff.\n- **\u26A0\uFE0F `ChangeType` RESETS GUI-gated comm settings** (runtime-validated on the 1214C): it **disabled\n the OPC UA server** (`OpcUaServer`\u2192`false`) and **cleared the OPC UA runtime-license** selection\n (the custom server interface and PUT/GET *survived*). So **`tia_project_archive` first** on a CPU\n with hand-configured OPC UA/PUT-GET, and **re-verify after**. Recovery: `tia_obj_set_attributes\n {handle, attributes:{OpcUaServer:true}}` on the "OPC UA" device-item (it **is** writable; re-select the license in the\n GUI). `ChangeType` to the **same** version is rejected ("Cannot change the type of the device item").\n\n## Recipe \u2014 enable a **Modbus TCP server** (`MB_SERVER`) on the S7-1200 (VERIFIED, FW V4.0)\n\nLets an external client (e.g. a Node backend) read/write the CPU over **Modbus TCP, port 502**\n(verified 2026-06-07; full backend/app detail in `docs/COMM-SCENARIOS.md`).\n\n1. **Non-optimized DB with an `Array of Word`** for the holding-register block (`MB_HOLD_REG`).\n Modbus needs a byte-addressable (non-optimized) DB \u2014 optimized access won\'t map.\n2. **On FW V4.0 use `MB_SERVER` V1.x**, which takes **`CONNECT_ID` + `IP_PORT`** parameters\n (**not** `CONNECT`/`TCON`, which the newer instruction versions use). Pin the instruction\n version when generating the FB.\n3. Instantiate `MB_SERVER` as a **multi-instance inside an FB** (its instance lives in the FB\'s\n instance DB), call it cyclically.\n4. **Map a holding register \u2192 a command tag** (e.g. `MB_HOLD_REG[0]` \u2192 `LedCmd`), so writing the\n register drives the output.\n\n> **Instance-DB gotcha (the big one):** when you regenerate the FB via `tia_source_put`, the\n> existing **instance DB** can go inconsistent (its interface no longer matches the FB).\n> **Recompile first** \u2014 a software-scope `tia_compile` regenerates the instance DB in most cases.\n> Only if it still reports inconsistent after a compile (typical when the interface was edited via\n> source), delete + recreate it, then recompile:\n>\n> ```\n> tia_compile { ... } # try first\n> tia_block_delete { ... the stale instance DB ... } # only if still inconsistent\n> tia_instancedb_create { ... fresh instance DB for the FB ... }\n> tia_compile { ... }\n> ```\n>\n> (Matches the \xA7Pipeline note: recompile first, delete+recreate only as the fallback.)\n\n## Recipe \u2014 enable **S7 / PUT-GET** on the S7-1200 (port 102)\n\nLets an external S7 client (e.g. `nodes7`) read/write the CPU over **S7comm, port 102**.\n\n1. For a fresh CPU, ask the human to enable PUT/GET: *Properties \u2192 Protection & Security \u2192\n Connection mechanisms \u2192 "Permit access with PUT/GET communication"*. No direct setter was\n verified on the 1214C V4.4. Alternatively, `tia_device_from_mastercopy` inherits this\n permission from an owner-prepared station; do not script the GUI.\n2. **Non-optimized DB** for the data the client touches (PUT/GET addresses absolute offsets, so\n the DB must be byte-addressable / non-optimized).\n3. Compile + download as usual; the client then reads/writes the DB by area+offset.\n\n## Recipe \u2014 enable **OPC UA** on the S7-1200 (port 4840)\n\nLets an external OPC UA client read/write the CPU over **OPC UA, port 4840**.\nUse the manual sequence for a fresh CPU, or clone an owner-prepared station as described below.\n\n**Prerequisite \u2014 firmware \u2265 V4.4.** OPC UA server isn\'t available on V4.0. If the project is on\nan older FW, bump it in-place first (see *bump the project firmware in-place* above \u2014\n`ChangeType` to `.../V4.4`).\n\nFor a fresh CPU, step 1 is scriptable; steps 2\u20133 require human configuration:\n\n1. **Activate the OPC UA server** \u2014 *Properties \u2192 OPC UA \u2192 Server* (enable). *(This step **is**\n scriptable via Openness: `tia_obj_set_attributes {handle, attributes:{OpcUaServer:true}}` on the "OPC UA"\n device-item \u2014 it auto-generates the server certificate.)*\n2. **Select the runtime license** \u2014 *"SIMATIC OPC UA S7-1200 Basic"* (Runtime licenses).\n3. **Create a server interface** (type **Interface**) and drop the **`ModbusData.HR` array**, not the\n DB or separate elements. The S7-1200 does not auto-expose DBs. Browse the resulting node IDs.\n\n**Finding the node IDs (client side):** browse `ns=3;s=ServerInterfaces` with any OPC UA client;\nthe actual data nodes show up under **`ns=4`**. Use those node IDs from the backend.\n\n**Prepared-station path (V21 / 1214C V4.4):** capture the configured source with\n`tia_library_mastercopy_create`, then `tia_device_from_mastercopy {masterCopy}`. This creates a new\nstation, preserving PUT/GET, selected runtime license and the HR interface; it is not an existing-CPU\nsetter or a license grant. TIA may rename the new PLC. Certificates are not copied: inspect its\n"OPC UA" item; `OpcUaServer:false` then `true` regenerated the certificate in the measured clone.\nCompile, save/reopen and check the exported HR mappings before any human-gated download.\nThe GUI type **Interface** is exposed as `SimaticInterface` (Export/Delete, no Import);\n`ServerInterface.Import` did not reproduce its HR mapping. See `tia_guide {"topic":"gui-gates"}`.\n\n## Recipe \u2014 WinCC Unified HMI: read, then guarded writes\n\nOnly for a WinCC **Unified** HMI (`tia_hmis` \u2192 `kind:"unified"`). A Classic HMI answers `409 hmi_not_unified`; use the screen export/import there. Everything below is offline (M-off): it edits the project, never the panel or the PLC.\n\n1. **Read first.** `tia_hmis` for the HMI name, then `tia_hmi_tag_tables`, `tia_hmi_tags` (`table`), `tia_hmi_alarm_classes`, `tia_hmi_alarms` (`kind`: `discrete`|`analog`) and `tia_hmi_connections`. Every read pages (`limit` 1..1000, `cursor`): follow `nextCursor` UNCHANGED, and on `cursor_stale` restart from the first page. Read `inventoryGaps` too: a non-empty list means a value reads `null` because Openness refused it, so do not write on the strength of that value.\n2. **Baseline.** `tia_hmi_validate` (scope `all`, or `tags`/`alarms`/`connections`/`screens`) aggregates the per-object `Validate()` results into `errors`, `warnings` and `findings`. Unified has NO compile: a clean validate is not a clean compile, and it can be slow (Long).\n3. **`dryRun:true` on EVERY write first** (`tia_hmi_tag_table_create|delete`, `tia_hmi_tag_create|update|delete`, `tia_hmi_alarm_create|update|delete`). The plan runs the same guards as the real call and changes nothing; repeat without `dryRun` only when it answers `plan_ok`. The real answer carries `postcheck` (`verified:true`, `requested` equal to `actual`). `409 postcheck_failed` is NOT a success: read the object again before going on (`rollback` says what was undone; a delete is never rolled back).\n4. **What the guards enforce \u2014 fix the cause, do not retry the same call.** Names: letters, digits and `_`, starting with a letter or `_` (tag tables may also hold spaces and `-` inside), at most 128 characters (`invalid_name`), unique ignoring case (`name_collision`). `dataType` is an allow-list: Bool, Byte, Char, DInt, DWord, Int, LInt, LReal, LWord, Real, SInt, String, UDInt, UInt, ULInt, USInt, Word, WChar, WString, DateTime, Time (`invalid_data_type`). A tag without `connection` is internal and needs `dataType`; with `connection` it is external and takes exactly one of `plcTag` or `address`. A PLC-bound tag needs a `plcTag` that EXISTS in the connected PLC (`plcName` when the connection\'s partner does not resolve to one PLC): `plc_unresolved` / `reference_not_found` mean fix the link, never invent a tag. A PLC tag whose own name contains a dot or a bracket is sent as ONE quoted token (`"A.B"`, `"Valve[1]"`): unquoted, `A.B` is member `B` of data block `A` and `Valve[1]` is an indexed name, so the call is refused. A discrete alarm needs an existing `alarmClass` and `triggerTag` and a `triggerBit` inside the width of the tag\'s type (Bool: 0, Word: 0..15; `trigger_bit_out_of_range`); an analog alarm has ONE `condition` and ONE `conditionValue` on a numeric tag (no limit ordering exists), and the value must fit the type (`condition_value_out_of_range`).\n5. **Alarm values, event text and what a read shows.** TIA stores the condition value of an alarm as a double: on an `LInt`, `ULInt` or `LWord` trigger tag a whole `conditionValue` above 2^53 in absolute value is refused `409 condition_value_out_of_range` (a `dryRun` too, nothing written); 2^53 itself is accepted, sent as a string, and `Real` and `LReal` values are always JSON numbers. `eventText` is PLAIN single-paragraph text per active project language: the serve wraps it as the rich text TIA stores (`<body><p>\u2026</p></body>`) and escapes `&`, `<` and `>`, so send no markup; a line break, an XML-invalid character (a tab is allowed), an unpaired surrogate, a blank text or more than 1024 characters is `400 bad_request`, and a text cannot be cleared by a write. A read answers the plain text (an event-text item without text is `""`, a language without an item `null`; any other markup comes back as raw rich text, which cannot be written back). TIA\'s placeholders read as `null`: an internal tag has `connection`, `plcName`, `plcTag`, `address`, `accessMode`, `acquisitionMode` and `acquisitionCycle` all `null` (TIA reads its connection back as a placeholder such as `<Internal tag>`), and an alarm class without a common class has `commonAlarmClass` `null` (`<No alarm class>`). The attribute list of an alarm itself is never read: `hmi_attribute_list_unavailable` and `hmi_attribute_not_writable` apply to tags and to the event text item of each culture (its list unreadable, `Text` not writable, or no item for that language), never to another alarm attribute.\n6. **Deleting.** A tag, or a tag table that holds one, is refused with `tag_in_use` while an alarm references it; a non-empty table needs `recursive:true` (`tag_table_not_empty`); the default table is refused. References from screens, scripts and logging are NOT scanned, so run `tia_hmi_validate` again after a delete.\n7. **Finish** with `tia_hmi_validate` and compare `errors` and `findings` with the baseline.\n\nLimits to remember: a **create\'s `dryRun` cannot check writability** (a `plan_ok` can still end in `hmi_attribute_not_writable`, after which the new object is removed again); an **update checks only what it changes** (a tag change against the stored bit or value, a connection change against its link), never a reference it leaves alone, and never switches a tag between `plcTag` and `address` \u2014 `tia_hmi_validate` finds a dangling carried reference; send a whole `conditionValue` as a **JSON integer or a string** (`5.0` and `1e3` are refused, and so is a whole value above 2^53 on an `LInt`, `ULInt` or `LWord` tag: step 5); a system tag may be an alarm trigger tag; `tia_hmi_validate` is Long, so it may answer `status:"running"` with a `jobId`: follow `tia_job_status` and never repeat the call.\n\nNo tool creates an HMI connection: when `tia_hmi_connections` is empty, PLC-bound tags cannot be created \u2014 ask the human to create the connection in TIA Portal.\n\n## Recipe \u2014 diff a project against a VCI workspace, or round-trip a block through a new one\n\nA VCI workspace is a folder on the serve host that mirrors project objects as files, so a diff tool or git can version\nthem. VCI takes **leaf objects only** (PLC blocks, PLC data types, tag tables): a device, a PLC, a group or the library is\nrefused with `409 vci_not_leaf` before VCI is called. Every write takes `dryRun:true` first (Gd11), a call holds at most 50\nobjects, and a batch is NOT a transaction: it stops at the first failure.\n\n**(1) A workspace that already has mapped objects is a baseline: its diff is READ-ONLY.**\n\n```\ntia_vci_workspaces -> `mappedObjects` above 0: a baseline exists\ntia_vci_status { workspace:"WS_1", limit:100 } -> follow nextCursor until it is null\n```\n\nClassify every row. `equal` is the only verified match. `projectChanged` (the project object changed), `workspaceChanged`\n(the file changed), `conflict` (both), `workspaceFileMissing` (the file is gone) and `unequal` (a difference of unknown\nside) are differences: report each by name, they are the result, not something to repair. `unknown`, `unsupported` and\n`statusFailed` prove nothing, neither equality nor a diff: report them by name, and the diff is NOT complete. **Never\nexport or import just to make a comparison equal.** `tia_vci_export` over a mapped object REPLACES its workspace file\nwith the project content (the plan says `action:"synchronize"`) and `tia_vci_import` replaces the project object with\nthe file, so either one destroys the difference you were asked to see. Refreshing the baseline is an explicit decision\nof the human: name the objects, ask, and only then export with `dryRun:true` first and read which files the plan\nreplaces.\n\n**(2) A NEW workspace, or new objects: export, then prove it.**\n\n```\n(a) tia_vci_workspaces -> reuse a workspace that is listed\n # none yet: ask the HUMAN for the root folder on the serve host. Never choose or invent a rootPath.\n tia_vci_workspace_create { name:"WS_1", rootPath:"<the folder the human gave>", dryRun:true }\n tia_vci_workspace_create { name:"WS_1", rootPath:"<the same folder>" } -> created | reused\n(b) tia_vci_export { workspace:"WS_1", objects:[{ kind:"block", name:"FB_Motor" }], dryRun:true }\n tia_vci_export { workspace:"WS_1", objects:[{ kind:"block", name:"FB_Motor" }] } -> the file(s) written\n(c) tia_vci_status { workspace:"WS_1", limit:100 } -> follow nextCursor until it is null\n(d) tia_export_block { plc:"PLC_1", block:"FB_Motor" } -> contentHash\n tia_block_set_attribute { plc:"PLC_1", block:"FB_Motor", name:"HeaderAuthor", value:"<a new text>" } -> an edit IN PLACE: the mapping survives\n tia_block_compile { plc:"PLC_1", block:"FB_Motor" }\n tia_export_block { plc:"PLC_1", block:"FB_Motor" } -> a DIFFERENT contentHash\n tia_vci_status { workspace:"WS_1", limit:100 } -> that row is now projectChanged\n(e) tia_vci_import { workspace:"WS_1", objects:[{ kind:"block", name:"FB_Motor" }], dryRun:true }\n tia_export_block { plc:"PLC_1", block:"FB_Motor" } -> a fresh contentHash\n tia_vci_import { workspace:"WS_1", objects:[{ kind:"block", name:"FB_Motor", expectedContentHash:"<fresh>" }] }\n tia_export_block { plc:"PLC_1", block:"FB_Motor" } -> the import REPLACED the project object: read it again by name\n tia_vci_status { workspace:"WS_1", limit:100 } -> that row is equal again\n```\n\n- **(b) Read the plan.** `action:"export"` creates a new file; `willCreateDirectory:true` on an object means the serve will\n create its target folder (the first export into a fresh workspace has none yet), and the dry run creates nothing. An\n object the plan lists as `synchronize` is already\n mapped and its file would be REPLACED: stop and go back to (1). `format` chooses the file format of an UNMAPPED object\n only (leave it out unless the serve answers `400 bad_request` with `details.supportedFormats`); a mapped object keeps its\n mapping\'s format and the selector is neither applied nor validated for it.\n- **(b) A `skip` is not a write.** An object the plan lists as `skip` (`reason:"already_equal"`) is already mapped and its\n status is `equal`: TIA refuses to synchronize an equal mapping, so the serve writes nothing for it and the answer lists it\n as `skip`.\n- **(c) Verify an export.** Every row of every page must be `equal`. Read `coverage` on EVERY page: `summary` and\n `coverage` describe only the rows of that response (the serve compares only the rows of the page), so fold them over all\n pages before saying the workspace is in sync. `409 cursor_stale` (a mapping appeared or went) restarts the walk once.\n- **(d) Edit the project IN PLACE, never by regenerating.** A block attribute (`tia_block_set_attribute`, a header attribute such as `HeaderAuthor`) keeps the project object, so its mapping stays and the row becomes `projectChanged` (measured on V21). If `tia_export_block` shows the same `contentHash` afterwards, that attribute is not part of the exported XML: try another header attribute (`HeaderFamily`, `HeaderName`). `tia_source_put` (regenerating the block from SCL) REPLACES the project object, and V21 DROPS its VCI mapping (measured): the row vanishes from `tia_vci_status` and `tia_vci_import` answers `409 not_mapped`, which is the correct answer, not a fault; `tia_import_xml` over an existing block replaces it the same way (not measured separately). Export the new object again to map it: `tia_vci_export` is refused `409 vci_path_collision` (`reason:"file_exists"`) while the old workspace file is still in the folder, so ask the human to remove or move that file first; on a baseline you were asked to diff, report the dropped mapping instead of exporting over it.\n- **(d) What a row says.** Only `equal` is a match. After a human edits a workspace file its row should show\n `workspaceChanged`; a row that still says `equal` after a known edit means the status is not live (V21 has no refresh\n call): say so and treat the check as NOT verified.\n- **(e) Read the plan before importing, and read the hash per kind.** The dry run shows per object `statusBefore` and\n `overwritesProjectChanges` (`true` for `projectChanged` and `conflict`: the import discards an edit that exists only in\n the project, there is no undo, so ask the human). An object that is already `equal` is skipped. The hash reader depends\n on the kind: a block uses `tia_export_block`, a type uses `tia_export_type { plc:"PLC_1", type:"UDT_Motor" }`, and a tag\n table has NO hash (the serve and the MCP refuse `expectedContentHash` for it), so rely on the dry run and the postcheck.\n A wrong `expectedContentHash` is `409 state_changed` and nothing was written.\n- **(e) A refused file, a changed attribute.** A workspace file that TIA refuses (an SD parser error, a corrupted resource\n file) is `400 bad_request` with TIA\'s text and nothing changed: fix the file, never retry it unchanged. A postcheck whose\n `attributeChanges` lists the `SecondaryType` or `Number` of an OB, or `IsOnlyStoredInLoadMemory`, `IsWriteProtectedInAS`\n or `DBAccessibleFromOPCUA` of a data block, means TIA changed the object while importing it (a SIMATIC SD import does):\n the object WAS written, so report the before and after and do not call the import done.\n- **An import REPLACES the project object.** After a real import the old object is disposed: a handle of it (`tia_obj_*`) and every value read before are stale, so re-read the block by name (`tia_export_block`, `tia_plc_blocks`) and then `tia_vci_status`. The serve does the same for its postcheck: an object it cannot find again by name, or whose mapping the replacement dropped, is `409 import_unverified` (the object WAS written). In a batch, an object that can no longer be found or mapped when its turn comes stops the batch there: `409 vci_batch_incomplete` naming it, or `409 conflict` when nothing was imported yet; nothing more is written.\n- **Verified only with a postcheck.** An import is done only when every imported object has `postcheck.verified:true`. Every\n other answer means it is NOT verified: `409 import_unverified` (the object WAS written, review it with `tia_export_block`\n or `tia_export_type`), `409 vci_batch_incomplete` (`done` lists the objects written and the skipped ones, `action: skip`, nothing written for them), a status row `unsupported`,\n `statusFailed` or `unknown`, `coverage.complete:false`, an omission marker that survives smaller `limit` retries, or a\n page walk that did not finish.\n- **Unknown outcomes.** `504 worker_restarted`, a `timeout` or a lost session during an export or an import leaves the\n outcome UNKNOWN or partial: walk `tia_vci_status` and re-read the object before repeating anything.\n- **Refusals before any write** (nothing changed): `vci_path_collision` (two objects, another mapping or an existing file\n share a target; `reason:"alias_unverifiable"` means the short 8.3 name of an existing file in the target folder could not\n be read, so a collision with its alias cannot be excluded), `vci_path_too_long`, `vci_mapping_outside_workspace` for an\n EXISTING mapping rejected in the plan, `not_mapped` (export it first), `workspace_file_missing`, `workspace_exists`,\n `workspace_root_in_use`, `workspace_ambiguous` (ask the human which workspace is meant) and `vci_inventory_incomplete`\n (the workspace inventory could not be read completely: report it and stop, never guess a workspace).\n- **`vci_mapping_outside_workspace` has TWO outcomes.** An existing mapping rejected in the plan changed nothing. After a\n NEW export the same kind means the file WAS written outside the workspace root: read its message and `details`\n (`object`, `directory`, `root`, `done`), report it, hand the cleanup to the human and never retry blindly.\n\n## Reference \u2014 global library and CAx error contracts (by app version)\n\n**Project library** (`tia_block_from_mastercopy`). A device copy is refused (`409 mastercopy_not_blocks` after app 1.6.3; up to 1.6.3 a 500).\n\n**Global libraries** (`tia_global_library_save` / `_close`). After app 1.6.3 a name that picks no single open USER library is refused, nothing saved or closed: `404 not_found` (`details.userLibraries` lists the names that work), or `409 conflict` for a read-only system/corporate library or a name several user libraries match only ignoring case; up to 1.6.3 the serve reports success even for an unknown name. A library opened read-only (`readWrite:false`) cannot be saved: `409 conflict` (`details.readOnly`) after app 1.6.3, a 500 up to 1.6.3 \u2014 close it and open it again with `readWrite:true` to change and save it.\n\n**CAx (AutomationML)** (`tia_cax_export` / `tia_cax_import`). A failed transfer is an error (`500 cax_transfer_failed`) after app 1.6.3; up to 1.6.3 the serve returns an opaque `result` even on failure \u2014 check the devices with `tia_devices`.\n\n## Reference \u2014 download plan fingerprint limits\n\n**Fingerprint limits** (`tia_download`): user program blocks, UDTs and tag tables only \u2014 no hardware configuration, system block groups, S7-1500 software units or technology objects; per-object fallback to modification dates (`source:"dates"`, warned in the plan \u2014 dates can false-positive `plan_stale`).\n\n## Recipe \u2014 generate the FAT/SAT I/O list (tia_io_map)\n\n**Generate the FAT/SAT I/O list** (`tia-verify` step 6). `tia_io_map` (`jobId` \u2192 `tia_job_status`), one\nlist per PLC, `limit:100`, `cursor` = previous `nextCursor` unchanged until null. Read `coverage` on every\npage; `cursor_stale` or differing coverage restarts once; omission marker: same call and cursor, half the\n`limit`, max 3 times, never follow its cursor. Rows: one per tag on a `channel`, or on a `range` with\nstatus `matched`; per unmatched `tag` entry; and (empty tag) per unmatched `channel` or channelless\n`range`; none for a `range` with status `channels`; a tag spanning channels: ONE row (`table`+`name`)\nlisting them; statuses `matched`|`unmatched`|`conflict` only. Unresolved channels/ranges and unparsed\ntags: "Could not be mapped". Print `coverage` numbers, `coverage.limits`, DERIVED addresses (spot-check in\nTIA). Complete ONLY after a finished walk with no marker left on ANY page and `coverage.complete: true`,\nsame counts, on every page; else start "NOT complete", say why. An unmatched tag is never\n"unused"/"orphan"; never invent, round or fix an address. Read-only; the human signs.\n\nLengths: a `range`\'s `start` is a byte number and its `length` is in BYTES (Openness reports an address length in bits and the map converts it, rounding up to whole bytes); `from` and `to` are its first and last bit (2 bytes from `%I0.0` end at `%I1.7`). `tia_device_tree` shows the raw Openness value, in BITS: convert before comparing the two.\n\n## Recipe \u2014 prove the project matches the versioned XML (tia_block_compare)\n\n**The project matches what\'s versioned \u2014 prove it, don\'t assume it.** A raw hash of an\nexport is NOT proof (two exports of the same block differ in `<Created>`/UIds). Use\n`tia_export_block` to pull a block inline and `tia_block_compare` to diff it against the\ncommitted XML (normalized \u2014 ignores formatting/BOM/`<Created>`; UIds are canonically renumbered,\npreserving wiring); `verdict:"equal"` is\nthe actual round-trip proof. After `tia_compile`/`tia_source_put`, read `blockChanges` and\nexport/commit any regenerated instance DBs before calling the project verified.\nComparison hashes (`normalizedSha256`) from older MCP builds that stripped UIds may change:\nrecompute stored comparison baselines.\n\n## Recipe \u2014 SIMATIC SD text: read, edit, create (tia_export_sd, tia_import_sd)\n\n`tia_export_sd` returns one block or type as `.s7dcl` code text and `.s7res` texts, with the same `contentHash`\nas `tia_export_block`/`tia_export_type`; `tia_import_sd` creates or replaces ONE object from them (the only SD route\nfor an object that does not exist yet; VCI updates mapped objects only). Run `dryRun:true` first and pass the fresh\n`contentHash` as `expectedContentHash`. Rules: an existing OB of any event class is refused (`sd_existing_ob_unsupported`: TIA\ngives every OB imported from SD a new number, a ProgramCycle OB 123 came back as OB 1): change it with `tia_export_block` +\n`tia_import_xml`, which keep its number and event class (a NEW OB can be created from SD); a global DB loses `IsOnlyStoredInLoadMemory`,\n`IsWriteProtectedInAS` and `DBAccessibleFromOPCUA`: read `changeImpact.dbAttributeChanges`, nothing is restored for\nyou (`IsOnlyStoredInLoadMemory` and `IsWriteProtectedInAS` can be restored with `tia_block_set_attribute`; a person sets\n`DBAccessibleFromOPCUA` again in TIA Portal, the block\'s properties, when that route refuses it: on V21 2100.0.121.1 its\n`400` `details.writable` omits it on an optimized global DB; then compile); comments only through `.s7res` (`//` inside a\nLAD/FBD network is refused; quote YAML values with `:` or `#`);\nFBD: a `wire#` consumer rung before its producer, every box output pin listed (an empty `et =>` is fine); TIA\nre-quotes some identifiers on export, so compare ignoring quotes. The object comes back inconsistent: compile it.\n\n## Reference \u2014 network, audit and CAx how-to\n\n**Network lifecycle.** `tia_subnet_delete` on a non-empty subnet is refused (`409 subnet_not_empty`); `disconnectNodes:true` disconnects its nodes and removes its IO systems. A subnet rename (`tia_subnet_update` `name`) takes at most 24 characters: a longer name is `400 invalid_subnet_name` (a `dryRun` too, nothing changed) although `tia_subnet_create` accepts longer names; a name equal to the current one is not a rename, and the serve counts UTF-16 code units, spaces included. PROFINET name (`tia_pn_name_set`): lower-case DNS labels (`a-z0-9-`) split by `.`, not an IP look-alike. A node in its default state (automatic name generation on, `PnDeviceName` read-only) takes a `name`: the serve switches auto-generation off first and writes the name second, and its `dryRun` cannot prove that the name becomes writable, so a `plan_ok` can still be followed by `409 pn_name_unsupported` from the real call; the serve then writes the previous auto-generation back and verifies it, the error ends with "Nothing was changed." only when that read-back confirmed it, and otherwise `409 conflict` names `autoGeneration` as NOT restored: re-read with `tia_device_network`. IO system first: `tia_io_system_create` on the controller, then `tia_io_system_connect` per device; `409 cross_subnet_assignment`: connect the device to that subnet (`tia_network_connect`) first.\n\n**Audit** (class R). Read blocks/types/tags via `tia_plc_*` and check the engineering baseline: optimized access, 100% symbolic, UDT-typed interfaces, FB + instance-DB, uniform naming. Scope `tia_crossrefs` with `target`/`kind` on a big project: a whole-PLC read can take minutes.\n\n**CAx (AutomationML).** `tia_cax_export` exports one device or the whole project; `tia_cax_import` takes `option`: `RetainTiaDevice` (default) / `OverwriteTiaDevice` / `MoveToParkingLot`.\n\n## Where to stop\n\nEverything above is **offline (M-off)**. `tia_download` / `tia_online` (G3/G4) are **not**\npart of scaffold \u2014 they belong to `tia-handoff` and require explicit human approval.\n';
29230
29231
  var SPEC_FORMAT = '# The project-spec (input model)\n\nA project-spec is ONE JSON document describing the whole project. Always run it\nthrough the pipeline front door: `tia_spec_validate` (rung 0, pure) \u2192 `tia_spec_plan`\n(dry) \u2192 `tia_spec_apply` (M-off, stops at gates).\n\n`tia_spec_validate` checks the shape only in part (it does not run the JSON Schema; the `spec-validate`\nskill adds it) and enforces: unique device/subnet/UDT/block/per-table tag names; every network node IP\ninside the subnet CIDR; `OrderNumber:<MLFB>/V<fw>` with `/V` \u2014 never `:V` (Gd5); no STL/GRAPH on an\nS7-1200; at most 8 SMs on an S7-1200 (its only module limit); and G5 \u2014 a spec with safety content\nmarked autonomous is REJECTED (F-logic is never autonomous).\n\nMinimal example:\n\n```json\n{\n "project": { "name": "Line2", "directory": "C:\\\\TIA\\\\Line2" },\n "conventions": {\n "namingScheme": "plcopen",\n "optimizedAccess": true,\n "symbolicOnly": true,\n "defaultLanguages": { "interlocks": "LAD", "algorithms": "SCL", "sequencers": "GRAPH" }\n },\n "devices": [\n {\n "name": "Line2_CPU",\n "typeIdentifier": "OrderNumber:6ES7 511-1AK02-0AB0/V2.9",\n "role": "cpu",\n "family": "S7-1500"\n }\n ],\n "network": {\n "subnet": { "type": "System:Subnet.Ethernet", "name": "PN_Line2", "cidr": "192.168.0.0/24" },\n "nodes": [{ "device": "Line2_CPU", "ip": "192.168.0.1", "createIoSystem": true }]\n },\n "dataTypes": [\n {\n "name": "UDT_Motor",\n "members": [\n { "name": "xStart", "dataType": "Bool", "comment": "Start command" },\n { "name": "rSpeed", "dataType": "Real", "comment": "Speed [%]" }\n ]\n }\n ],\n "tagTables": [{ "name": "IO", "purpose": "IO" }],\n "tags": [{ "table": "IO", "name": "Conv01_Run", "dataType": "Bool", "address": "%Q0.0" }]\n}\n```\n\nThe plan and `tia_spec_apply` neither import `dataTypes` nor author block logic: UDTs go in with\n`tia_types_import`, logic with `tia_source_put` / `tia_import_xml`.\n\nResolve every concrete MLFB + firmware via `tia_catalog` before building \u2014 never guess\nan order number. Project firmware must be \u2264 the physical device\'s firmware.\n';
29231
29232
  var FULL_GUIDE = [BRIEF, GATES_GUARDS, GUI_GATES, GOTCHAS, PIPELINE, RECIPES, SPEC_FORMAT].join("\n---\n\n");
29232
29233
  var CODEX_GUIDE = '# TIA Openness MCP \u2014 operating brief\n\nYou are driving Siemens TIA Portal V21 through the `tia_*` tools (an MCP over the TIA\nOpenness HTTP `serve`). This brief is ALWAYS in effect. For depth, call the `tia_guide`\ntool (topics: `gates-guards`, `gui-gates`, `gotchas`, `pipeline`, `recipes`,\n`spec-format`) \u2014 read the relevant topic BEFORE authoring blocks, changing hardware,\nor preparing a deploy. You are an assistant up to the gate, never an autonomous\ncommissioner.\n\n## Vocabulary (used across all tool descriptions)\n\n- **Class R** \u2014 read-only; safe anytime.\n- **Class M-off** \u2014 offline mutation (edits the project; never touches the physical PLC).\n- **Class GATE** \u2014 touches the physical world or a human-only decision; needs a human.\n- **G1..G7** \u2014 the GATES: G1 trust dialog, G2 S7-connection precondition (tool-enforced:\n both CPUs must compile clean), G3 download / CPU-STOP, G4 go-online (incl. station upload),\n G5 safety / F-logic (NEVER autonomous), G6 credentials \u2014 master secret, UMAC, upload /\n block / certificate passwords, password policy (from a human \u2014 never invented), G7 network\n scan. All except G2 are human-only \u2014 never crossed autonomously.\n- **Gd\\*** \u2014 tool-enforced GUARDS (preconditions the tools check), e.g. Gd5\n `OrderNumber:<MLFB>/V<fw>` format (slash before V, never `:V`), Gd8 only ERRORs block\n a compile (warnings don\'t), Gd9 clean compile before deploy, Gd11 dryRun-then-approve.\n\n## Non-negotiable rules\n\n1. **Serial only.** The serve owns ONE TIA Portal on ONE serial worker. Never fire\n concurrent `tia_*` calls; one hung Openness call can stall the whole serve.\n2. **Never cross a GATE autonomously.** A `requires_human_action` response is a HANDOFF,\n not an error: relay its `youMustDo`/`nextSteps` to the human verbatim, wait for their\n explicit yes, then resume exactly as instructed. Never self-approve a download; never\n invent a secret (G6); never author, modify or deploy safety/F logic (G5).\n3. **Long operations are jobs.** Long tools (connect, compile, download, upload,\n project create/save/archive, exports, CAx\u2026) may answer `status:"running"` with a\n `jobId` \u2014 the operation is STILL running on serve. Call `tia_job_status {jobId}`\n until it returns the final result; never repeat the original call. On `kind:"busy"`, poll\n `tia_job_status` only for a running job whose `jobId` is known (e.g. `details.jobId`).\n `tia_ping` probes `/health`: never busy, no job ID \u2014 use it for reachability only.\n Without a known running job ID, wait/recheck with `tia_status`; for `connect_incomplete`,\n follow the host-inspection handoff (`tia_guide {"topic":"gui-gates"}`), never retry connect.\n Offline tools (`tia_guide`, `tia_spec_validate`, `tia_spec_plan`, `tia_job_status`) never answer busy.\n4. **Compile before deploy.** `tia_compile` aggregates hardware + software and is the\n offline verifier: `errors:0` is the Gd9 precondition for download (G3) and for S7\n connections.\n5. **Follow the build pipeline order** (details: `tia_guide {"topic":"pipeline"}`):\n validate the spec (`tia_spec_validate`) \u2192 plan (`tia_spec_plan`) \u2192 scaffold\n (`tia_spec_apply` or the M-off tools) \u2192 verify (`tia_compile`) \u2192 human-gated deploy\n (`tia_download` with dryRun \u2192 human approval \u2192 `approved:true` + the same `planHash`).\n6. **Fresh CPUs may need GUI setup** (PUT/GET, OPC UA license/interface); a prepared station can\n inherit these via `tia_device_from_mastercopy`. Read `tia_guide {"topic":"gui-gates"}`.\n Missing settings are human handoffs, not retryable failures.\n7. **Prerequisites:** run the serve (`http://localhost:5000`; `tia_ping`). First\n connect per process may need G1; running/timeout alone are not G1 evidence.\n8. **Confirmation dialogs.** Where the client supports it, a gated call first asks the human in the client\'s dialog\n (elicitation); only the human answers it, and it never replaces dryRun \u2192 approval \u2192 `planHash`. `declined_by_human` /\n `cancelled_by_human` = refused, nothing sent: stop, no retry unless asked.\n9. **Size budget and paging.** A result holding `{"omitted":true,\u2026}` had that value cut out WHOLE by the MCP\'s size budget:\n repeating the same call returns the same marker, so follow its `hint` instead. Read large lists (`tia_plc_blocks`,\n `tia_plc_tags`, `tia_device_tree`) in pages: pass `limit`, then each `nextCursor` as `cursor` until it is `null`. A page\n with a marker has NO `nextCursor` (it would skip the omitted data): retry the same request with a smaller `limit`.\n `cursor_stale` means the project changed: restart from the first page (no `cursor`). Gate handoffs, plans and job\n envelopes are never cut. For XML too big for one result use `tia_export_xml` (it writes files on the serve host).\n\nSession start: `tia_ping` \u2192 `tia_status` \u2192 (if needed) `tia_start` / `tia_connect`.\nBefore the first build on a project: read `tia_guide {"topic":"pipeline"}` and\n`tia_guide {"topic":"gotchas"}`.\n\n**Tool names** are written bare (`tia_status`) here and in the skills. Claude Code shows them qualified:\n`mcp__plugin_tia-harness_tia__tia_status` (plugin; what a subagent `tools:` list needs) or\n`mcp__tia__tia_status` (standalone). Other clients may display them differently; the `tia_*` suffix\nis the tool.\n\n---\n\n# Gates vs guards\n\n## GATES vs GUARDS\n\n- **GATES (human-only \u2014 never auto-bypass):** trust dialog (**G1**), download / CPU-STOP\n (**G3**), go-online (**G4**, which includes a **station upload** (`tia_upload`): it goes\n online to read the CPU), network scan / accessible-devices (**G7**), master-secret/UMAC\n (**G6**, which includes a CPU **read-access password** for an upload, a block **know-how\n password** (`tia_block_protect`), a certificate file\'s password (`tia_certificate_import`)\n and the **password-policy** values (`tia_password_policy_set`)), **safety / F-logic\n (G5) \u2014 never autonomous**.\n- **GUARDS (tool-enforced preconditions):** compile-clean before deploy, consistency,\n dry-run\u2192approve, idempotency by name (advisory: re-runs do not converge), `OrderNumber:<MLFB>/V<fw>`\n format, serial-only.\n- Back up a physical CPU with the **`tia-backup`** skill (dedicated empty project; the upload\n token is bound to the project shown in the handoff).\n- **Picking the G3 download path (no gate, no scan):** `tia_pg_interfaces` lists the connection\n modes/PG-PC interfaces TIA already sees for the CPU (plus the OS status of each adapter) \u2014\n use it to fill `connectionMode`/`pcInterfaceName`/`targetInterfaceName` for `tia_download`\n instead of reaching for `tia_accessible_devices` (a real network scan, GATE G7).\n- **Fresh 1214C communication settings:** PUT/GET, OPC UA license and HR interface need a\n human source configuration; `tia_device_from_mastercopy` can inherit it into a new station.\n Server activation is scriptable: `tia_obj_set_attributes {handle, attributes:{OpcUaServer:true}}`.\n Details and certificate recovery: `tia_guide {"topic":"gui-gates"}`. Never script the GUI.\n\n**Deploy-time approval gates** (download / online / network-scan / secret / safety = **G3/G4/G7/G6/G5**)\nare a *different* class \u2014 see the **`tia-handoff`** skill. Those are "a human **approves an action**",\nnot "a human **clicks a GUI setting**". Both are human interaction points; surface them as\n`requires_human_action` with concrete guidance, never as a tool failure.\n\n---\n\n# GUI gates \u2014 expected human interaction points\n\n## Human interaction points (GUI gates) \u2014 EXPECTED, not an error\n\nExpected handoffs include trust, fresh-CPU setup and firmware-change recovery.\nOn the validated 1214C V4.4, no direct setter for PUT/GET, license selection or HR mapping was verified;\na **prepared station master copy inherits all three**. Do not blindly retry a missing setting: give the human the exact steps.\n\n| # | Signal you\'ll see | Why it\'s expected | Tell the human (exact GUI steps) |\n|---|---|---|---|\n| **G1 trust** | `EngineeringSecurityException` or a failed start with `details.cause:"trust"` \u2192 `requires_human_action` / `trust_dialog`. Neither `running` nor the 20-minute client timeout (`STARTING_UNCONFIRMED`) proves G1 or success. | First attach may prompt **per serve process**. | Human on the **serve host**: click **"Yes to all"** only on a visible trust dialog. While a job runs, poll `tia_job_status`; do not queue calls. A timeout does not cancel it: inspect the host, wait for completion before status/retry. After explicit G1 handoff, retry with `resumeToken`. For `TRUST_DIALOG_DENIED_OR_EXPIRED`, inspect `closedPids`/`stillRunningPids`/`unknownPids`: close only verified remaining TIA started by serve **with no open project**, then retry with a human ready. |\n| **OPC UA license** | `tia_compile` **ERROR**: *"The selected OPC UA license is not sufficient\u2026"* | No verified direct setter on this 1214C; a fresh project or firmware change can leave it unset | CPU \u2192 **Properties \u2192 General \u2192 Runtime licenses \u2192 OPC UA** \u2192 required **"SIMATIC OPC UA S7-1200 Basic"**; purchased \u2192 the license the owner declares for this CPU. Recompile. |\n| **OPC UA interface** | OPC UA client connects but the DB nodes aren\'t there (`ns=4` empty / no `ServerInterfaces`) | The validated **S7-1200** requires a configured server interface to expose DBs | CPU \u2192 **OPC UA communication \u2192 Server interfaces \u2192 Add new server interface** \u2192 type **Interface** \u2192 drop the **`HR` array** (`ModbusData.HR`), not the DB or individual elements. Recompile. |\n| **PUT/GET** | S7 client connects on port 102 but reads return access-denied | No verified direct setter on this 1214C | CPU \u2192 **Properties \u2192 Protection & Security \u2192 Connection mechanisms** \u2192 check **"Permit access with PUT/GET communication from remote partner"**. Compile + human-gated download (`hardware:true`). |\n| **FW-change reset** | After `tia_device_change_version`: OPC UA server off, the license error on compile, blocks `isConsistent:false` | `DeviceItem.ChangeType` **resets GUI-gated comm settings** (server activation + license); the interface & PUT/GET survive | `tia_project_archive` **before** the FW change. After: re-set `OpcUaServer:true` via `tia_obj_set_attributes` (scriptable), re-select the license (row above), recompile. |\n\n**Bounded connect:** `connect_incomplete` / `CONNECT_UNCONFIRMED` (`serve_host_inspection`)\nnames the last phase, not G1 or success. No cancellation or TIA kill: don\'t repeat or queue work.\nHuman: inspect the host and answer pending Siemens dialogs. If none is pending and unresponsive,\nsave stdout (CLI) or `%APPDATA%\\TIAOpenness\\startup.log` (tray, overwritten on launch),\nthen restart the **process** (tray: Exit/relaunch, not API Stop/Start).\nTIA may remain running: inspect it and verify project state before reconnecting.\nA finished MCP job carrying this handoff isn\'t connection proof.\n\n**Prepared station:** `tia_library_mastercopy_create {device}`, then `tia_device_from_mastercopy {masterCopy}`\nclones all three settings and HR mappings. Not an existing-CPU setter or license grant.\nCertificates are not copied: on the NEW "OPC UA" item, `OpcUaServer:false` then `true` regenerated one; compile afterwards.\nGUI type **Interface** maps to `SimaticInterface` (Export, no Import).\nThe separate `ServerInterface.Import` did not reproduce its HR mappings.\n\n**1214C/V21 bench, 2026-10-26:** `HR[0..2]` IDs in `ns=4`: HR array \u2192 `13,14,15`;\nindividual elements \u2192 `12,23,34`; whole DB \u2192 `14,15,16`.\nSelection/order affects IDs; probe after construction/import.\n\n---\n\n# Hard-won gotchas (runtime-validated)\n\n## Hard-won gotchas\n\n1. **Always compile before deploy.** `tia_compile` aggregates **hardware + software**; a\n **clean** compile (`errors:0`) is the precondition for download and for S7 connections.\n `tia_download` compiles too and leaves the project modified (`projectModified` in plan/result):\n save (`tia_project_save`) before switching projects; Openness does not say what changed.\n First download over another project\'s or TIA version\'s program: plan\n `allowUpgradeTargetDevice:true`, or a refusal may leave the CPU stopped (the plan cannot predict it).\n2. **One serial worker:** never concurrent `tia_*` calls; a hung operation may need a serve restart.\n3. **FB edits:** software-scope `tia_compile`; export regenerated DBs (`blockChanges`).\n Still inconsistent: `tia_block_delete` + `tia_instancedb_create`, recompile.\n **Global DB source put** re-creates it: `IsOnlyStoredInLoadMemory` resets\n (no source support; pragma ignored); nested starts need `BEGIN`.\n UDT put/`tia_types_import` did not reset DB values. Save XML/text/flags.\n Inspect `changeImpact.dbAttributeChanges`/`readGaps` (unknown; `trackChanges:false` opts out).\n Restore flag=true: `tia_block_set_attribute`, compile; starts: saved XML/text, not attributes.\n **N warnings then 0:** hardware compile produced OPC UA guest/unsecured + missing\n protection-level warnings; next skipped hardware. Check `messages[]` "Hardware configuration".\n4. **Firmware rule: project FW \u2264 device FW.** Bump the project FW **in-place** with\n `tia_device_change_version` (`DeviceItem.ChangeType`), which preserves the **program** \u2014 never\n set the project higher than the physical CPU. **\u26A0\uFE0F It RESETS GUI-gated comm settings** (the\n **OPC UA server activation** + **runtime-license**; the server interface and PUT/GET survive):\n **archive first** (`tia_project_archive`) on a CPU with hand-configured OPC UA, recompile after\n (it marks blocks inconsistent), and re-verify. Same-version `ChangeType` is rejected.\n5. **Use a NON-optimized DB** for Modbus (`MB_HOLD_REG`) and S7 (absolute addressing); OPC UA\n works with optimized or not.\n6. **Order numbers use `/V<fw>`, not `:V<fw>`** (guard Gd5).\n7. **A station upload (`tia_upload`) ADDS a new station to the open project \u2014 back up into a\n dedicated EMPTY project.** Bench (S7-1200 1214C, 2026-09-26): 0 \u2192 1 device in ~75 s, twice,\n with the CPU in RUN throughout. Protect the working project FIRST: `tia_project_create` closes\n it and is refused (`409 unsaved_changes`) while it has unsaved changes, so `tia_project_save` +\n `tia_project_archive` first (never `discardUnsavedChanges` to get past the refusal), with the\n archive `name` WITH the `.zap21` extension (absent or extension-less fails).\n **A V17 program does not upload into V21 (2026-10-31):** use the TIA version the program was\n made with. `upload_incompatible_version` is definite: check versions and `stationAdded` in\n `details`; a partial station is not a backup. Approval stays single-use.\n8. **One wrong know-how password can lock a block for the session.** Observed on the bench\n (2026-10-12): after one rejected unprotect (`tia_block_protect {protect:false}`), TIA refused\n the CORRECT password of that block for the rest of the session (cause not confirmed \u2014 possibly\n brute-force protection). Never retry with a guess \u2014 ask the human for the password (G6); if a\n password the human confirms is refused, stop and hand off instead of retrying.\n9. **`unsaved_changes` and `binding_conflict` are refusals, not faults: nothing was changed.**\n `tia_connect`, `tia_project_close`, `tia_disconnect` and `tia_project_create` answer\n `409 unsaved_changes` when the call would close a project with unsaved changes (the error lists\n each one). ASK the human; the recommended answer is to repeat the same call with\n `saveUnsavedChanges:true`. Pass `discardUnsavedChanges:true` (data loss) ONLY when the human\n explicitly decides to throw the work away, never to make the error go away (the client then asks\n the human to confirm in its own dialog; `declined_by_human` = nothing was sent, stop).\n `409 binding_conflict` means the project this session is bound to is no longer the one open in\n the bound TIA (closed, replaced or Save As done by hand; `tia_status` shows `boundProjectPath`\n and `bindingDrift`): ask the human which project is intended, then `tia_connect` with the bound\n path (back to it) or the open one (adopt it) \u2014 do not repeat the refused call first.\n10. **`503 audit_unavailable`: the serve could not write its audit log, so it refused the call BEFORE\n running (nothing reached the PLC).** Have the human fix the disk or permissions, then re-plan.\n An `auditWarning` in a response = the call ran but was not fully recorded: report it.\n\n## Prerequisites (environment)\n\n- The **`tia` serve must be running** (default `http://localhost:5000`, e.g.\n `TIAOpenness.exe serve 5000`). The MCP is a pure HTTP client; point it at the serve host via\n `TIA_API_BASE` if it runs elsewhere.\n- The Windows user must belong to the **"Siemens TIA Openness"** local group.\n- A first connection per serve process may show a trust dialog; a human confirms it on the serve host. A slow start or timeout alone is not G1 evidence.\n\n---\n\n# The build pipeline (spec \u2192 verified project)\n\nTIA version preflight: `tia_guide {"topic":"recipes"}`, \'TIA version evidence and SimaticML\', before authoring.\n\n| # | Stage | Tool(s) | Class | What it does |\n|---|---|---|---|---|\n| 0 | Validate the spec | `tia_spec_validate` | R (pure) | Partial shape checks + the cross-field rules the tool implements: unique names, IP inside the subnet CIDR, Gd5 order-number format, no STL/GRAPH on S7-1200, the G5 safety rule, at most 8 SMs on an S7-1200. It does NOT run the JSON Schema or per-model module limits; the `spec-validate` skill covers both. Needs no serve. |\n| 1 | Plan | `tia_spec_plan` | R (pure) | Turns a VALID spec into the ordered list of M-off operations. Nothing mutates. |\n| 2 | Scaffold | `tia_spec_apply` (or the M-off tools manually) | M-off | Creates part of the project content in dependency order (scope below). Stops at every gate. |\n| 3 | Verify | `tia_compile` | M-off | THE offline verifier: aggregates hardware + software. Gd8: only ERRORs block. `errors:0` is the Gd9 precondition for any deploy. |\n| 4 | Handoff / deploy | `tia_download` | GATE G3 | `dryRun:true` verifies compile, connection and software fingerprint \u2192 `planHash` \u2192 HUMAN approval \u2192 `approved:true` + SAME single-use `planHash`. Serve re-checks software (`plan_stale` if changed). Approval binds connection/options and covered software, NOT hardware: humans must confirm hardware has not changed since that dryRun; changed hardware needs a NEW plan and approval, never the old token. Fingerprint covers user blocks, UDTs and tag tables only; exclusions and `source:"dates"` fallback: `tia_guide {"topic":"recipes"}`, \'Reference \u2014 download plan fingerprint limits\'. Never self-approve; resolve connection via `tia_pg_interfaces` (no scan). |\n\nFor the first download over another project\'s or another TIA version\'s program, plan with\n`allowUpgradeTargetDevice:true`; without it, a refusal may leave the CPU stopped.\nThe offline plan cannot predict whether TIA will request that confirmation.\n\nFor the first download over another project\'s or another TIA version\'s program, plan with\n`allowUpgradeTargetDevice:true`; without it, a refusal may leave the CPU stopped.\nThe offline plan cannot predict whether TIA will request that confirmation.\n\nScaffold order (UDTs BEFORE the blocks that use them): by hand, `tia_guide {"topic":"recipes"}`, \'Pipeline order\'. `tia_spec_apply` automates only subnets, devices, modules, network, tag tables, tags, FB shells, control-module instance DBs and the compile; protection, constants, UDTs and all logic stay manual. The FB shells it creates are empty: add their logic with `tia_source_put` (SCL) or `tia_import_xml` (LAD/FBD).\n\nUse the PlcSoftware name from `tia_plcs`, not the device name.\n\n## The approval envelope (what a gate handoff looks like)\n\nGated tools return `status:"requires_human_action"` with:\n\n- `gate` \u2014 which gate (e.g. `download_approval`, `station_upload`, `go_online`, `trust_dialog`);\n- `youMustDo` \u2014 what the human must confirm, in plain words;\n- `plan` + `planHash` \u2014 exactly what would be executed (the hash binds the approval to\n this exact plan; a changed plan needs a new approval); the download\'s plan also carries\n `fingerprint` (the software content the plan was verified against \u2014 show it too);\n- `nextSteps` \u2014 how to resume after the human\'s yes.\n\nRelay the envelope to the human, wait for an explicit yes, resume exactly as\ninstructed. The AI never approves, never invents a secret, never deploys F-logic.\n\n**Confirmation dialog.** When the client supports elicitation, the crossing calls (`tia_download` with\n`approved:true`; `tia_upload`, `tia_online`, `tia_accessible_devices` with `confirm:true`) first ask the\nhuman in a dialog; clients without it behave as before. The dialog only checks the human\'s answer: the\n`planHash` and serve\'s approval token stay the authority.\nPasswords (G6) are never asked there. `declined_by_human` / `cancelled_by_human` = the human refused:\nnothing was sent, no retry unless asked. `elicitation_failed` (`isError`) = the dialog could not be\nshown or answered, nothing was sent (fails closed).\n\n## After scaffolding\n\n- Re-run `tia_compile` after ANY authoring change.\n- `tia_project_save` regularly; `tia_project_archive` BEFORE risky operations\n (firmware change \u2014 see `tia_guide {"topic":"gotchas"}`).\n- Auditing an existing project is class R (`tia_plc_*` reads); baseline: `tia_guide {"topic":"recipes"}`, \'Reference \u2014 network, audit and CAx how-to\'.\n- `tia_crossrefs` (R, Long; poll `tia_job_status` for `jobId`): `UnusedObjects` returns\n CANDIDATES, not proof (OBs, external-only uses and library TYPEs can look unused).\n Before edits, use `target`, `kind`, `filter:"ObjectsWithReferences"`; the human interprets\n TIA\'s `referenceType` (`Uses`/`UsedBy`) and `access`. Page containers/whole PLCs with\n `limit` + unchanged `nextCursor` until null. App 1.8+ caches whole-PLC walks until mutation/close/cursor expiry;\n older serves re-read pages. Read coverage on every page, not only the first:\n a later page can report less than an earlier one. On `cursor_stale`, restart from the first\n page; differing counts restart the walk once from the first page. On omission retry the same request with smaller `limit`,\n never its cursor. Claim complete/no uses ONLY after a finished walk with identical counts,\n no omissions and `coverage.complete:true` on EVERY page; else NOT complete\n (inspect `coverage.unavailableOwners`).\n- **FAT/SAT I/O list** (`tia-verify` step 6): `tia_io_map`; recipe: `tia_guide {"topic":"recipes"}`, \'Recipe \u2014 generate the FAT/SAT I/O list\'.\n- **Prove the project matches what\'s versioned** (a raw hash is NOT proof): `tia_guide {"topic":"recipes"}`, \'Recipe \u2014 prove the project matches the versioned XML\'.\n\n## Network lifecycle (subnets, PROFINET names, IO systems)\n\nRead first (`tia_subnet_get`, `tia_device_network`, `tia_io_systems`), then run each write\'s `dryRun` (answered by\nthe serve, needs an open project). Order, PROFINET names, `disconnectNodes`: `tia_guide {"topic":"recipes"}`, \'Reference \u2014 network, audit and CAx how-to\'.\n\n- **Refused, nothing changed:** `tia_subnet_delete` of a non-empty subnet (`409 subnet_not_empty`);\n `tia_io_system_connect` across subnets (`409 cross_subnet_assignment`: `tia_network_connect` the device to that subnet first).\n- **`409 postcheck_failed`:** the write did not take effect as asked: re-read, never repeat blindly.\n\n## Libraries, HMI, CAx and PLC security\n\nReads are class R; every change is class M-off (offline, with `dryRun`) and reaches the CPU\nonly through a later `tia_compile` + human-gated `tia_download` (G3). Every file path is a\npath ON THE SERVE HOST.\n\n- **Guarded PLC writes** (`tia_tag_update`, `tia_constant_update`, `tia_constant_delete`,\n `tia_tagtable_delete`, `tia_block_group_delete`, `tia_ob_create`, `tia_block_compile`): the serve\n answers their `dryRun` (it needs an open project) with the guard verdict (name collision, default\n tag table, non-empty group, singleton OB).\n- **Project library:** `tia_library_mastercopies` / `tia_library_types` read it;\n `tia_library_mastercopy_create` turns a DEVICE into a master copy (a block cannot be a source);\n `tia_device_from_mastercopy` inherits PUT/GET, OPC UA license selection and HR mappings into a NEW station; regenerate its certificate;\n `tia_block_from_mastercopy` needs one that holds PLC blocks.\n- **Global libraries** (in the TIA Portal session, not the project): `tia_global_libraries`,\n `tia_global_library_create` / `_open` / `_save` / `_close`; save/close take the name from\n `tia_global_libraries` (exact name first, then ignoring case). REFUSED, nothing saved or closed\n (`404 not_found` / `409 conflict`): a name that picks no single open USER library (unknown, read-only\n system/corporate, several matches ignoring case) and a save of a `readWrite:false` library. Up to app\n 1.6.3 an unknown name can report success without saving or closing anything: check `tia_global_libraries`.\n- **HMI:** `tia_hmis` and `tia_hmi_screens` read any HMI; screen files\n (`tia_hmi_screen_export`, `tia_hmi_screens_import`) work for WinCC **Classic** only, and the\n import OVERWRITES same-named screens.\n- **CAx (AutomationML):** `tia_cax_export` / `tia_cax_import` (scope, `option` values: recipes). Archive the\n project before an overwrite. A failed transfer is an error after app 1.6.3; on an older serve check the\n devices with `tia_devices`.\n- **Error contracts by app version:** `tia_guide {"topic":"recipes"}`, \'Reference \u2014 global library and CAx error contracts (by app version)\'.\n- **PLC security:** `tia_certificates` / `tia_certificate_template` / `tia_password_policy`\n read; `tia_certificate_import` / `_export` / `_delete`, `tia_password_policy_set` and\n `tia_block_protect` change the project. **G6:** a block or certificate password and the\n password-policy values come from a HUMAN \u2014 never invent, guess or reuse one; dryRun plans\n show a password as `[redacted]`. A CPU without the certificate manager or a policy service\n answers 409.\n- **Multiuser:** `tia_project_servers`, `tia_server_projects` read Project Servers; `tia_local_session_open` needs NO open project (`tia_project_close`, `tia_start`). Nothing is ever checked in.\n\n---\n\n# Recipes (runtime-verified)\n\nNot copied here: Codex reads at most 32 KiB of AGENTS.md and cuts the rest without a word. Call\n`tia_guide {"topic":"recipes"}` for the verified recipes (unlocking a freshly-created CPU, the in-place firmware\nbump, Modbus TCP, S7 PUT/GET and OPC UA on the S7-1200, the scaffold order) before you need one.\n\n---\n\n# The project-spec (input model)\n\nA project-spec is ONE JSON document describing the whole project. Always run it\nthrough the pipeline front door: `tia_spec_validate` (rung 0, pure) \u2192 `tia_spec_plan`\n(dry) \u2192 `tia_spec_apply` (M-off, stops at gates).\n\n`tia_spec_validate` checks the shape only in part (it does not run the JSON Schema; the `spec-validate`\nskill adds it) and enforces: unique device/subnet/UDT/block/per-table tag names; every network node IP\ninside the subnet CIDR; `OrderNumber:<MLFB>/V<fw>` with `/V` \u2014 never `:V` (Gd5); no STL/GRAPH on an\nS7-1200; at most 8 SMs on an S7-1200 (its only module limit); and G5 \u2014 a spec with safety content\nmarked autonomous is REJECTED (F-logic is never autonomous).\n\nMinimal example:\n\n```json\n{\n "project": { "name": "Line2", "directory": "C:\\\\TIA\\\\Line2" },\n "conventions": {\n "namingScheme": "plcopen",\n "optimizedAccess": true,\n "symbolicOnly": true,\n "defaultLanguages": { "interlocks": "LAD", "algorithms": "SCL", "sequencers": "GRAPH" }\n },\n "devices": [\n {\n "name": "Line2_CPU",\n "typeIdentifier": "OrderNumber:6ES7 511-1AK02-0AB0/V2.9",\n "role": "cpu",\n "family": "S7-1500"\n }\n ],\n "network": {\n "subnet": { "type": "System:Subnet.Ethernet", "name": "PN_Line2", "cidr": "192.168.0.0/24" },\n "nodes": [{ "device": "Line2_CPU", "ip": "192.168.0.1", "createIoSystem": true }]\n },\n "dataTypes": [\n {\n "name": "UDT_Motor",\n "members": [\n { "name": "xStart", "dataType": "Bool", "comment": "Start command" },\n { "name": "rSpeed", "dataType": "Real", "comment": "Speed [%]" }\n ]\n }\n ],\n "tagTables": [{ "name": "IO", "purpose": "IO" }],\n "tags": [{ "table": "IO", "name": "Conv01_Run", "dataType": "Bool", "address": "%Q0.0" }]\n}\n```\n\nThe plan and `tia_spec_apply` neither import `dataTypes` nor author block logic: UDTs go in with\n`tia_types_import`, logic with `tia_source_put` / `tia_import_xml`.\n\nResolve every concrete MLFB + firmware via `tia_catalog` before building \u2014 never guess\nan order number. Project firmware must be \u2264 the physical device\'s firmware.\n';
@@ -37434,6 +37435,7 @@ function resolveBudget(getEnv = (name) => process.env[name]) {
37434
37435
  var PAGING_HINT = "Call the same tool again with limit (1..1000) and pass nextCursor from each page as cursor to read the rest.";
37435
37436
  var PAGED_HINT = "The budget omitted data from this page, so any nextCursor was removed from it: following a cursor now would skip what was omitted. Retry the same request (the same cursor, or none for the first page) with a smaller limit, for example half of the one you used. Only follow a nextCursor from a page that arrives without an omission marker.";
37436
37437
  var EXPORT_XML_HINT = "The XML is too large for the response budget. sha256, normalizedSha256, contentHash (when the serve computed one) and bytes stay in this result. Use tia_export_xml to write the block/type XML files to a directory on the serve host (it returns file paths), or tia_block_compare (block) to check the block against a SimaticML file you already hold without returning XML, or raise TIA_MCP_MAX_VALUE_CHARS/TIA_MCP_MAX_RESPONSE_CHARS on the MCP. tia_export_xml and tia_block_compare are not registered when TIA_MCP_MODE=read-only: in that mode raise the two limits.";
37438
+ var EXPORT_SD_HINT = "The SD text is too large for the response budget. contentHash (when the serve computed one), s7dclBytes and s7resBytes stay in this result. Raise TIA_MCP_MAX_VALUE_CHARS/TIA_MCP_MAX_RESPONSE_CHARS on the MCP, or export the object to a VCI workspace file on the serve host (tia_vci_export, which is not registered when TIA_MCP_MODE=read-only: in that mode raise the two limits). An omitted s7dcl is not the object: do not import or compare it.";
37437
37439
  var CROSSREFS_HINT = "Call tia_crossrefs again with limit (1..1000) and pass the nextCursor of each page as cursor to read the sources page by page, or narrow the read with target, kind or filter. summary and coverage stay in this result. An omitted section is NOT complete: do not report the sources, an UnusedObjects list or any claim that nothing uses an object as complete from it.";
37438
37440
  var VCI_STATUS_HINT = "Call tia_vci_status again with limit (recommended 100, up to 1000) and pass the nextCursor of each page as cursor to read the objects page by page. summary and coverage stay in this result and describe the rows of the response, so fold them across every page of a paged read. An omitted section is NOT verified: do not report the workspace as clean, or any object as equal, from it.";
37439
37441
  var IOMAP_HINT = "Call tia_io_map again with limit (1..1000), starting at 100 to 200, and pass the nextCursor of each page as cursor to read the entries page by page. summary and coverage stay in this result. An omitted section is NOT complete: do not report the channels, the matched tags, the unmatched tags or a FAT/SAT I/O list as complete from it.";
@@ -37472,6 +37474,7 @@ var TOOL_HINTS = {
37472
37474
  tia_io_map: { unpaged: IOMAP_HINT, paged: PAGED_HINT },
37473
37475
  tia_export_block: EXPORT_XML_HINT,
37474
37476
  tia_export_type: EXPORT_XML_HINT,
37477
+ tia_export_sd: EXPORT_SD_HINT,
37475
37478
  tia_catalog: "Pass a more specific filter/typeIdentifier and keep verbose off.",
37476
37479
  tia_compile: "Compile one block with tia_block_compile, or read messages from the compile result summary."
37477
37480
  };
@@ -37774,6 +37777,7 @@ var tool_classes_default = {
37774
37777
  tia_disconnect: "M-off",
37775
37778
  tia_download: "GATE",
37776
37779
  tia_export_block: "M-off",
37780
+ tia_export_sd: "R",
37777
37781
  tia_export_type: "R",
37778
37782
  tia_export_xml: "M-off",
37779
37783
  tia_fb_create: "M-off",
@@ -37802,6 +37806,7 @@ var tool_classes_default = {
37802
37806
  tia_hmi_tags: "R",
37803
37807
  tia_hmi_validate: "R",
37804
37808
  tia_hmis: "R",
37809
+ tia_import_sd: "M-off",
37805
37810
  tia_import_xml: "M-off",
37806
37811
  tia_instancedb_create: "M-off",
37807
37812
  tia_instances: "R",
@@ -37906,6 +37911,7 @@ var tool_classes_default = {
37906
37911
  "tia_device_network",
37907
37912
  "tia_device_tree",
37908
37913
  "tia_devices",
37914
+ "tia_export_sd",
37909
37915
  "tia_export_type",
37910
37916
  "tia_global_libraries",
37911
37917
  "tia_guide",
@@ -38106,7 +38112,7 @@ function registerJobTools(server) {
38106
38112
  "tia_job_status",
38107
38113
  {
38108
38114
  title: "TIA \u2014 long-operation status",
38109
- description: 'Waits (up to waitSeconds, default 20, max 25) for a background job started by a long tool that answered status:"running" (tia_connect, tia_start, tia_show_ui, tia_project_create/save/saveas/close/archive, tia_compile, tia_source_put, tia_device_create, tia_import_xml, tia_types_import, tia_download, tia_upload, tia_export_xml, tia_export_block, tia_block_compare, tia_crossrefs, tia_io_map, tia_spec_apply, tia_cax_export/import, tia_hmi_screen_export, tia_hmi_screens_import, tia_hmi_validate, tia_global_library_create/open/save, tia_library_mastercopy_create, tia_device_from_mastercopy, tia_vci_status, tia_vci_export, tia_vci_import) and returns its FINAL result with job:{id,tool,state,durationMs} \u2014 including a gate handoff if the operation ended in one. While a job runs, every other serve-bound tool answers kind:"busy" (with details.jobId): call this instead of polling tia_status, and never repeat the original call. A lifecycle job that is still running may be starting or waiting for a trust dialog; running alone is not G1 evidence. Follow its conditional nextSteps, and ask a human to confirm G1 only if the dialog is visible on the serve host. Does not call serve. Class R.',
38115
+ description: 'Waits (up to waitSeconds, default 20, max 25) for a background job started by a long tool that answered status:"running" (tia_connect, tia_start, tia_show_ui, tia_project_create/save/saveas/close/archive, tia_compile, tia_source_put, tia_device_create, tia_import_xml, tia_types_import, tia_download, tia_upload, tia_export_xml, tia_export_block, tia_block_compare, tia_crossrefs, tia_io_map, tia_spec_apply, tia_cax_export/import, tia_hmi_screen_export, tia_hmi_screens_import, tia_hmi_validate, tia_global_library_create/open/save, tia_library_mastercopy_create, tia_device_from_mastercopy, tia_vci_status, tia_vci_export, tia_vci_import, tia_export_sd, tia_import_sd) and returns its FINAL result with job:{id,tool,state,durationMs} \u2014 including a gate handoff if the operation ended in one. While a job runs, every other serve-bound tool answers kind:"busy" (with details.jobId): call this instead of polling tia_status, and never repeat the original call. A lifecycle job that is still running may be starting or waiting for a trust dialog; running alone is not G1 evidence. Follow its conditional nextSteps, and ask a human to confirm G1 only if the dialog is visible on the serve host. Does not call serve. Class R.',
38110
38116
  inputSchema: {
38111
38117
  jobId: external_exports.string().describe("jobId returned by the long tool (or by a busy error's details.jobId)"),
38112
38118
  waitSeconds: external_exports.number().int().min(0).max(25).optional().describe("how long this call may wait (default 20, max 25)")
@@ -38563,10 +38569,7 @@ function registerReadOnlyTools(server) {
38563
38569
  "tia_instances",
38564
38570
  {
38565
38571
  title: "TIA \u2014 running instances",
38566
- description: (
38567
- // Stryker disable next-line StringLiteral: handoff prose, facts are tested
38568
- "Lists TIA Portal sessions exposed by Openness and native Siemens.Automation.Portal.exe processes on the serve host. Native-only rows include the PID with mode and project path set to null. Maps to GET /instances. Read-only (class R)."
38569
- ),
38572
+ description: "Lists TIA Portal sessions exposed by Openness and native Siemens.Automation.Portal.exe processes on the serve host. Native-only rows include the PID with mode and project path set to null. Maps to GET /instances. Read-only (class R).",
38570
38573
  inputSchema: {}
38571
38574
  },
38572
38575
  async () => getResult("/instances")
@@ -39190,9 +39193,8 @@ function startingUnconfirmedResult(err, operation) {
39190
39193
  kind: err.kind,
39191
39194
  status: err.status,
39192
39195
  type: err.type,
39193
- // Stryker disable next-line LogicalOperator: Client-created timeouts omit `inner` and TiaApiError defaults it to null; the serve emits no timeout kind.
39196
+ // A "timeout" kind is produced by the client, not the serve, so inner and details are null.
39194
39197
  inner: err.inner ?? null,
39195
- // Stryker disable next-line LogicalOperator: Client-created timeouts omit `details` and TiaApiError defaults it to null; the serve emits no timeout kind.
39196
39198
  details: err.details ?? null,
39197
39199
  hint: "The client timeout does not cancel the serve-side operation, so its serial worker may still be occupied. A timeout or reachable /health endpoint proves neither success nor G1.",
39198
39200
  nextSteps: [
@@ -40563,7 +40565,6 @@ var IGNORED_ALWAYS = [
40563
40565
  "indentation and blank lines (also inside multi-line <Text> comments, via a per-line trim)",
40564
40566
  "<Created> (export timestamp)",
40565
40567
  "<InstalledProducts> (TIA hotfix level and installed option packages)",
40566
- // Stryker disable next-line StringLiteral: ignored-field explanation; compare-wiring.test.ts covers the actual normalization
40567
40568
  "UId numbering (canonical first appearance across definitions and references; connectivity is preserved)"
40568
40569
  ];
40569
40570
  var IGNORED_FORMATTING = "<NewLine/> and <Blank/> structured-text formatting tokens";
@@ -42863,10 +42864,7 @@ function renderPseudoScl(xml) {
42863
42864
  }
42864
42865
 
42865
42866
  // src/tools/asCode.ts
42866
- var COMPARISON_HASH_NOTE = (
42867
- // Stryker disable next-line StringLiteral: comparison migration prose; compare-wiring.test.ts covers the hash behavior
42868
- "`normalizedSha256` now uses wiring-safe UId canonicalization: stored values may change; recompute comparison baselines."
42869
- );
42867
+ var COMPARISON_HASH_NOTE = "`normalizedSha256` now uses wiring-safe UId canonicalization: stored values may change; recompute comparison baselines.";
42870
42868
  var HASH_CONTRACT_NOTE = "`contentHash`, `normalizedSha256` and `sha256` are different hash contracts over different normalizations: never substitute one for another, and pass only the `contentHash` of a fresh read as `expectedContentHash`. " + COMPARISON_HASH_NOTE;
42871
42869
  async function fetchXml(path, options) {
42872
42870
  const q = options ? `?options=${encodeURIComponent(options)}` : "";
@@ -42985,8 +42983,7 @@ function registerAsCodeTools(server) {
42985
42983
  "tia_block_compare",
42986
42984
  {
42987
42985
  title: "TIA \u2014 compare a block with given SimaticML",
42988
- description: "Exports the block from the project and compares it with the SimaticML you pass (e.g. the file committed in git). Like tia_export_block, this may compile an inconsistent block first (export requires consistency), which can regenerate its instance DB; read-mostly, treated as read for agent tool policy. Normalized: ignores BOM, line endings, indentation, blank lines, <Created>, <InstalledProducts> and \u2014 unless ignoreFormatting:false \u2014 <NewLine/>/<Blank/> formatting tokens (see the result's `ignored` field for the exact list). UIds are renumbered by first appearance across definitions and references: rewiring differs, pure renumbering matches; UId-like text in comments and values is preserved. Returns verdict equal|different and the first differing line. " + COMPARISON_HASH_NOTE + // Stryker disable next-line StringLiteral: route explanation; compare-wiring.test.ts exercises the comparison flow
42989
- " This is the proof that the project contains what was versioned. Maps to GET /plcs/{plc}/blocks/{block}/xml. Engineering version and schema namespaces remain significant; equality is not cross-version import acceptance. " + LONG_OPERATION_NOTE,
42986
+ description: "Exports the block from the project and compares it with the SimaticML you pass (e.g. the file committed in git). Like tia_export_block, this may compile an inconsistent block first (export requires consistency), which can regenerate its instance DB; read-mostly, treated as read for agent tool policy. Normalized: ignores BOM, line endings, indentation, blank lines, <Created>, <InstalledProducts> and \u2014 unless ignoreFormatting:false \u2014 <NewLine/>/<Blank/> formatting tokens (see the result's `ignored` field for the exact list). UIds are renumbered by first appearance across definitions and references: rewiring differs, pure renumbering matches; UId-like text in comments and values is preserved. Returns verdict equal|different and the first differing line. " + COMPARISON_HASH_NOTE + " This is the proof that the project contains what was versioned. Maps to GET /plcs/{plc}/blocks/{block}/xml. Engineering version and schema namespaces remain significant; equality is not cross-version import acceptance. " + LONG_OPERATION_NOTE,
42990
42987
  inputSchema: {
42991
42988
  plc: external_exports.string().describe("PLC software name from tia_plcs.name, not the device station name"),
42992
42989
  block: external_exports.string().describe("block name"),
@@ -43001,12 +42998,8 @@ function registerAsCodeTools(server) {
43001
42998
  "tia_block_render",
43002
42999
  {
43003
43000
  title: "TIA \u2014 render a block as readable pseudo-SCL (LAD/FBD)",
43004
- description: (
43005
- // Stryker disable next-line StringLiteral: inline-input guidance prose; blockRender.test.ts covers path refusals and BOM XML
43006
- "Class R, pure/offline: never calls serve. Pass XML text, not a file path: use the inline xml field of tia_export_block {plc, block}. Renders ONE SimaticML block as readable pseudo-SCL: LAD/FBD contacts, coils, logic boxes, comparators, MOVE/arithmetic, timers, counters, edges and block calls become SCL-like statements; SCL networks are rebuilt from their tokens; STL/GRAPH networks are marked not rendered. A value read by several statements or assigned to several targets is evaluated once: held in an RLO_<UId> temporary (UId of the part producing it) or read back from the first coil that wrote it. A MOVE/arithmetic output read by another part is inlined only when the box is always enabled; otherwise IF <EN> THEN TMP_<UId> := <value>; END_IF; and the reader uses TMP_<UId>, which keeps its previous (stale) value when EN is false. The output or return value of ONE call is TMP_<UId>_<pin> when it has several targets or, for an FC (no instance), when another part reads it or it is negated: bound in the call (pin => TMP_<UId>_<pin>, or TMP_<UId>_<pin> := call(args); for the return value), and targets and readers copy from it; two calls never share one. A call with an instance and one target is direct or read as #inst.pin. An edge (P_TRIG/N_TRIG) runs every scan: used inside an IF <EN> body it is evaluated before the IF (RLO_<UId> := P_TRIG(...);), not conditional on that EN. A negated output pin shows as NOT (a negated instance or call output: a following line target := NOT #t.Q; under the same EN). TYPE#(x) is x read as TYPE: an absolute address of a non-natural type for its size shows its own type (INT#(%MW0)); a comparator, arithmetic box or Inc/Dec casts with the instruction type every operand but a constant, a boolean or one of that type, values forwarded by MOVE, a box or a call too (INT#(RLO_40), INT#(TMP_41)); constants and written places are never cast. What it cannot translate stays visible as (* unsupported: ... *) and is listed in unsupported, as are a duplicate UId, edge memory shared by several edge parts, a negated operand on an S/R/P/N coil and an invalid name or UId: that part is ambiguous, read it in the XML or report it as not reviewed. A network too large to render is marked not rendered and in unsupported (render budget). Hidden and bidirectional characters show as <U+XXXX>. For review only: not importable, layout not preserved, ENO shown as EN (errors not modeled). Returns {text, blocks, unsupported, note}."
43007
- ),
43001
+ description: "Class R, pure/offline: never calls serve. Pass XML text, not a file path: use the inline xml field of tia_export_block {plc, block}. Renders ONE SimaticML block as readable pseudo-SCL: LAD/FBD contacts, coils, logic boxes, comparators, MOVE/arithmetic, timers, counters, edges and block calls become SCL-like statements; SCL networks are rebuilt from their tokens; STL/GRAPH networks are marked not rendered. A value read by several statements or assigned to several targets is evaluated once: held in an RLO_<UId> temporary (UId of the part producing it) or read back from the first coil that wrote it. A MOVE/arithmetic output read by another part is inlined only when the box is always enabled; otherwise IF <EN> THEN TMP_<UId> := <value>; END_IF; and the reader uses TMP_<UId>, which keeps its previous (stale) value when EN is false. The output or return value of ONE call is TMP_<UId>_<pin> when it has several targets or, for an FC (no instance), when another part reads it or it is negated: bound in the call (pin => TMP_<UId>_<pin>, or TMP_<UId>_<pin> := call(args); for the return value), and targets and readers copy from it; two calls never share one. A call with an instance and one target is direct or read as #inst.pin. An edge (P_TRIG/N_TRIG) runs every scan: used inside an IF <EN> body it is evaluated before the IF (RLO_<UId> := P_TRIG(...);), not conditional on that EN. A negated output pin shows as NOT (a negated instance or call output: a following line target := NOT #t.Q; under the same EN). TYPE#(x) is x read as TYPE: an absolute address of a non-natural type for its size shows its own type (INT#(%MW0)); a comparator, arithmetic box or Inc/Dec casts with the instruction type every operand but a constant, a boolean or one of that type, values forwarded by MOVE, a box or a call too (INT#(RLO_40), INT#(TMP_41)); constants and written places are never cast. What it cannot translate stays visible as (* unsupported: ... *) and is listed in unsupported, as are a duplicate UId, edge memory shared by several edge parts, a negated operand on an S/R/P/N coil and an invalid name or UId: that part is ambiguous, read it in the XML or report it as not reviewed. A network too large to render is marked not rendered and in unsupported (render budget). Hidden and bidirectional characters show as <U+XXXX>. For review only: not importable, layout not preserved, ENO shown as EN (errors not modeled). Returns {text, blocks, unsupported, note}.",
43008
43002
  inputSchema: {
43009
- // Stryker disable next-line StringLiteral: input description prose; path validation and parsing stay in mutation scope
43010
43003
  xml: external_exports.string().describe("XML text of ONE SimaticML block export, NOT a file path. Get it from the inline xml field of tia_export_block {plc, block}")
43011
43004
  }
43012
43005
  },
@@ -43326,10 +43319,7 @@ var expectedContentHashField = {
43326
43319
  )
43327
43320
  };
43328
43321
  var UNGUARDED_WRITE_HINT = "expectedContentHash was sent but the serve did not return `contentGuard`: it does not implement the stale-write guard (an older serve \u2014 update the TIAOpenness app on the host), so this write was NOT guarded against changes made in the project after you read the object. Re-read it (tia_export_block / tia_export_type) and compare before relying on the result.";
43329
- var SOURCE_IMPACT_NOTE = (
43330
- // Stryker disable next-line StringLiteral: description-only receipt catalog and guide pointer; runtime decisions remain in scope
43331
- " Returns changeImpact/compileImpact (flags/members), memberCapture and readGaps (unknown); trackChanges:false skips observation. See tia_guide gotchas. "
43332
- );
43322
+ var SOURCE_IMPACT_NOTE = " Returns changeImpact/compileImpact (flags/members), memberCapture and readGaps (unknown); trackChanges:false skips observation. See tia_guide gotchas. ";
43333
43323
  function guardedSummary(summary, expectedContentHash) {
43334
43324
  return expectedContentHash === void 0 ? summary : `${summary}, guarded by expectedContentHash (verified by the serve only when the write really runs; dryRun never calls it)`;
43335
43325
  }
@@ -43451,11 +43441,8 @@ function registerAuthoringTools(server) {
43451
43441
  description: `Creates a device (CPU/HMI/IO) by typeIdentifier. Optional group is an existing device user-group path (Area/Line, case-insensitive); omitted means project level. For group, GET /status must advertise supportsDeviceGroupCreation:true (app 1.8.1+); older serves are refused before creation. Uses typed CreateWithItem, never the unsafe generic CreateDevices call. The successful receipt identifies the canonical group; missing or different placement is an error naming the created station when available: inspect before retrying, never retry automatically. A dryRun preview does not check serve support. The answer uses the station type identifier, falling back to the first readable DeviceItem.TypeIdentifier, including HMI panels. typeIdentifierSource is device, deviceItem or unavailable; unavailable metadata has typeIdentifier:null and an explicit typeIdentifierUnavailableReason. For a single-item device such as a Classic panel, set its name as deviceItemName and omit deviceName; deviceName is the station name and may be read-only. On 400 device_name_read_only, re-read GET /devices before retrying with only deviceItemName. Guard Gd5: '/V<fw>' (slash), never ':V' \u2014 resolve via tia_catalog. Maps to POST /devices. Class M-off. ${LONG_OPERATION_NOTE}`,
43452
43442
  inputSchema: {
43453
43443
  typeIdentifier: external_exports.string().describe("OrderNumber:<MLFB>/V<fw> (Gd5; resolve via tia_catalog)"),
43454
- // Stryker disable next-line StringLiteral: handoff prose, facts are tested
43455
43444
  deviceItemName: external_exports.string().optional().describe("device-item name; for an HMI, names the panel item (for a single-item device, use this as its name)"),
43456
- // Stryker disable next-line StringLiteral: handoff prose, facts are tested
43457
43445
  deviceName: external_exports.string().optional().describe("station name; may be read-only on some device types"),
43458
- // Stryker disable next-line StringLiteral: tool parameter documentation
43459
43446
  group: external_exports.string().optional().describe("existing device user-group path from the project root, e.g. Area/Line; omitted: project level (app 1.8.1+)"),
43460
43447
  ...dryRunField
43461
43448
  }
@@ -43707,10 +43694,7 @@ function registerAuthoringTools(server) {
43707
43694
  "tia_tag_create",
43708
43695
  {
43709
43696
  title: "TIA \u2014 create tag",
43710
- description: (
43711
- // Stryker disable next-line StringLiteral: refusal guidance prose; validation behavior is covered by PlcValidationTests
43712
- "App 1.8+ serve returns 400 bad_request (details.field, rule) for quote-bearing names or malformed/type-mismatched/out-of-range absolute addresses. Creates a tag in a table. Refused with 409 name_collision (details.collidesWith = the colliding tag, constant or block) when the name matches, ignoring case, any tag, constant or block of the PLC. The result carries `overlaps`: the OTHER tags whose logical address overlaps this one (informational, never a refusal). Maps to POST /plcs/{plc}/tags. M-off."
43713
- ),
43697
+ description: "App 1.8+ serve returns 400 bad_request (details.field, rule) for quote-bearing names or malformed/type-mismatched/out-of-range absolute addresses. Creates a tag in a table. Refused with 409 name_collision (details.collidesWith = the colliding tag, constant or block) when the name matches, ignoring case, any tag, constant or block of the PLC. The result carries `overlaps`: the OTHER tags whose logical address overlaps this one (informational, never a refusal). Maps to POST /plcs/{plc}/tags. M-off.",
43714
43698
  inputSchema: {
43715
43699
  plc: external_exports.string().describe("PLC software name from tia_plcs.name, not the device station name"),
43716
43700
  table: external_exports.string().optional().describe("tag table (default: the standard one)"),
@@ -43740,10 +43724,7 @@ function registerAuthoringTools(server) {
43740
43724
  "tia_tag_update",
43741
43725
  {
43742
43726
  title: "TIA \u2014 update tag",
43743
- description: (
43744
- // Stryker disable next-line StringLiteral: refusal guidance prose; validation behavior is covered by PlcValidationTests
43745
- "App 1.8+ serve returns 400 bad_request (details.field, rule) for quote-bearing names or malformed/type-mismatched/out-of-range absolute addresses, including previews. Updates ONE tag: rename, data type, logical address and the external accessible/visible/writable flags. Only the fields you pass change, and only those that differ from the current value are written (none passed: 400 missing_param; all unchanged: 200 with changes:[]). A rename is refused with 409 name_collision (details.collidesWith = the colliding tag, constant or block) when the new name matches, ignoring case, another tag, constant or block of the PLC; an unknown table or tag is 404 not_found. The result carries `changes` [{field,from,to}] and `overlaps`: the OTHER tags whose address overlaps the final one (informational, never a refusal). dryRun (Gd11) is answered by the serve (needs an open project): it runs the same guards and returns that plan WITHOUT changing anything. Maps to POST /plcs/{plc}/tagtables/{table}/tags/{tag}. M-off."
43746
- ),
43727
+ description: "App 1.8+ serve returns 400 bad_request (details.field, rule) for quote-bearing names or malformed/type-mismatched/out-of-range absolute addresses, including previews. Updates ONE tag: rename, data type, logical address and the external accessible/visible/writable flags. Only the fields you pass change, and only those that differ from the current value are written (none passed: 400 missing_param; all unchanged: 200 with changes:[]). A rename is refused with 409 name_collision (details.collidesWith = the colliding tag, constant or block) when the new name matches, ignoring case, another tag, constant or block of the PLC; an unknown table or tag is 404 not_found. The result carries `changes` [{field,from,to}] and `overlaps`: the OTHER tags whose address overlaps the final one (informational, never a refusal). dryRun (Gd11) is answered by the serve (needs an open project): it runs the same guards and returns that plan WITHOUT changing anything. Maps to POST /plcs/{plc}/tagtables/{table}/tags/{tag}. M-off.",
43747
43728
  inputSchema: {
43748
43729
  plc: external_exports.string().describe("PLC software name from tia_plcs.name, not the device station name"),
43749
43730
  table: external_exports.string().describe("tag table that holds the tag"),
@@ -43768,10 +43749,7 @@ function registerAuthoringTools(server) {
43768
43749
  "tia_constant_create",
43769
43750
  {
43770
43751
  title: "TIA \u2014 create constant",
43771
- description: (
43772
- // Stryker disable next-line StringLiteral: refusal guidance prose; validation behavior is covered by PlcValidationTests
43773
- "App 1.8+ serve returns 400 bad_request (details.field, rule) for quote-bearing names or invalid decimal integer literals; typed/radix literals pass through. Creates a user constant in a tag table. Refused with 409 name_collision (details.collidesWith = the colliding tag, constant or block) when the name matches, ignoring case, any tag, constant or block of the PLC. Maps to POST /plcs/{plc}/constants. M-off."
43774
- ),
43752
+ description: "App 1.8+ serve returns 400 bad_request (details.field, rule) for quote-bearing names or invalid decimal integer literals; typed/radix literals pass through. Creates a user constant in a tag table. Refused with 409 name_collision (details.collidesWith = the colliding tag, constant or block) when the name matches, ignoring case, any tag, constant or block of the PLC. Maps to POST /plcs/{plc}/constants. M-off.",
43775
43753
  inputSchema: {
43776
43754
  plc: external_exports.string().describe("PLC software name from tia_plcs.name, not the device station name"),
43777
43755
  table: external_exports.string().optional().describe("tag table (default: the standard one)"),
@@ -43787,10 +43765,7 @@ function registerAuthoringTools(server) {
43787
43765
  "tia_constant_update",
43788
43766
  {
43789
43767
  title: "TIA \u2014 update constant",
43790
- description: (
43791
- // Stryker disable next-line StringLiteral: refusal guidance prose; validation behavior is covered by PlcValidationTests
43792
- "App 1.8+ serve returns 400 bad_request (details.field, rule) for quote-bearing names or invalid decimal integer literals, including previews; typed/radix literals pass through. Updates ONE user constant: rename, data type and value. Only the fields you pass change, and only those that differ from the current value are written (none passed: 400 missing_param; all unchanged: 200 with changes:[]). A rename is refused with 409 name_collision (details.collidesWith = the colliding tag, constant or block) when the new name matches, ignoring case, another tag, constant or block of the PLC; an unknown table or constant is 404 not_found. dryRun (Gd11) is answered by the serve (needs an open project): it runs the same guards and returns the plan {changes:[{field,from,to}]} WITHOUT changing anything. Maps to POST /plcs/{plc}/tagtables/{table}/constants/{constant}. M-off."
43793
- ),
43768
+ description: "App 1.8+ serve returns 400 bad_request (details.field, rule) for quote-bearing names or invalid decimal integer literals, including previews; typed/radix literals pass through. Updates ONE user constant: rename, data type and value. Only the fields you pass change, and only those that differ from the current value are written (none passed: 400 missing_param; all unchanged: 200 with changes:[]). A rename is refused with 409 name_collision (details.collidesWith = the colliding tag, constant or block) when the new name matches, ignoring case, another tag, constant or block of the PLC; an unknown table or constant is 404 not_found. dryRun (Gd11) is answered by the serve (needs an open project): it runs the same guards and returns the plan {changes:[{field,from,to}]} WITHOUT changing anything. Maps to POST /plcs/{plc}/tagtables/{table}/constants/{constant}. M-off.",
43794
43769
  inputSchema: {
43795
43770
  plc: external_exports.string().describe("PLC software name from tia_plcs.name, not the device station name"),
43796
43771
  table: external_exports.string().describe("tag table that holds the constant"),
@@ -43981,10 +43956,7 @@ function registerAuthoringTools(server) {
43981
43956
  "tia_types_import",
43982
43957
  {
43983
43958
  title: "TIA \u2014 import type/UDT (SimaticML XML)",
43984
- description: (
43985
- // Stryker disable next-line StringLiteral: target-local UDT authoring guidance, not import validation
43986
- "Imports a UDT in SimaticML XML. Use a real export for the selected target; cross-version import compatibility is unverified, and V21 import behavior is unchanged (no new version preflight refusal). See tia_guide recipes, 'TIA version evidence and SimaticML'. Import UDTs BEFORE the blocks that use them (Gd6). Stale-write guard: pass the type's `contentHash` from tia_export_type (or tia_type_source) as `expectedContentHash` and the serve checks it against the type's current export BEFORE importing \u2014 a mismatch is 409 state_changed and NOTHING is imported; a match adds `contentGuard` to the result. " + HASH_CONTRACT_NOTE + " It guards exactly ONE type: the XML (or the file at `path`) must contain exactly one type (else 400 bad_request), and a hash for a type that does not exist (any more) is refused as state_changed \u2014 omit it to create; an existing type whose current export is not well-formed XML cannot be hashed and is refused with 409 unverifiable (NOTHING is imported; repair it, or omit expectedContentHash to write without the guard). " + SOURCE_IMPACT_NOTE + `Needs an app with the guard: an older serve ignores the field and the result says the import was NOT guarded. dryRun never verifies it. Maps to POST /plcs/{plc}/types/import. M-off. ${LONG_OPERATION_NOTE}`
43987
- ),
43959
+ description: "Imports a UDT in SimaticML XML. Use a real export for the selected target; cross-version import compatibility is unverified, and V21 import behavior is unchanged (no new version preflight refusal). See tia_guide recipes, 'TIA version evidence and SimaticML'. Import UDTs BEFORE the blocks that use them (Gd6). Stale-write guard: pass the type's `contentHash` from tia_export_type (or tia_type_source) as `expectedContentHash` and the serve checks it against the type's current export BEFORE importing \u2014 a mismatch is 409 state_changed and NOTHING is imported; a match adds `contentGuard` to the result. " + HASH_CONTRACT_NOTE + " It guards exactly ONE type: the XML (or the file at `path`) must contain exactly one type (else 400 bad_request), and a hash for a type that does not exist (any more) is refused as state_changed \u2014 omit it to create; an existing type whose current export is not well-formed XML cannot be hashed and is refused with 409 unverifiable (NOTHING is imported; repair it, or omit expectedContentHash to write without the guard). " + SOURCE_IMPACT_NOTE + `Needs an app with the guard: an older serve ignores the field and the result says the import was NOT guarded. dryRun never verifies it. Maps to POST /plcs/{plc}/types/import. M-off. ${LONG_OPERATION_NOTE}`,
43988
43960
  inputSchema: {
43989
43961
  plc: external_exports.string().describe("PLC software name from tia_plcs.name, not the device station name"),
43990
43962
  xml: external_exports.string().optional().describe("SimaticML XML content of the UDT (alternative to path)"),
@@ -44133,12 +44105,8 @@ function registerAssetTools(server) {
44133
44105
  "tia_device_from_mastercopy",
44134
44106
  {
44135
44107
  title: "TIA \u2014 station from a prepared master copy",
44136
- description: (
44137
- // Stryker disable next-line StringLiteral: handoff prose, not an executable contract
44138
- `Requires app \u2265 v1.8.0. Creates a new station from a device master copy in the open project's library (name from tia_library_mastercopies), returning {device: actualName}; TIA may rename the copy and its PLC. Known block-only content is refused with 409 mastercopy_not_device; unknown content goes to Openness. Clones an owner-prepared configuration, including PUT/GET, purchased-license selection and OPC UA interface mappings on the validated 1214C V4.4; it is not a setter for an existing CPU and does not grant license entitlement. Certificates are not copied: inspect the new OPC UA item, regenerate its server certificate if needed and compile before any human-gated download. Maps to POST /devices/frommastercopy {masterCopy}. Class M-off. ${LONG_OPERATION_NOTE}`
44139
- ),
44108
+ description: `Requires app \u2265 v1.8.0. Creates a new station from a device master copy in the open project's library (name from tia_library_mastercopies), returning {device: actualName}; TIA may rename the copy and its PLC. Known block-only content is refused with 409 mastercopy_not_device; unknown content goes to Openness. Clones an owner-prepared configuration, including PUT/GET, purchased-license selection and OPC UA interface mappings on the validated 1214C V4.4; it is not a setter for an existing CPU and does not grant license entitlement. Certificates are not copied: inspect the new OPC UA item, regenerate its server certificate if needed and compile before any human-gated download. Maps to POST /devices/frommastercopy {masterCopy}. Class M-off. ${LONG_OPERATION_NOTE}`,
44140
44109
  inputSchema: {
44141
- // Stryker disable next-line StringLiteral: schema description prose; validation stays in mutation scope
44142
44110
  masterCopy: external_exports.string().min(1).describe("owner-prepared device master copy in the project library"),
44143
44111
  ...dryRunField
44144
44112
  }
@@ -44968,6 +44936,129 @@ function registerVciTools(server) {
44968
44936
  );
44969
44937
  }
44970
44938
 
44939
+ // src/tools/sd.ts
44940
+ var SD_KINDS = ["block", "type"];
44941
+ var SD_DB_FLAGS = ["IsOnlyStoredInLoadMemory", "IsWriteProtectedInAS", "DBAccessibleFromOPCUA"];
44942
+ function sdWriterRules() {
44943
+ return "Text rules (TIA V21): comments only through the .s7res texts: `//` inside a LAD/FBD network is refused (in SCL networks it is an ordinary comment); quote a YAML value that contains `:` or `#`; FBD: a `wire#` consumer rung comes before its producer rung and every box output pin is listed (an empty `et =>` is allowed).";
44944
+ }
44945
+ function sdQuotingNote() {
44946
+ return 'TIA re-quotes some identifiers on export (`a` returns as "a"): compare ignoring quotes.';
44947
+ }
44948
+ function sdObNote() {
44949
+ return "OBs: an existing OB of ANY event class is refused (409 sd_existing_ob_unsupported): TIA gives every OB imported from SD a new number (a ProgramCycle OB 123 came back as OB 1), even with S7_BlockNumber; use tia_export_block and tia_import_xml to change one and keep its number and event class. A new OB from SD becomes ProgramCycle, numbered by TIA; the receipt (blocks[0].number, eventClass) names them when it could be read (blocks null with receiptError otherwise).";
44950
+ }
44951
+ function sdDbNote() {
44952
+ return `Global DBs: the text carries no ${SD_DB_FLAGS.join(", ")}, so an import resets all three; changeImpact.dbAttributeChanges reports them and nothing is restored: IsOnlyStoredInLoadMemory and IsWriteProtectedInAS can be restored with tia_block_set_attribute; DBAccessibleFromOPCUA is set again by a person in TIA Portal (the block's properties) when that route refuses it; then compile.`;
44953
+ }
44954
+ function exportSdPath({ plc, kind, name }) {
44955
+ return `/plcs/${seg(plc)}/${kind === "block" ? "blocks" : "types"}/${seg(name)}/sd`;
44956
+ }
44957
+ async function exportSdFlow(args) {
44958
+ try {
44959
+ const data = await tiaFetch(exportSdPath(args), {}, { timeoutMs: LONG_OPERATION_TIMEOUT_MS });
44960
+ if (!isObject2(data)) return textResult(data);
44961
+ return textResult({
44962
+ ...data,
44963
+ hashNote: "contentHash is the stale-write hash of the SimaticML export of the same object (the one tia_export_block and tia_export_type return), not a hash of this text: pass it as expectedContentHash to tia_import_sd. s7dclBytes and s7resBytes count the UTF-8 text as returned (no BOM, line endings as TIA wrote them: CRLF).",
44964
+ ...typeof data.contentHash === "string" ? {} : {
44965
+ nextHints: [
44966
+ "contentHash is null: contentHashError says why (the object changed while it was exported, or the block is not consistent). Export it again, or compile the block first, before importing with a guard; never pass another hash as expectedContentHash."
44967
+ ]
44968
+ }
44969
+ });
44970
+ } catch (e) {
44971
+ return errorResult(asTiaError(e));
44972
+ }
44973
+ }
44974
+ var IMPORT_SD_HINTS = {
44975
+ state_changed: "The object changed in the project after it was read, so the stale-write guard refused the import and NOTHING was written (details.expected = the hash you sent, details.actual = the current one; null means the object no longer exists). Re-read it with tia_export_sd, merge your edit onto the current s7dcl and s7res it returns, and only then retry with the new contentHash as expectedContentHash. " + HASH_CONTRACT_NOTE,
44976
+ sd_existing_ob_unsupported: "NOTHING was written. TIA gives every OB imported from SD a new number and makes it a ProgramCycle OB, whatever it was (details.block, details.eventClass: null when it could not be read). An OB keeps its number and event class only through SimaticML: tia_export_block, edit, tia_import_xml. A new OB can still be created with tia_import_sd.",
44977
+ sd_import_failed: "TIA refused the text (details.messages carries its own words). details.changed:false means the project object is as it was; null means it could not be verified, so re-read it with tia_export_sd before retrying. Fix the text and send it again. " + sdWriterRules(),
44978
+ sd_import_partial: "TIA applied only part of the text: the object may have changed. Re-read it with tia_export_sd and compare before retrying.",
44979
+ sd_import_unverified: "TIA reported an import but the project has no object of that name afterwards. Read the project (tia_plc_blocks, tia_plc_types) before repeating.",
44980
+ sd_declaration_mismatch: "NOTHING was written. TIA takes the object from the declaration inside the .s7dcl text: it must declare exactly the one block or type named by kind and name."
44981
+ };
44982
+ async function importSdFlow(args) {
44983
+ const body = jsonBody({
44984
+ kind: args.kind,
44985
+ name: args.name,
44986
+ s7dcl: args.s7dcl,
44987
+ s7res: args.s7res,
44988
+ group: args.group,
44989
+ expectedContentHash: args.expectedContentHash
44990
+ });
44991
+ const r = await serveMutate("POST", `/plcs/${seg(args.plc)}/sd/import`, body, {
44992
+ dryRun: args.dryRun,
44993
+ timeoutMs: LONG_OPERATION_TIMEOUT_MS,
44994
+ hints: IMPORT_SD_HINTS
44995
+ });
44996
+ if (args.dryRun || r.isError) return r;
44997
+ const data = JSON.parse(r.content[0].text);
44998
+ if (!isObject2(data)) return r;
44999
+ const nextHints = [
45000
+ "The imported object is inconsistent until it is compiled: compile (tia_block_compile for a block, tia_compile for the PLC) and read the messages before relying on it.",
45001
+ ...sourceImpactHints(data),
45002
+ ...unguardedWriteHints(args.expectedContentHash, data)
45003
+ ];
45004
+ if (typeof data.receiptError === "string" && data.receiptError.trim()) {
45005
+ nextHints.push(
45006
+ `receiptError: the serve could not build the block receipt (${data.receiptError.trim()}); the import itself succeeded ('imported' is real). Verify with tia_export_sd.`
45007
+ );
45008
+ }
45009
+ const first = Array.isArray(data.blocks) && isObject2(data.blocks[0]) ? data.blocks[0] : void 0;
45010
+ if (first !== void 0 && first.created === true && typeof first.eventClass === "string") {
45011
+ nextHints.push(`A new OB from SD is a ProgramCycle OB: TIA gave it number ${String(first.number)}; use tia_ob_create for another event class.`);
45012
+ }
45013
+ return textResult({ ...data, nextHints });
45014
+ }
45015
+ function registerSdTools(server) {
45016
+ const kindInput = external_exports.enum(SD_KINDS).describe("block (OB, FB, FC, global or instance DB) or type (a PLC data type)");
45017
+ const plcInput = external_exports.string().describe("PLC software name from tia_plcs.name, not the device station name");
45018
+ server.registerTool(
45019
+ "tia_export_sd",
45020
+ {
45021
+ title: "TIA \u2014 export one block or type (SIMATIC SD, inline)",
45022
+ description: `Exports ONE block (OB, FB, FC, DB) or PLC data type as SIMATIC SD text, INLINE: \`s7dcl\` (the code; LAD/FBD as NETWORK ... RUNG text) and \`s7res\` (YAML texts; null when TIA wrote none) with byte counts, state, messages and \`contentHash\`: the SAME stale-write hash tia_export_block and tia_export_type return (null with contentHashError when the block is not consistent or the object changed while it was exported: read it again), to pass as expectedContentHash to tia_import_sd; it is not a hash of this text, never substitute another hash. TIA V20+ (types V21+). Never compiles or changes the project (it works in a scratch folder on the serve host, removed best effort: one that cannot be removed stays in the temp folder, unlogged). 404 not_found; 409 inconsistent (a type), know_how_protected, sd_export_failed (details.state, details.messages: TIA's own words), sd_not_supported. ${sdQuotingNote()} Maps to GET /plcs/{plc}/blocks/{block}/sd and /plcs/{plc}/types/{type}/sd. Class R. ` + LONG_OPERATION_NOTE,
45023
+ inputSchema: {
45024
+ plc: plcInput,
45025
+ kind: kindInput,
45026
+ name: external_exports.string().min(1).describe("block or type name")
45027
+ }
45028
+ },
45029
+ async ({ plc, kind, name }) => {
45030
+ const args = { plc, kind, name };
45031
+ return jobs.run("tia_export_sd", args, () => exportSdFlow(args));
45032
+ }
45033
+ );
45034
+ server.registerTool(
45035
+ "tia_import_sd",
45036
+ {
45037
+ title: "TIA \u2014 create or replace one block or type from SIMATIC SD text",
45038
+ description: `Creates or REPLACES ONE block or PLC data type from SIMATIC SD text (\`s7dcl\`, plus \`s7res\` YAML texts). The only way to create a block or type from SD text (the VCI tools update mapped objects only). An existing object is replaced where it lives; a new one goes to the root group or to \`group\` (an existing user group, '/'-separated; 404 not_found if missing). No undo. The text must declare exactly the object named by kind and name (400 sd_declaration_mismatch). ${sdObNote()} ${sdDbNote()} ${sdWriterRules()} Checked before anything is written, in a dryRun too (plan: action create|replace, group, dbFlagsReset): expectedContentHash (from tia_export_sd, tia_export_block or tia_export_type: a different current hash is 409 state_changed, an inconsistent object 409 inconsistent; a match returns contentGuard), 409 sd_kind_mismatch, 409 sd_group_mismatch, 409 know_how_protected, 409 name_collision (new block). TIA's refusal of the text is 400 sd_import_failed with its messages (details.changed false = nothing changed, null = unverified), a partly applied one 409 sd_import_partial: never reported as done. The object comes back inconsistent: compile before download. dryRun first (Gd11). Maps to POST /plcs/{plc}/sd/import. Class M-off. ` + LONG_OPERATION_NOTE,
45039
+ inputSchema: {
45040
+ plc: plcInput,
45041
+ kind: kindInput,
45042
+ name: external_exports.string().min(1).describe("name of the block or type the text declares"),
45043
+ s7dcl: external_exports.string().min(1).describe("the text of the .s7dcl file (LF or CRLF; the serve writes it as UTF-8 with BOM and CRLF)"),
45044
+ s7res: external_exports.string().min(1).optional().describe("the text of the .s7res file (YAML multilingual texts); omit when the object has none"),
45045
+ group: external_exports.string().min(1).optional().describe("user group for an object that does not exist yet ('/'-separated); omit for the root; for an existing object omit it or name the group it lives in"),
45046
+ expectedContentHash: external_exports.string().regex(
45047
+ CONTENT_HASH_PATTERN,
45048
+ "expectedContentHash must be exactly 64 hexadecimal characters: a contentHash returned by tia_export_sd, tia_export_block or tia_export_type"
45049
+ ).optional().describe(
45050
+ "Stale-write guard (optional): the `contentHash` of the object as you last read it (64 hex characters). The serve verifies it before writing, in a dryRun too. Omit it when creating a new object."
45051
+ ),
45052
+ ...dryRunField
45053
+ }
45054
+ },
45055
+ async ({ plc, kind, name, s7dcl, s7res, group, expectedContentHash, dryRun }) => {
45056
+ const args = { plc, kind, name, s7dcl, s7res, group, expectedContentHash, dryRun };
45057
+ return jobs.run("tia_import_sd", args, () => importSdFlow(args));
45058
+ }
45059
+ );
45060
+ }
45061
+
44971
45062
  // src/tools/security.ts
44972
45063
  var CERTIFICATE_USAGES = ["Tls", "WebServer", "OpcUaServer", "OpcUaClient", "OpcUaClientServer"];
44973
45064
  var SECRET_FIELDS = ["password"];
@@ -46365,6 +46456,7 @@ function buildServer(mode, version2, budget = resolveBudget()) {
46365
46456
  registerMultiuserTools(server);
46366
46457
  registerHmiUnifiedTools(server);
46367
46458
  registerVciTools(server);
46459
+ registerSdTools(server);
46368
46460
  registerSecurityTools(server);
46369
46461
  registerCompileTools(server);
46370
46462
  registerDownloadTools(server);
@@ -46375,7 +46467,7 @@ function buildServer(mode, version2, budget = resolveBudget()) {
46375
46467
  }
46376
46468
 
46377
46469
  // src/index.ts
46378
- var VERSION = "1.12.3";
46470
+ var VERSION = "1.13.1";
46379
46471
  async function main() {
46380
46472
  if (process.argv.slice(2).some((a) => a === "--version" || a === "-v")) {
46381
46473
  console.log(VERSION);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@renanlido/tia-openness-mcp",
3
- "version": "1.12.3",
3
+ "version": "1.13.1",
4
4
  "description": "MCP server (stdio) — thin HTTP client over the TIA Openness `serve` API. Zero Openness/net48 references.",
5
5
  "mcpName": "io.github.renanlido/tia-openness",
6
6
  "keywords": [