@renanlido/tia-openness-mcp 1.12.3 → 1.13.0

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 +135 -3
  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
@@ -29226,7 +29226,7 @@ var GATES_GUARDS = '# Gates vs guards\n\n## GATES vs GUARDS\n\n- **GATES (human-
29226
29226
  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
29227
  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
29228
  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';
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## 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
29230
  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
29231
  var FULL_GUIDE = [BRIEF, GATES_GUARDS, GUI_GATES, GOTCHAS, PIPELINE, RECIPES, SPEC_FORMAT].join("\n---\n\n");
29232
29232
  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 +37434,10 @@ function resolveBudget(getEnv = (name) => process.env[name]) {
37434
37434
  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
37435
  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
37436
  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.";
37437
+ var EXPORT_SD_HINT = (
37438
+ // Stryker disable next-line StringLiteral: static module constant, evaluated once at import; budget.test.ts pins every sentence of the delivered hint
37439
+ "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."
37440
+ );
37437
37441
  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
37442
  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
37443
  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 +37476,7 @@ var TOOL_HINTS = {
37472
37476
  tia_io_map: { unpaged: IOMAP_HINT, paged: PAGED_HINT },
37473
37477
  tia_export_block: EXPORT_XML_HINT,
37474
37478
  tia_export_type: EXPORT_XML_HINT,
37479
+ tia_export_sd: EXPORT_SD_HINT,
37475
37480
  tia_catalog: "Pass a more specific filter/typeIdentifier and keep verbose off.",
37476
37481
  tia_compile: "Compile one block with tia_block_compile, or read messages from the compile result summary."
37477
37482
  };
@@ -37774,6 +37779,7 @@ var tool_classes_default = {
37774
37779
  tia_disconnect: "M-off",
37775
37780
  tia_download: "GATE",
37776
37781
  tia_export_block: "M-off",
37782
+ tia_export_sd: "R",
37777
37783
  tia_export_type: "R",
37778
37784
  tia_export_xml: "M-off",
37779
37785
  tia_fb_create: "M-off",
@@ -37802,6 +37808,7 @@ var tool_classes_default = {
37802
37808
  tia_hmi_tags: "R",
37803
37809
  tia_hmi_validate: "R",
37804
37810
  tia_hmis: "R",
37811
+ tia_import_sd: "M-off",
37805
37812
  tia_import_xml: "M-off",
37806
37813
  tia_instancedb_create: "M-off",
37807
37814
  tia_instances: "R",
@@ -37906,6 +37913,7 @@ var tool_classes_default = {
37906
37913
  "tia_device_network",
37907
37914
  "tia_device_tree",
37908
37915
  "tia_devices",
37916
+ "tia_export_sd",
37909
37917
  "tia_export_type",
37910
37918
  "tia_global_libraries",
37911
37919
  "tia_guide",
@@ -38106,7 +38114,7 @@ function registerJobTools(server) {
38106
38114
  "tia_job_status",
38107
38115
  {
38108
38116
  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.',
38117
+ 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
38118
  inputSchema: {
38111
38119
  jobId: external_exports.string().describe("jobId returned by the long tool (or by a busy error's details.jobId)"),
38112
38120
  waitSeconds: external_exports.number().int().min(0).max(25).optional().describe("how long this call may wait (default 20, max 25)")
@@ -44968,6 +44976,129 @@ function registerVciTools(server) {
44968
44976
  );
44969
44977
  }
44970
44978
 
44979
+ // src/tools/sd.ts
44980
+ var SD_KINDS = ["block", "type"];
44981
+ var SD_DB_FLAGS = ["IsOnlyStoredInLoadMemory", "IsWriteProtectedInAS", "DBAccessibleFromOPCUA"];
44982
+ function sdWriterRules() {
44983
+ 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).";
44984
+ }
44985
+ function sdQuotingNote() {
44986
+ return 'TIA re-quotes some identifiers on export (`a` returns as "a"): compare ignoring quotes.';
44987
+ }
44988
+ function sdObNote() {
44989
+ 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).";
44990
+ }
44991
+ function sdDbNote() {
44992
+ 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.`;
44993
+ }
44994
+ function exportSdPath({ plc, kind, name }) {
44995
+ return `/plcs/${seg(plc)}/${kind === "block" ? "blocks" : "types"}/${seg(name)}/sd`;
44996
+ }
44997
+ async function exportSdFlow(args) {
44998
+ try {
44999
+ const data = await tiaFetch(exportSdPath(args), {}, { timeoutMs: LONG_OPERATION_TIMEOUT_MS });
45000
+ if (!isObject2(data)) return textResult(data);
45001
+ return textResult({
45002
+ ...data,
45003
+ 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).",
45004
+ ...typeof data.contentHash === "string" ? {} : {
45005
+ nextHints: [
45006
+ "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."
45007
+ ]
45008
+ }
45009
+ });
45010
+ } catch (e) {
45011
+ return errorResult(asTiaError(e));
45012
+ }
45013
+ }
45014
+ var IMPORT_SD_HINTS = {
45015
+ 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,
45016
+ 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.",
45017
+ 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(),
45018
+ 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.",
45019
+ 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.",
45020
+ 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."
45021
+ };
45022
+ async function importSdFlow(args) {
45023
+ const body = jsonBody({
45024
+ kind: args.kind,
45025
+ name: args.name,
45026
+ s7dcl: args.s7dcl,
45027
+ s7res: args.s7res,
45028
+ group: args.group,
45029
+ expectedContentHash: args.expectedContentHash
45030
+ });
45031
+ const r = await serveMutate("POST", `/plcs/${seg(args.plc)}/sd/import`, body, {
45032
+ dryRun: args.dryRun,
45033
+ timeoutMs: LONG_OPERATION_TIMEOUT_MS,
45034
+ hints: IMPORT_SD_HINTS
45035
+ });
45036
+ if (args.dryRun || r.isError) return r;
45037
+ const data = JSON.parse(r.content[0].text);
45038
+ if (!isObject2(data)) return r;
45039
+ const nextHints = [
45040
+ "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.",
45041
+ ...sourceImpactHints(data),
45042
+ ...unguardedWriteHints(args.expectedContentHash, data)
45043
+ ];
45044
+ if (typeof data.receiptError === "string" && data.receiptError.trim()) {
45045
+ nextHints.push(
45046
+ `receiptError: the serve could not build the block receipt (${data.receiptError.trim()}); the import itself succeeded ('imported' is real). Verify with tia_export_sd.`
45047
+ );
45048
+ }
45049
+ const first = Array.isArray(data.blocks) && isObject2(data.blocks[0]) ? data.blocks[0] : void 0;
45050
+ if (first !== void 0 && first.created === true && typeof first.eventClass === "string") {
45051
+ 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.`);
45052
+ }
45053
+ return textResult({ ...data, nextHints });
45054
+ }
45055
+ function registerSdTools(server) {
45056
+ const kindInput = external_exports.enum(SD_KINDS).describe("block (OB, FB, FC, global or instance DB) or type (a PLC data type)");
45057
+ const plcInput = external_exports.string().describe("PLC software name from tia_plcs.name, not the device station name");
45058
+ server.registerTool(
45059
+ "tia_export_sd",
45060
+ {
45061
+ title: "TIA \u2014 export one block or type (SIMATIC SD, inline)",
45062
+ 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,
45063
+ inputSchema: {
45064
+ plc: plcInput,
45065
+ kind: kindInput,
45066
+ name: external_exports.string().min(1).describe("block or type name")
45067
+ }
45068
+ },
45069
+ async ({ plc, kind, name }) => {
45070
+ const args = { plc, kind, name };
45071
+ return jobs.run("tia_export_sd", args, () => exportSdFlow(args));
45072
+ }
45073
+ );
45074
+ server.registerTool(
45075
+ "tia_import_sd",
45076
+ {
45077
+ title: "TIA \u2014 create or replace one block or type from SIMATIC SD text",
45078
+ 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,
45079
+ inputSchema: {
45080
+ plc: plcInput,
45081
+ kind: kindInput,
45082
+ name: external_exports.string().min(1).describe("name of the block or type the text declares"),
45083
+ 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)"),
45084
+ s7res: external_exports.string().min(1).optional().describe("the text of the .s7res file (YAML multilingual texts); omit when the object has none"),
45085
+ 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"),
45086
+ expectedContentHash: external_exports.string().regex(
45087
+ CONTENT_HASH_PATTERN,
45088
+ "expectedContentHash must be exactly 64 hexadecimal characters: a contentHash returned by tia_export_sd, tia_export_block or tia_export_type"
45089
+ ).optional().describe(
45090
+ "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."
45091
+ ),
45092
+ ...dryRunField
45093
+ }
45094
+ },
45095
+ async ({ plc, kind, name, s7dcl, s7res, group, expectedContentHash, dryRun }) => {
45096
+ const args = { plc, kind, name, s7dcl, s7res, group, expectedContentHash, dryRun };
45097
+ return jobs.run("tia_import_sd", args, () => importSdFlow(args));
45098
+ }
45099
+ );
45100
+ }
45101
+
44971
45102
  // src/tools/security.ts
44972
45103
  var CERTIFICATE_USAGES = ["Tls", "WebServer", "OpcUaServer", "OpcUaClient", "OpcUaClientServer"];
44973
45104
  var SECRET_FIELDS = ["password"];
@@ -46365,6 +46496,7 @@ function buildServer(mode, version2, budget = resolveBudget()) {
46365
46496
  registerMultiuserTools(server);
46366
46497
  registerHmiUnifiedTools(server);
46367
46498
  registerVciTools(server);
46499
+ registerSdTools(server);
46368
46500
  registerSecurityTools(server);
46369
46501
  registerCompileTools(server);
46370
46502
  registerDownloadTools(server);
@@ -46375,7 +46507,7 @@ function buildServer(mode, version2, budget = resolveBudget()) {
46375
46507
  }
46376
46508
 
46377
46509
  // src/index.ts
46378
- var VERSION = "1.12.3";
46510
+ var VERSION = "1.13.0";
46379
46511
  async function main() {
46380
46512
  if (process.argv.slice(2).some((a) => a === "--version" || a === "-v")) {
46381
46513
  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.0",
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": [